DeclBase.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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/DeclOpenMP.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/DependentDiagnostic.h"
  25. #include "clang/AST/ExternalASTSource.h"
  26. #include "clang/AST/Stmt.h"
  27. #include "clang/AST/StmtCXX.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <algorithm>
  33. #include "llvm/Support/OacrIgnoreCond.h" // HLSL Change - options change visibility rules
  34. using namespace clang;
  35. //===----------------------------------------------------------------------===//
  36. // Statistics
  37. //===----------------------------------------------------------------------===//
  38. #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
  39. #define ABSTRACT_DECL(DECL)
  40. #include "clang/AST/DeclNodes.inc"
  41. void Decl::updateOutOfDate(IdentifierInfo &II) const {
  42. getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
  43. }
  44. void *Decl::operator new(std::size_t Size, const ASTContext &Context,
  45. unsigned ID, std::size_t Extra) {
  46. // Allocate an extra 8 bytes worth of storage, which ensures that the
  47. // resulting pointer will still be 8-byte aligned.
  48. void *Start = Context.Allocate(Size + Extra + 8);
  49. void *Result = (char*)Start + 8;
  50. unsigned *PrefixPtr = (unsigned *)Result - 2;
  51. // Zero out the first 4 bytes; this is used to store the owning module ID.
  52. PrefixPtr[0] = 0;
  53. // Store the global declaration ID in the second 4 bytes.
  54. PrefixPtr[1] = ID;
  55. return Result;
  56. }
  57. void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
  58. DeclContext *Parent, std::size_t Extra) {
  59. assert(!Parent || &Parent->getParentASTContext() == &Ctx);
  60. // With local visibility enabled, we track the owning module even for local
  61. // declarations.
  62. if (Ctx.getLangOpts().ModulesLocalVisibility) {
  63. void *Buffer = ::operator new(sizeof(Module *) + Size + Extra, Ctx);
  64. return new (Buffer) Module*(nullptr) + 1;
  65. }
  66. return ::operator new(Size + Extra, Ctx);
  67. }
  68. Module *Decl::getOwningModuleSlow() const {
  69. assert(isFromASTFile() && "Not from AST file?");
  70. return getASTContext().getExternalSource()->getModule(getOwningModuleID());
  71. }
  72. bool Decl::hasLocalOwningModuleStorage() const {
  73. return getASTContext().getLangOpts().ModulesLocalVisibility;
  74. }
  75. const char *Decl::getDeclKindName() const {
  76. switch (DeclKind) {
  77. default: llvm_unreachable("Declaration not in DeclNodes.inc!");
  78. #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
  79. #define ABSTRACT_DECL(DECL)
  80. #include "clang/AST/DeclNodes.inc"
  81. }
  82. }
  83. void Decl::setInvalidDecl(bool Invalid) {
  84. InvalidDecl = Invalid;
  85. assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
  86. if (Invalid && !isa<ParmVarDecl>(this)) {
  87. // Defensive maneuver for ill-formed code: we're likely not to make it to
  88. // a point where we set the access specifier, so default it to "public"
  89. // to avoid triggering asserts elsewhere in the front end.
  90. setAccess(AS_public);
  91. }
  92. }
  93. const char *DeclContext::getDeclKindName() const {
  94. switch (DeclKind) {
  95. default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
  96. #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
  97. #define ABSTRACT_DECL(DECL)
  98. #include "clang/AST/DeclNodes.inc"
  99. }
  100. }
  101. bool Decl::StatisticsEnabled = false;
  102. void Decl::EnableStatistics() {
  103. StatisticsEnabled = true;
  104. }
  105. void Decl::PrintStats() {
  106. llvm::errs() << "\n*** Decl Stats:\n";
  107. int totalDecls = 0;
  108. #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
  109. #define ABSTRACT_DECL(DECL)
  110. #include "clang/AST/DeclNodes.inc"
  111. llvm::errs() << " " << totalDecls << " decls total.\n";
  112. int totalBytes = 0;
  113. #define DECL(DERIVED, BASE) \
  114. if (n##DERIVED##s > 0) { \
  115. totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
  116. llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
  117. << sizeof(DERIVED##Decl) << " each (" \
  118. << n##DERIVED##s * sizeof(DERIVED##Decl) \
  119. << " bytes)\n"; \
  120. }
  121. #define ABSTRACT_DECL(DECL)
  122. #include "clang/AST/DeclNodes.inc"
  123. llvm::errs() << "Total bytes = " << totalBytes << "\n";
  124. }
  125. void Decl::add(Kind k) {
  126. switch (k) {
  127. #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
  128. #define ABSTRACT_DECL(DECL)
  129. #include "clang/AST/DeclNodes.inc"
  130. }
  131. }
  132. bool Decl::isTemplateParameterPack() const {
  133. if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
  134. return TTP->isParameterPack();
  135. if (const NonTypeTemplateParmDecl *NTTP
  136. = dyn_cast<NonTypeTemplateParmDecl>(this))
  137. return NTTP->isParameterPack();
  138. if (const TemplateTemplateParmDecl *TTP
  139. = dyn_cast<TemplateTemplateParmDecl>(this))
  140. return TTP->isParameterPack();
  141. return false;
  142. }
  143. bool Decl::isParameterPack() const {
  144. if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
  145. return Parm->isParameterPack();
  146. return isTemplateParameterPack();
  147. }
  148. FunctionDecl *Decl::getAsFunction() {
  149. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
  150. return FD;
  151. if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
  152. return FTD->getTemplatedDecl();
  153. return nullptr;
  154. }
  155. bool Decl::isTemplateDecl() const {
  156. return isa<TemplateDecl>(this);
  157. }
  158. const DeclContext *Decl::getParentFunctionOrMethod() const {
  159. for (const DeclContext *DC = getDeclContext();
  160. DC && !DC->isTranslationUnit() && !DC->isNamespace();
  161. DC = DC->getParent())
  162. if (DC->isFunctionOrMethod())
  163. return DC;
  164. return nullptr;
  165. }
  166. //===----------------------------------------------------------------------===//
  167. // PrettyStackTraceDecl Implementation
  168. //===----------------------------------------------------------------------===//
  169. void PrettyStackTraceDecl::print(raw_ostream &OS) const {
  170. SourceLocation TheLoc = Loc;
  171. if (TheLoc.isInvalid() && TheDecl)
  172. TheLoc = TheDecl->getLocation();
  173. if (TheLoc.isValid()) {
  174. TheLoc.print(OS, SM);
  175. OS << ": ";
  176. }
  177. OS << Message;
  178. if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
  179. OS << " '";
  180. DN->printQualifiedName(OS);
  181. OS << '\'';
  182. }
  183. OS << '\n';
  184. }
  185. //===----------------------------------------------------------------------===//
  186. // Decl Implementation
  187. //===----------------------------------------------------------------------===//
  188. // Out-of-line virtual method providing a home for Decl.
  189. Decl::~Decl() { }
  190. void Decl::setDeclContext(DeclContext *DC) {
  191. DeclCtx = DC;
  192. }
  193. void Decl::setLexicalDeclContext(DeclContext *DC) {
  194. if (DC == getLexicalDeclContext())
  195. return;
  196. if (isInSemaDC()) {
  197. setDeclContextsImpl(getDeclContext(), DC, getASTContext());
  198. } else {
  199. getMultipleDC()->LexicalDC = DC;
  200. }
  201. Hidden = cast<Decl>(DC)->Hidden;
  202. }
  203. void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
  204. ASTContext &Ctx) {
  205. if (SemaDC == LexicalDC) {
  206. DeclCtx = SemaDC;
  207. } else {
  208. Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
  209. MDC->SemanticDC = SemaDC;
  210. MDC->LexicalDC = LexicalDC;
  211. DeclCtx = MDC;
  212. }
  213. }
  214. /// HLSL Change Begin - back port from llvm-project/73c6a2448f24 & f721e0582b15.
  215. bool Decl::isInLocalScopeForInstantiation() const {
  216. const DeclContext *LDC = getLexicalDeclContext();
  217. if (!LDC->isDependentContext())
  218. return false;
  219. while (true) {
  220. if (LDC->isFunctionOrMethod())
  221. return true;
  222. if (!isa<TagDecl>(LDC))
  223. return false;
  224. if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
  225. if (CRD->isLambda())
  226. return true;
  227. LDC = LDC->getLexicalParent();
  228. }
  229. return false;
  230. }
  231. /// HLSL Change End - back port from llvm-project/73c6a2448f24 & f721e0582b15.
  232. bool Decl::isInAnonymousNamespace() const {
  233. const DeclContext *DC = getDeclContext();
  234. do {
  235. if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
  236. if (ND->isAnonymousNamespace())
  237. return true;
  238. } while ((DC = DC->getParent()));
  239. return false;
  240. }
  241. bool Decl::isInStdNamespace() const {
  242. return getDeclContext()->isStdNamespace();
  243. }
  244. TranslationUnitDecl *Decl::getTranslationUnitDecl() {
  245. if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
  246. return TUD;
  247. DeclContext *DC = getDeclContext();
  248. assert(DC && "This decl is not contained in a translation unit!");
  249. while (!DC->isTranslationUnit()) {
  250. DC = DC->getParent();
  251. assert(DC && "This decl is not contained in a translation unit!");
  252. }
  253. return cast<TranslationUnitDecl>(DC);
  254. }
  255. ASTContext &Decl::getASTContext() const {
  256. return getTranslationUnitDecl()->getASTContext();
  257. }
  258. ASTMutationListener *Decl::getASTMutationListener() const {
  259. return getASTContext().getASTMutationListener();
  260. }
  261. unsigned Decl::getMaxAlignment() const {
  262. if (!hasAttrs())
  263. return 0;
  264. unsigned Align = 0;
  265. const AttrVec &V = getAttrs();
  266. ASTContext &Ctx = getASTContext();
  267. specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
  268. for (; I != E; ++I)
  269. Align = std::max(Align, I->getAlignment(Ctx));
  270. return Align;
  271. }
  272. bool Decl::isUsed(bool CheckUsedAttr) const {
  273. if (Used)
  274. return true;
  275. // Check for used attribute.
  276. if (CheckUsedAttr && hasAttr<UsedAttr>())
  277. return true;
  278. return false;
  279. }
  280. void Decl::markUsed(ASTContext &C) {
  281. if (Used)
  282. return;
  283. if (C.getASTMutationListener())
  284. C.getASTMutationListener()->DeclarationMarkedUsed(this);
  285. Used = true;
  286. }
  287. bool Decl::isReferenced() const {
  288. if (Referenced)
  289. return true;
  290. // Check redeclarations.
  291. for (auto I : redecls())
  292. if (I->Referenced)
  293. return true;
  294. return false;
  295. }
  296. /// \brief Determine the availability of the given declaration based on
  297. /// the target platform.
  298. ///
  299. /// When it returns an availability result other than \c AR_Available,
  300. /// if the \p Message parameter is non-NULL, it will be set to a
  301. /// string describing why the entity is unavailable.
  302. ///
  303. /// FIXME: Make these strings localizable, since they end up in
  304. /// diagnostics.
  305. static AvailabilityResult CheckAvailability(ASTContext &Context,
  306. const AvailabilityAttr *A,
  307. std::string *Message) {
  308. VersionTuple TargetMinVersion =
  309. Context.getTargetInfo().getPlatformMinVersion();
  310. if (TargetMinVersion.empty())
  311. return AR_Available;
  312. // Check if this is an App Extension "platform", and if so chop off
  313. // the suffix for matching with the actual platform.
  314. StringRef ActualPlatform = A->getPlatform()->getName();
  315. StringRef RealizedPlatform = ActualPlatform;
  316. if (Context.getLangOpts().AppExt) {
  317. size_t suffix = RealizedPlatform.rfind("_app_extension");
  318. if (suffix != StringRef::npos)
  319. RealizedPlatform = RealizedPlatform.slice(0, suffix);
  320. }
  321. StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
  322. // Match the platform name.
  323. if (RealizedPlatform != TargetPlatform)
  324. return AR_Available;
  325. StringRef PrettyPlatformName
  326. = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
  327. if (PrettyPlatformName.empty())
  328. PrettyPlatformName = ActualPlatform;
  329. std::string HintMessage;
  330. if (!A->getMessage().empty()) {
  331. HintMessage = " - ";
  332. HintMessage += A->getMessage();
  333. }
  334. // Make sure that this declaration has not been marked 'unavailable'.
  335. if (A->getUnavailable()) {
  336. if (Message) {
  337. Message->clear();
  338. llvm::raw_string_ostream Out(*Message);
  339. Out << "not available on " << PrettyPlatformName
  340. << HintMessage;
  341. }
  342. return AR_Unavailable;
  343. }
  344. // Make sure that this declaration has already been introduced.
  345. if (!A->getIntroduced().empty() &&
  346. TargetMinVersion < A->getIntroduced()) {
  347. if (Message) {
  348. Message->clear();
  349. llvm::raw_string_ostream Out(*Message);
  350. VersionTuple VTI(A->getIntroduced());
  351. VTI.UseDotAsSeparator();
  352. Out << "introduced in " << PrettyPlatformName << ' '
  353. << VTI << HintMessage;
  354. }
  355. return AR_NotYetIntroduced;
  356. }
  357. // Make sure that this declaration hasn't been obsoleted.
  358. if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
  359. if (Message) {
  360. Message->clear();
  361. llvm::raw_string_ostream Out(*Message);
  362. VersionTuple VTO(A->getObsoleted());
  363. VTO.UseDotAsSeparator();
  364. Out << "obsoleted in " << PrettyPlatformName << ' '
  365. << VTO << HintMessage;
  366. }
  367. return AR_Unavailable;
  368. }
  369. // Make sure that this declaration hasn't been deprecated.
  370. if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
  371. if (Message) {
  372. Message->clear();
  373. llvm::raw_string_ostream Out(*Message);
  374. VersionTuple VTD(A->getDeprecated());
  375. VTD.UseDotAsSeparator();
  376. Out << "first deprecated in " << PrettyPlatformName << ' '
  377. << VTD << HintMessage;
  378. }
  379. return AR_Deprecated;
  380. }
  381. return AR_Available;
  382. }
  383. AvailabilityResult Decl::getAvailability(std::string *Message) const {
  384. AvailabilityResult Result = AR_Available;
  385. std::string ResultMessage;
  386. for (const auto *A : attrs()) {
  387. if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
  388. if (Result >= AR_Deprecated)
  389. continue;
  390. if (Message)
  391. ResultMessage = Deprecated->getMessage();
  392. Result = AR_Deprecated;
  393. continue;
  394. }
  395. if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
  396. if (Message)
  397. *Message = Unavailable->getMessage();
  398. return AR_Unavailable;
  399. }
  400. if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
  401. AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
  402. Message);
  403. if (AR == AR_Unavailable)
  404. return AR_Unavailable;
  405. if (AR > Result) {
  406. Result = AR;
  407. if (Message)
  408. ResultMessage.swap(*Message);
  409. }
  410. continue;
  411. }
  412. }
  413. if (Message)
  414. Message->swap(ResultMessage);
  415. return Result;
  416. }
  417. bool Decl::canBeWeakImported(bool &IsDefinition) const {
  418. IsDefinition = false;
  419. // Variables, if they aren't definitions.
  420. if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
  421. if (Var->isThisDeclarationADefinition()) {
  422. IsDefinition = true;
  423. return false;
  424. }
  425. return true;
  426. // Functions, if they aren't definitions.
  427. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
  428. if (FD->hasBody()) {
  429. IsDefinition = true;
  430. return false;
  431. }
  432. return true;
  433. // Objective-C classes, if this is the non-fragile runtime.
  434. } else if (isa<ObjCInterfaceDecl>(this) &&
  435. getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
  436. return true;
  437. // Nothing else.
  438. } else {
  439. return false;
  440. }
  441. }
  442. bool Decl::isWeakImported() const {
  443. bool IsDefinition;
  444. if (!canBeWeakImported(IsDefinition))
  445. return false;
  446. for (const auto *A : attrs()) {
  447. if (isa<WeakImportAttr>(A))
  448. return true;
  449. if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
  450. if (CheckAvailability(getASTContext(), Availability,
  451. nullptr) == AR_NotYetIntroduced)
  452. return true;
  453. }
  454. }
  455. return false;
  456. }
  457. unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
  458. switch (DeclKind) {
  459. case Function:
  460. case CXXMethod:
  461. case CXXConstructor:
  462. case CXXDestructor:
  463. case CXXConversion:
  464. case EnumConstant:
  465. case Var:
  466. case ImplicitParam:
  467. case ParmVar:
  468. case NonTypeTemplateParm:
  469. case ObjCMethod:
  470. case ObjCProperty:
  471. case MSProperty:
  472. return IDNS_Ordinary;
  473. case Label:
  474. return IDNS_Label;
  475. case IndirectField:
  476. return IDNS_Ordinary | IDNS_Member;
  477. case ObjCCompatibleAlias:
  478. case ObjCInterface:
  479. return IDNS_Ordinary | IDNS_Type;
  480. case Typedef:
  481. case TypeAlias:
  482. case TypeAliasTemplate:
  483. case UnresolvedUsingTypename:
  484. case TemplateTypeParm:
  485. case ObjCTypeParam:
  486. return IDNS_Ordinary | IDNS_Type;
  487. case UsingShadow:
  488. return 0; // we'll actually overwrite this later
  489. case UnresolvedUsingValue:
  490. return IDNS_Ordinary | IDNS_Using;
  491. case Using:
  492. return IDNS_Using;
  493. case ObjCProtocol:
  494. return IDNS_ObjCProtocol;
  495. case Field:
  496. case ObjCAtDefsField:
  497. case ObjCIvar:
  498. return IDNS_Member;
  499. case Record:
  500. case CXXRecord:
  501. case Enum:
  502. return IDNS_Tag | IDNS_Type;
  503. case Namespace:
  504. case NamespaceAlias:
  505. return IDNS_Namespace;
  506. case FunctionTemplate:
  507. case VarTemplate:
  508. return IDNS_Ordinary;
  509. case ClassTemplate:
  510. case TemplateTemplateParm:
  511. return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
  512. // Never have names.
  513. case Friend:
  514. case FriendTemplate:
  515. case AccessSpec:
  516. case LinkageSpec:
  517. case FileScopeAsm:
  518. case StaticAssert:
  519. case ObjCPropertyImpl:
  520. case Block:
  521. case Captured:
  522. case TranslationUnit:
  523. case ExternCContext:
  524. case UsingDirective:
  525. case ClassTemplateSpecialization:
  526. case ClassTemplatePartialSpecialization:
  527. case ClassScopeFunctionSpecialization:
  528. case VarTemplateSpecialization:
  529. case VarTemplatePartialSpecialization:
  530. case ObjCImplementation:
  531. case ObjCCategory:
  532. case ObjCCategoryImpl:
  533. case Import:
  534. case OMPThreadPrivate:
  535. case Empty:
  536. case HLSLBuffer: // HLSL Change
  537. // Never looked up by name.
  538. return 0;
  539. }
  540. llvm_unreachable("Invalid DeclKind!");
  541. }
  542. void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
  543. assert(!HasAttrs && "Decl already contains attrs.");
  544. AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
  545. assert(AttrBlank.empty() && "HasAttrs was wrong?");
  546. AttrBlank = attrs;
  547. HasAttrs = true;
  548. }
  549. void Decl::dropAttrs() {
  550. if (!HasAttrs) return;
  551. HasAttrs = false;
  552. getASTContext().eraseDeclAttrs(this);
  553. }
  554. const AttrVec &Decl::getAttrs() const {
  555. assert(HasAttrs && "No attrs to get!");
  556. return getASTContext().getDeclAttrs(this);
  557. }
  558. Decl *Decl::castFromDeclContext (const DeclContext *D) {
  559. Decl::Kind DK = D->getDeclKind();
  560. switch(DK) {
  561. #define DECL(NAME, BASE)
  562. #define DECL_CONTEXT(NAME) \
  563. case Decl::NAME: \
  564. return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
  565. #define DECL_CONTEXT_BASE(NAME)
  566. #include "clang/AST/DeclNodes.inc"
  567. default:
  568. #define DECL(NAME, BASE)
  569. #define DECL_CONTEXT_BASE(NAME) \
  570. if (DK >= first##NAME && DK <= last##NAME) \
  571. return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
  572. #include "clang/AST/DeclNodes.inc"
  573. llvm_unreachable("a decl that inherits DeclContext isn't handled");
  574. }
  575. }
  576. DeclContext *Decl::castToDeclContext(const Decl *D) {
  577. Decl::Kind DK = D->getKind();
  578. switch(DK) {
  579. #define DECL(NAME, BASE)
  580. #define DECL_CONTEXT(NAME) \
  581. case Decl::NAME: \
  582. return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
  583. #define DECL_CONTEXT_BASE(NAME)
  584. #include "clang/AST/DeclNodes.inc"
  585. default:
  586. #define DECL(NAME, BASE)
  587. #define DECL_CONTEXT_BASE(NAME) \
  588. if (DK >= first##NAME && DK <= last##NAME) \
  589. return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
  590. #include "clang/AST/DeclNodes.inc"
  591. llvm_unreachable("a decl that inherits DeclContext isn't handled");
  592. }
  593. }
  594. SourceLocation Decl::getBodyRBrace() const {
  595. // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
  596. // FunctionDecl stores EndRangeLoc for this purpose.
  597. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
  598. const FunctionDecl *Definition;
  599. if (FD->hasBody(Definition))
  600. return Definition->getSourceRange().getEnd();
  601. return SourceLocation();
  602. }
  603. if (Stmt *Body = getBody())
  604. return Body->getSourceRange().getEnd();
  605. return SourceLocation();
  606. }
  607. bool Decl::AccessDeclContextSanity() const {
  608. #ifndef NDEBUG
  609. // Suppress this check if any of the following hold:
  610. // 1. this is the translation unit (and thus has no parent)
  611. // 2. this is a template parameter (and thus doesn't belong to its context)
  612. // 3. this is a non-type template parameter
  613. // 4. the context is not a record
  614. // 5. it's invalid
  615. // 6. it's a C++0x static_assert.
  616. if (isa<TranslationUnitDecl>(this) ||
  617. isa<TemplateTypeParmDecl>(this) ||
  618. isa<NonTypeTemplateParmDecl>(this) ||
  619. !isa<CXXRecordDecl>(getDeclContext()) ||
  620. isInvalidDecl() ||
  621. isa<StaticAssertDecl>(this) ||
  622. // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
  623. // as DeclContext (?).
  624. isa<ParmVarDecl>(this) ||
  625. // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
  626. // AS_none as access specifier.
  627. isa<CXXRecordDecl>(this) ||
  628. isa<ClassScopeFunctionSpecializationDecl>(this))
  629. return true;
  630. assert(Access != AS_none &&
  631. "Access specifier is AS_none inside a record decl");
  632. #endif
  633. return true;
  634. }
  635. static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
  636. static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
  637. const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
  638. QualType Ty;
  639. if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
  640. Ty = D->getType();
  641. else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
  642. Ty = D->getUnderlyingType();
  643. else
  644. return nullptr;
  645. if (Ty->isFunctionPointerType())
  646. Ty = Ty->getAs<PointerType>()->getPointeeType();
  647. else if (BlocksToo && Ty->isBlockPointerType())
  648. Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
  649. return Ty->getAs<FunctionType>();
  650. }
  651. /// Starting at a given context (a Decl or DeclContext), look for a
  652. /// code context that is not a closure (a lambda, block, etc.).
  653. template <class T> static Decl *getNonClosureContext(T *D) {
  654. if (getKind(D) == Decl::CXXMethod) {
  655. CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  656. if (MD->getOverloadedOperator() == OO_Call &&
  657. MD->getParent()->isLambda())
  658. return getNonClosureContext(MD->getParent()->getParent());
  659. return MD;
  660. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  661. return FD;
  662. } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  663. return MD;
  664. } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  665. return getNonClosureContext(BD->getParent());
  666. } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
  667. return getNonClosureContext(CD->getParent());
  668. } else {
  669. return nullptr;
  670. }
  671. }
  672. Decl *Decl::getNonClosureContext() {
  673. return ::getNonClosureContext(this);
  674. }
  675. Decl *DeclContext::getNonClosureAncestor() {
  676. return ::getNonClosureContext(this);
  677. }
  678. //===----------------------------------------------------------------------===//
  679. // DeclContext Implementation
  680. //===----------------------------------------------------------------------===//
  681. bool DeclContext::classof(const Decl *D) {
  682. switch (D->getKind()) {
  683. #define DECL(NAME, BASE)
  684. #define DECL_CONTEXT(NAME) case Decl::NAME:
  685. #define DECL_CONTEXT_BASE(NAME)
  686. #include "clang/AST/DeclNodes.inc"
  687. return true;
  688. default:
  689. #define DECL(NAME, BASE)
  690. #define DECL_CONTEXT_BASE(NAME) \
  691. if (D->getKind() >= Decl::first##NAME && \
  692. D->getKind() <= Decl::last##NAME) \
  693. return true;
  694. #include "clang/AST/DeclNodes.inc"
  695. return false;
  696. }
  697. }
  698. DeclContext::~DeclContext() { }
  699. /// \brief Find the parent context of this context that will be
  700. /// used for unqualified name lookup.
  701. ///
  702. /// Generally, the parent lookup context is the semantic context. However, for
  703. /// a friend function the parent lookup context is the lexical context, which
  704. /// is the class in which the friend is declared.
  705. DeclContext *DeclContext::getLookupParent() {
  706. // FIXME: Find a better way to identify friends
  707. if (isa<FunctionDecl>(this))
  708. if (getParent()->getRedeclContext()->isFileContext() &&
  709. getLexicalParent()->getRedeclContext()->isRecord())
  710. return getLexicalParent();
  711. return getParent();
  712. }
  713. bool DeclContext::isInlineNamespace() const {
  714. return isNamespace() &&
  715. cast<NamespaceDecl>(this)->isInline();
  716. }
  717. bool DeclContext::isStdNamespace() const {
  718. if (!isNamespace())
  719. return false;
  720. const NamespaceDecl *ND = cast<NamespaceDecl>(this);
  721. if (ND->isInline()) {
  722. return ND->getParent()->isStdNamespace();
  723. }
  724. if (!getParent()->getRedeclContext()->isTranslationUnit())
  725. return false;
  726. const IdentifierInfo *II = ND->getIdentifier();
  727. return II && II->isStr("std");
  728. }
  729. bool DeclContext::isDependentContext() const {
  730. if (isFileContext())
  731. return false;
  732. if (isa<ClassTemplatePartialSpecializationDecl>(this))
  733. return true;
  734. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
  735. if (Record->getDescribedClassTemplate())
  736. return true;
  737. if (Record->isDependentLambda())
  738. return true;
  739. }
  740. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
  741. if (Function->getDescribedFunctionTemplate())
  742. return true;
  743. // Friend function declarations are dependent if their *lexical*
  744. // context is dependent.
  745. if (cast<Decl>(this)->getFriendObjectKind())
  746. return getLexicalParent()->isDependentContext();
  747. }
  748. // FIXME: A variable template is a dependent context, but is not a
  749. // DeclContext. A context within it (such as a lambda-expression)
  750. // should be considered dependent.
  751. return getParent() && getParent()->isDependentContext();
  752. }
  753. bool DeclContext::isTransparentContext() const {
  754. if (DeclKind == Decl::Enum)
  755. return !cast<EnumDecl>(this)->isScoped();
  756. else if (DeclKind == Decl::LinkageSpec)
  757. return true;
  758. // HLSL Change Starts
  759. if (DeclKind == Decl::HLSLBuffer)
  760. return true;
  761. // HLSL Change Ends
  762. return false;
  763. }
  764. static bool isLinkageSpecContext(const DeclContext *DC,
  765. LinkageSpecDecl::LanguageIDs ID) {
  766. while (DC->getDeclKind() != Decl::TranslationUnit) {
  767. if (DC->getDeclKind() == Decl::LinkageSpec)
  768. return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
  769. DC = DC->getLexicalParent();
  770. }
  771. return false;
  772. }
  773. bool DeclContext::isExternCContext() const {
  774. return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
  775. }
  776. bool DeclContext::isExternCXXContext() const {
  777. return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
  778. }
  779. bool DeclContext::Encloses(const DeclContext *DC) const {
  780. if (getPrimaryContext() != this)
  781. return getPrimaryContext()->Encloses(DC);
  782. for (; DC; DC = DC->getParent())
  783. if (DC->getPrimaryContext() == this)
  784. return true;
  785. return false;
  786. }
  787. DeclContext *DeclContext::getPrimaryContext() {
  788. switch (DeclKind) {
  789. case Decl::TranslationUnit:
  790. case Decl::ExternCContext:
  791. case Decl::LinkageSpec:
  792. case Decl::Block:
  793. case Decl::Captured:
  794. // There is only one DeclContext for these entities.
  795. return this;
  796. // HLSL Change Starts
  797. case Decl::HLSLBuffer:
  798. // Each buffer, even with the same name, is a distinct construct.
  799. return this;
  800. // HLSL Change Ends
  801. case Decl::Namespace:
  802. // The original namespace is our primary context.
  803. return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
  804. case Decl::ObjCMethod:
  805. return this;
  806. case Decl::ObjCInterface:
  807. if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
  808. return Def;
  809. return this;
  810. case Decl::ObjCProtocol:
  811. if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
  812. return Def;
  813. return this;
  814. case Decl::ObjCCategory:
  815. return this;
  816. case Decl::ObjCImplementation:
  817. case Decl::ObjCCategoryImpl:
  818. return this;
  819. default:
  820. if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
  821. // If this is a tag type that has a definition or is currently
  822. // being defined, that definition is our primary context.
  823. TagDecl *Tag = cast<TagDecl>(this);
  824. if (TagDecl *Def = Tag->getDefinition())
  825. return Def;
  826. if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
  827. // Note, TagType::getDecl returns the (partial) definition one exists.
  828. TagDecl *PossiblePartialDef = TagTy->getDecl();
  829. if (PossiblePartialDef->isBeingDefined())
  830. return PossiblePartialDef;
  831. } else {
  832. assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
  833. }
  834. return Tag;
  835. }
  836. assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
  837. "Unknown DeclContext kind");
  838. return this;
  839. }
  840. }
  841. void
  842. DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
  843. Contexts.clear();
  844. if (DeclKind != Decl::Namespace) {
  845. Contexts.push_back(this);
  846. return;
  847. }
  848. NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
  849. for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
  850. N = N->getPreviousDecl())
  851. Contexts.push_back(N);
  852. std::reverse(Contexts.begin(), Contexts.end());
  853. }
  854. std::pair<Decl *, Decl *>
  855. DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
  856. bool FieldsAlreadyLoaded) {
  857. // Build up a chain of declarations via the Decl::NextInContextAndBits field.
  858. Decl *FirstNewDecl = nullptr;
  859. Decl *PrevDecl = nullptr;
  860. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  861. if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
  862. continue;
  863. Decl *D = Decls[I];
  864. if (PrevDecl)
  865. PrevDecl->NextInContextAndBits.setPointer(D);
  866. else
  867. FirstNewDecl = D;
  868. PrevDecl = D;
  869. }
  870. return std::make_pair(FirstNewDecl, PrevDecl);
  871. }
  872. /// \brief We have just acquired external visible storage, and we already have
  873. /// built a lookup map. For every name in the map, pull in the new names from
  874. /// the external storage.
  875. void DeclContext::reconcileExternalVisibleStorage() const {
  876. assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
  877. NeedToReconcileExternalVisibleStorage = false;
  878. for (auto &Lookup : *LookupPtr)
  879. Lookup.second.setHasExternalDecls();
  880. }
  881. /// \brief Load the declarations within this lexical storage from an
  882. /// external source.
  883. /// \return \c true if any declarations were added.
  884. bool
  885. DeclContext::LoadLexicalDeclsFromExternalStorage() const {
  886. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  887. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  888. // Notify that we have a DeclContext that is initializing.
  889. ExternalASTSource::Deserializing ADeclContext(Source);
  890. // Load the external declarations, if any.
  891. SmallVector<Decl*, 64> Decls;
  892. ExternalLexicalStorage = false;
  893. switch (Source->FindExternalLexicalDecls(this, Decls)) {
  894. case ELR_Success:
  895. break;
  896. case ELR_Failure:
  897. case ELR_AlreadyLoaded:
  898. return false;
  899. }
  900. if (Decls.empty())
  901. return false;
  902. // We may have already loaded just the fields of this record, in which case
  903. // we need to ignore them.
  904. bool FieldsAlreadyLoaded = false;
  905. if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
  906. FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
  907. // Splice the newly-read declarations into the beginning of the list
  908. // of declarations.
  909. Decl *ExternalFirst, *ExternalLast;
  910. std::tie(ExternalFirst, ExternalLast) =
  911. BuildDeclChain(Decls, FieldsAlreadyLoaded);
  912. ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
  913. FirstDecl = ExternalFirst;
  914. if (!LastDecl)
  915. LastDecl = ExternalLast;
  916. return true;
  917. }
  918. DeclContext::lookup_result
  919. ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
  920. DeclarationName Name) {
  921. ASTContext &Context = DC->getParentASTContext();
  922. StoredDeclsMap *Map;
  923. if (!(Map = DC->LookupPtr))
  924. Map = DC->CreateStoredDeclsMap(Context);
  925. if (DC->NeedToReconcileExternalVisibleStorage)
  926. DC->reconcileExternalVisibleStorage();
  927. (*Map)[Name].removeExternalDecls();
  928. return DeclContext::lookup_result();
  929. }
  930. DeclContext::lookup_result
  931. ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
  932. DeclarationName Name,
  933. ArrayRef<NamedDecl*> Decls) {
  934. ASTContext &Context = DC->getParentASTContext();
  935. StoredDeclsMap *Map;
  936. if (!(Map = DC->LookupPtr))
  937. Map = DC->CreateStoredDeclsMap(Context);
  938. if (DC->NeedToReconcileExternalVisibleStorage)
  939. DC->reconcileExternalVisibleStorage();
  940. StoredDeclsList &List = (*Map)[Name];
  941. // Clear out any old external visible declarations, to avoid quadratic
  942. // performance in the redeclaration checks below.
  943. List.removeExternalDecls();
  944. if (!List.isNull()) {
  945. // We have both existing declarations and new declarations for this name.
  946. // Some of the declarations may simply replace existing ones. Handle those
  947. // first.
  948. llvm::SmallVector<unsigned, 8> Skip;
  949. for (unsigned I = 0, N = Decls.size(); I != N; ++I)
  950. if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
  951. Skip.push_back(I);
  952. Skip.push_back(Decls.size());
  953. // Add in any new declarations.
  954. unsigned SkipPos = 0;
  955. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  956. if (I == Skip[SkipPos])
  957. ++SkipPos;
  958. else
  959. List.AddSubsequentDecl(Decls[I]);
  960. }
  961. } else {
  962. // Convert the array to a StoredDeclsList.
  963. for (ArrayRef<NamedDecl*>::iterator
  964. I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  965. if (List.isNull())
  966. List.setOnlyValue(*I);
  967. else
  968. List.AddSubsequentDecl(*I);
  969. }
  970. }
  971. return List.getLookupResult();
  972. }
  973. DeclContext::decl_iterator DeclContext::decls_begin() const {
  974. if (hasExternalLexicalStorage())
  975. LoadLexicalDeclsFromExternalStorage();
  976. return decl_iterator(FirstDecl);
  977. }
  978. bool DeclContext::decls_empty() const {
  979. if (hasExternalLexicalStorage())
  980. LoadLexicalDeclsFromExternalStorage();
  981. return !FirstDecl;
  982. }
  983. bool DeclContext::containsDecl(Decl *D) const {
  984. return (D->getLexicalDeclContext() == this &&
  985. (D->NextInContextAndBits.getPointer() || D == LastDecl));
  986. }
  987. void DeclContext::removeDecl(Decl *D) {
  988. assert(D->getLexicalDeclContext() == this &&
  989. "decl being removed from non-lexical context");
  990. assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
  991. "decl is not in decls list");
  992. // Remove D from the decl chain. This is O(n) but hopefully rare.
  993. if (D == FirstDecl) {
  994. if (D == LastDecl)
  995. FirstDecl = LastDecl = nullptr;
  996. else
  997. FirstDecl = D->NextInContextAndBits.getPointer();
  998. } else {
  999. for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
  1000. assert(I && "decl not found in linked list");
  1001. if (I->NextInContextAndBits.getPointer() == D) {
  1002. I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
  1003. if (D == LastDecl) LastDecl = I;
  1004. break;
  1005. }
  1006. }
  1007. }
  1008. // Mark that D is no longer in the decl chain.
  1009. D->NextInContextAndBits.setPointer(nullptr);
  1010. // Remove D from the lookup table if necessary.
  1011. if (isa<NamedDecl>(D)) {
  1012. NamedDecl *ND = cast<NamedDecl>(D);
  1013. // Remove only decls that have a name
  1014. if (!ND->getDeclName()) return;
  1015. StoredDeclsMap *Map = getPrimaryContext()->LookupPtr;
  1016. if (!Map) return;
  1017. StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
  1018. assert(Pos != Map->end() && "no lookup entry for decl");
  1019. if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
  1020. Pos->second.remove(ND);
  1021. }
  1022. }
  1023. void DeclContext::addHiddenDecl(Decl *D) {
  1024. assert(D->getLexicalDeclContext() == this &&
  1025. "Decl inserted into wrong lexical context");
  1026. assert(!D->getNextDeclInContext() && D != LastDecl &&
  1027. "Decl already inserted into a DeclContext");
  1028. if (FirstDecl) {
  1029. LastDecl->NextInContextAndBits.setPointer(D);
  1030. LastDecl = D;
  1031. } else {
  1032. FirstDecl = LastDecl = D;
  1033. }
  1034. // Notify a C++ record declaration that we've added a member, so it can
  1035. // update it's class-specific state.
  1036. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
  1037. Record->addedMember(D);
  1038. // If this is a newly-created (not de-serialized) import declaration, wire
  1039. // it in to the list of local import declarations.
  1040. if (!D->isFromASTFile()) {
  1041. if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
  1042. D->getASTContext().addedLocalImportDecl(Import);
  1043. }
  1044. }
  1045. void DeclContext::addDecl(Decl *D) {
  1046. addHiddenDecl(D);
  1047. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  1048. ND->getDeclContext()->getPrimaryContext()->
  1049. makeDeclVisibleInContextWithFlags(ND, false, true);
  1050. }
  1051. void DeclContext::addDeclInternal(Decl *D) {
  1052. addHiddenDecl(D);
  1053. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  1054. ND->getDeclContext()->getPrimaryContext()->
  1055. makeDeclVisibleInContextWithFlags(ND, true, true);
  1056. }
  1057. /// shouldBeHidden - Determine whether a declaration which was declared
  1058. /// within its semantic context should be invisible to qualified name lookup.
  1059. static bool shouldBeHidden(NamedDecl *D) {
  1060. // Skip unnamed declarations.
  1061. if (!D->getDeclName())
  1062. return true;
  1063. // Skip entities that can't be found by name lookup into a particular
  1064. // context.
  1065. if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
  1066. D->isTemplateParameter())
  1067. return true;
  1068. // Skip template specializations.
  1069. // FIXME: This feels like a hack. Should DeclarationName support
  1070. // template-ids, or is there a better way to keep specializations
  1071. // from being visible?
  1072. if (isa<ClassTemplateSpecializationDecl>(D))
  1073. return true;
  1074. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  1075. if (FD->isFunctionTemplateSpecialization())
  1076. return true;
  1077. return false;
  1078. }
  1079. /// buildLookup - Build the lookup data structure with all of the
  1080. /// declarations in this DeclContext (and any other contexts linked
  1081. /// to it or transparent contexts nested within it) and return it.
  1082. ///
  1083. /// Note that the produced map may miss out declarations from an
  1084. /// external source. If it does, those entries will be marked with
  1085. /// the 'hasExternalDecls' flag.
  1086. StoredDeclsMap *DeclContext::buildLookup() {
  1087. assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
  1088. if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
  1089. return LookupPtr;
  1090. SmallVector<DeclContext *, 2> Contexts;
  1091. collectAllContexts(Contexts);
  1092. if (HasLazyExternalLexicalLookups) {
  1093. HasLazyExternalLexicalLookups = false;
  1094. for (auto *DC : Contexts) {
  1095. if (DC->hasExternalLexicalStorage())
  1096. HasLazyLocalLexicalLookups |=
  1097. DC->LoadLexicalDeclsFromExternalStorage();
  1098. }
  1099. if (!HasLazyLocalLexicalLookups)
  1100. return LookupPtr;
  1101. }
  1102. for (auto *DC : Contexts)
  1103. buildLookupImpl(DC, hasExternalVisibleStorage());
  1104. // We no longer have any lazy decls.
  1105. HasLazyLocalLexicalLookups = false;
  1106. return LookupPtr;
  1107. }
  1108. /// buildLookupImpl - Build part of the lookup data structure for the
  1109. /// declarations contained within DCtx, which will either be this
  1110. /// DeclContext, a DeclContext linked to it, or a transparent context
  1111. /// nested within it.
  1112. void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
  1113. for (Decl *D : DCtx->noload_decls()) {
  1114. // Insert this declaration into the lookup structure, but only if
  1115. // it's semantically within its decl context. Any other decls which
  1116. // should be found in this context are added eagerly.
  1117. //
  1118. // If it's from an AST file, don't add it now. It'll get handled by
  1119. // FindExternalVisibleDeclsByName if needed. Exception: if we're not
  1120. // in C++, we do not track external visible decls for the TU, so in
  1121. // that case we need to collect them all here.
  1122. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  1123. if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
  1124. (!ND->isFromASTFile() ||
  1125. (isTranslationUnit() &&
  1126. !getParentASTContext().getLangOpts().CPlusPlus)))
  1127. makeDeclVisibleInContextImpl(ND, Internal);
  1128. // If this declaration is itself a transparent declaration context
  1129. // or inline namespace, add the members of this declaration of that
  1130. // context (recursively).
  1131. if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
  1132. if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
  1133. buildLookupImpl(InnerCtx, Internal);
  1134. }
  1135. }
  1136. NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
  1137. DeclContext::lookup_result
  1138. DeclContext::lookup(DeclarationName Name) const {
  1139. assert(DeclKind != Decl::LinkageSpec &&
  1140. "Should not perform lookups into linkage specs!");
  1141. const DeclContext *PrimaryContext = getPrimaryContext();
  1142. if (PrimaryContext != this)
  1143. return PrimaryContext->lookup(Name);
  1144. // If we have an external source, ensure that any later redeclarations of this
  1145. // context have been loaded, since they may add names to the result of this
  1146. // lookup (or add external visible storage).
  1147. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  1148. if (Source)
  1149. (void)cast<Decl>(this)->getMostRecentDecl();
  1150. if (hasExternalVisibleStorage()) {
  1151. assert(Source && "external visible storage but no external source?");
  1152. if (NeedToReconcileExternalVisibleStorage)
  1153. reconcileExternalVisibleStorage();
  1154. StoredDeclsMap *Map = LookupPtr;
  1155. if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
  1156. // FIXME: Make buildLookup const?
  1157. Map = const_cast<DeclContext*>(this)->buildLookup();
  1158. if (!Map)
  1159. Map = CreateStoredDeclsMap(getParentASTContext());
  1160. // If we have a lookup result with no external decls, we are done.
  1161. std::pair<StoredDeclsMap::iterator, bool> R =
  1162. Map->insert(std::make_pair(Name, StoredDeclsList()));
  1163. if (!R.second && !R.first->second.hasExternalDecls())
  1164. return R.first->second.getLookupResult();
  1165. if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
  1166. if (StoredDeclsMap *Map = LookupPtr) {
  1167. StoredDeclsMap::iterator I = Map->find(Name);
  1168. if (I != Map->end())
  1169. return I->second.getLookupResult();
  1170. }
  1171. }
  1172. return lookup_result();
  1173. }
  1174. StoredDeclsMap *Map = LookupPtr;
  1175. if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
  1176. Map = const_cast<DeclContext*>(this)->buildLookup();
  1177. if (!Map)
  1178. return lookup_result();
  1179. StoredDeclsMap::iterator I = Map->find(Name);
  1180. if (I == Map->end())
  1181. return lookup_result();
  1182. return I->second.getLookupResult();
  1183. }
  1184. DeclContext::lookup_result
  1185. DeclContext::noload_lookup(DeclarationName Name) {
  1186. assert(DeclKind != Decl::LinkageSpec &&
  1187. "Should not perform lookups into linkage specs!");
  1188. DeclContext *PrimaryContext = getPrimaryContext();
  1189. if (PrimaryContext != this)
  1190. return PrimaryContext->noload_lookup(Name);
  1191. // If we have any lazy lexical declarations not in our lookup map, add them
  1192. // now. Don't import any external declarations, not even if we know we have
  1193. // some missing from the external visible lookups.
  1194. if (HasLazyLocalLexicalLookups) {
  1195. SmallVector<DeclContext *, 2> Contexts;
  1196. collectAllContexts(Contexts);
  1197. for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
  1198. buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
  1199. HasLazyLocalLexicalLookups = false;
  1200. }
  1201. StoredDeclsMap *Map = LookupPtr;
  1202. if (!Map)
  1203. return lookup_result();
  1204. StoredDeclsMap::iterator I = Map->find(Name);
  1205. return I != Map->end() ? I->second.getLookupResult()
  1206. : lookup_result();
  1207. }
  1208. void DeclContext::localUncachedLookup(DeclarationName Name,
  1209. SmallVectorImpl<NamedDecl *> &Results) {
  1210. Results.clear();
  1211. // If there's no external storage, just perform a normal lookup and copy
  1212. // the results.
  1213. if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
  1214. lookup_result LookupResults = lookup(Name);
  1215. Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
  1216. return;
  1217. }
  1218. // If we have a lookup table, check there first. Maybe we'll get lucky.
  1219. // FIXME: Should we be checking these flags on the primary context?
  1220. if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
  1221. if (StoredDeclsMap *Map = LookupPtr) {
  1222. StoredDeclsMap::iterator Pos = Map->find(Name);
  1223. if (Pos != Map->end()) {
  1224. Results.insert(Results.end(),
  1225. Pos->second.getLookupResult().begin(),
  1226. Pos->second.getLookupResult().end());
  1227. return;
  1228. }
  1229. }
  1230. }
  1231. // Slow case: grovel through the declarations in our chain looking for
  1232. // matches.
  1233. // FIXME: If we have lazy external declarations, this will not find them!
  1234. // FIXME: Should we CollectAllContexts and walk them all here?
  1235. for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
  1236. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  1237. if (ND->getDeclName() == Name)
  1238. Results.push_back(ND);
  1239. }
  1240. }
  1241. DeclContext *DeclContext::getRedeclContext() {
  1242. DeclContext *Ctx = this;
  1243. // Skip through transparent contexts.
  1244. while (Ctx->isTransparentContext())
  1245. Ctx = Ctx->getParent();
  1246. return Ctx;
  1247. }
  1248. DeclContext *DeclContext::getEnclosingNamespaceContext() {
  1249. DeclContext *Ctx = this;
  1250. // Skip through non-namespace, non-translation-unit contexts.
  1251. while (!Ctx->isFileContext())
  1252. Ctx = Ctx->getParent();
  1253. return Ctx->getPrimaryContext();
  1254. }
  1255. RecordDecl *DeclContext::getOuterLexicalRecordContext() {
  1256. // Loop until we find a non-record context.
  1257. RecordDecl *OutermostRD = nullptr;
  1258. DeclContext *DC = this;
  1259. while (DC->isRecord()) {
  1260. OutermostRD = cast<RecordDecl>(DC);
  1261. DC = DC->getLexicalParent();
  1262. }
  1263. return OutermostRD;
  1264. }
  1265. bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
  1266. // For non-file contexts, this is equivalent to Equals.
  1267. if (!isFileContext())
  1268. return O->Equals(this);
  1269. do {
  1270. if (O->Equals(this))
  1271. return true;
  1272. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
  1273. if (!NS || !NS->isInline())
  1274. break;
  1275. O = NS->getParent();
  1276. } while (O);
  1277. return false;
  1278. }
  1279. void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
  1280. DeclContext *PrimaryDC = this->getPrimaryContext();
  1281. DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
  1282. // If the decl is being added outside of its semantic decl context, we
  1283. // need to ensure that we eagerly build the lookup information for it.
  1284. PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
  1285. }
  1286. void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
  1287. bool Recoverable) {
  1288. assert(this == getPrimaryContext() && "expected a primary DC");
  1289. // Skip declarations within functions.
  1290. if (isFunctionOrMethod())
  1291. return;
  1292. // Skip declarations which should be invisible to name lookup.
  1293. if (shouldBeHidden(D))
  1294. return;
  1295. // If we already have a lookup data structure, perform the insertion into
  1296. // it. If we might have externally-stored decls with this name, look them
  1297. // up and perform the insertion. If this decl was declared outside its
  1298. // semantic context, buildLookup won't add it, so add it now.
  1299. //
  1300. // FIXME: As a performance hack, don't add such decls into the translation
  1301. // unit unless we're in C++, since qualified lookup into the TU is never
  1302. // performed.
  1303. if (LookupPtr || hasExternalVisibleStorage() ||
  1304. ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
  1305. (getParentASTContext().getLangOpts().CPlusPlus ||
  1306. !isTranslationUnit()))) {
  1307. // If we have lazily omitted any decls, they might have the same name as
  1308. // the decl which we are adding, so build a full lookup table before adding
  1309. // this decl.
  1310. buildLookup();
  1311. makeDeclVisibleInContextImpl(D, Internal);
  1312. } else {
  1313. HasLazyLocalLexicalLookups = true;
  1314. }
  1315. // If we are a transparent context or inline namespace, insert into our
  1316. // parent context, too. This operation is recursive.
  1317. if (isTransparentContext() || isInlineNamespace())
  1318. getParent()->getPrimaryContext()->
  1319. makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
  1320. Decl *DCAsDecl = cast<Decl>(this);
  1321. // Notify that a decl was made visible unless we are a Tag being defined.
  1322. if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
  1323. if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
  1324. L->AddedVisibleDecl(this, D);
  1325. }
  1326. void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
  1327. // Find or create the stored declaration map.
  1328. StoredDeclsMap *Map = LookupPtr;
  1329. if (!Map) {
  1330. ASTContext *C = &getParentASTContext();
  1331. Map = CreateStoredDeclsMap(*C);
  1332. }
  1333. // If there is an external AST source, load any declarations it knows about
  1334. // with this declaration's name.
  1335. // If the lookup table contains an entry about this name it means that we
  1336. // have already checked the external source.
  1337. if (!Internal)
  1338. if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
  1339. if (hasExternalVisibleStorage() &&
  1340. Map->find(D->getDeclName()) == Map->end())
  1341. Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
  1342. // Insert this declaration into the map.
  1343. StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
  1344. if (Internal) {
  1345. // If this is being added as part of loading an external declaration,
  1346. // this may not be the only external declaration with this name.
  1347. // In this case, we never try to replace an existing declaration; we'll
  1348. // handle that when we finalize the list of declarations for this name.
  1349. DeclNameEntries.setHasExternalDecls();
  1350. DeclNameEntries.AddSubsequentDecl(D);
  1351. return;
  1352. }
  1353. if (DeclNameEntries.isNull()) {
  1354. DeclNameEntries.setOnlyValue(D);
  1355. return;
  1356. }
  1357. if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
  1358. // This declaration has replaced an existing one for which
  1359. // declarationReplaces returns true.
  1360. return;
  1361. }
  1362. // Put this declaration into the appropriate slot.
  1363. DeclNameEntries.AddSubsequentDecl(D);
  1364. }
  1365. UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
  1366. return cast<UsingDirectiveDecl>(*I);
  1367. }
  1368. /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
  1369. /// this context.
  1370. DeclContext::udir_range DeclContext::using_directives() const {
  1371. // FIXME: Use something more efficient than normal lookup for using
  1372. // directives. In C++, using directives are looked up more than anything else.
  1373. lookup_result Result = lookup(UsingDirectiveDecl::getName());
  1374. return udir_range(Result.begin(), Result.end());
  1375. }
  1376. //===----------------------------------------------------------------------===//
  1377. // Creation and Destruction of StoredDeclsMaps. //
  1378. //===----------------------------------------------------------------------===//
  1379. StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
  1380. assert(!LookupPtr && "context already has a decls map");
  1381. assert(getPrimaryContext() == this &&
  1382. "creating decls map on non-primary context");
  1383. StoredDeclsMap *M;
  1384. bool Dependent = isDependentContext();
  1385. if (Dependent)
  1386. M = new DependentStoredDeclsMap();
  1387. else
  1388. M = new StoredDeclsMap();
  1389. M->Previous = C.LastSDM;
  1390. C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
  1391. LookupPtr = M;
  1392. return M;
  1393. }
  1394. void ASTContext::ReleaseDeclContextMaps() {
  1395. // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
  1396. // pointer because the subclass doesn't add anything that needs to
  1397. // be deleted.
  1398. StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
  1399. }
  1400. void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
  1401. while (Map) {
  1402. // Advance the iteration before we invalidate memory.
  1403. llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
  1404. if (Dependent)
  1405. delete static_cast<DependentStoredDeclsMap*>(Map);
  1406. else
  1407. delete Map;
  1408. Map = Next.getPointer();
  1409. Dependent = Next.getInt();
  1410. }
  1411. }
  1412. DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
  1413. DeclContext *Parent,
  1414. const PartialDiagnostic &PDiag) {
  1415. assert(Parent->isDependentContext()
  1416. && "cannot iterate dependent diagnostics of non-dependent context");
  1417. Parent = Parent->getPrimaryContext();
  1418. if (!Parent->LookupPtr)
  1419. Parent->CreateStoredDeclsMap(C);
  1420. DependentStoredDeclsMap *Map =
  1421. static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
  1422. // Allocate the copy of the PartialDiagnostic via the ASTContext's
  1423. // BumpPtrAllocator, rather than the ASTContext itself.
  1424. PartialDiagnostic::Storage *DiagStorage = nullptr;
  1425. if (PDiag.hasStorage())
  1426. DiagStorage = new (C) PartialDiagnostic::Storage;
  1427. DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
  1428. // TODO: Maybe we shouldn't reverse the order during insertion.
  1429. DD->NextDiagnostic = Map->FirstDiagnostic;
  1430. Map->FirstDiagnostic = DD;
  1431. return DD;
  1432. }