blob: e99f7ec5b06ea81202b426eb4b2c4dd1f76fd349 [file] [log] [blame]
Eli Friedman7dbab8a2008-06-07 16:52:53 +00001//===--- 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
14#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +000018#include "clang/AST/Decl.h"
Argyrios Kyrtzidis2951e142008-06-09 21:05:31 +000019#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclContextInternals.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000022#include "clang/AST/DeclObjC.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000023#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
John McCallc62bb642010-03-24 05:22:00 +000025#include "clang/AST/DependentDiagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "clang/AST/ExternalASTSource.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000027#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/Type.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000030#include "clang/Basic/TargetInfo.h"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000031#include "llvm/ADT/DenseMap.h"
Chris Lattnereae6cb62009-03-05 08:00:35 +000032#include "llvm/Support/raw_ostream.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000033#include <algorithm>
Eli Friedman7dbab8a2008-06-07 16:52:53 +000034using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Statistics
38//===----------------------------------------------------------------------===//
39
Alexis Hunted053252010-05-30 07:21:58 +000040#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
41#define ABSTRACT_DECL(DECL)
42#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000043
Douglas Gregor7dab26b2013-02-09 01:35:03 +000044void Decl::updateOutOfDate(IdentifierInfo &II) const {
45 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
46}
47
Douglas Gregor72172e92012-01-05 21:55:30 +000048void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
49 unsigned ID,
50 unsigned Size) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000051 // Allocate an extra 8 bytes worth of storage, which ensures that the
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000052 // resulting pointer will still be 8-byte aligned.
Douglas Gregor52261fd2012-01-05 23:49:36 +000053 void *Start = Context.Allocate(Size + 8);
54 void *Result = (char*)Start + 8;
Douglas Gregor64af53c2012-01-05 22:27:05 +000055
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000056 unsigned *PrefixPtr = (unsigned *)Result - 2;
57
58 // Zero out the first 4 bytes; this is used to store the owning module ID.
59 PrefixPtr[0] = 0;
60
61 // Store the global declaration ID in the second 4 bytes.
62 PrefixPtr[1] = ID;
Douglas Gregor64af53c2012-01-05 22:27:05 +000063
64 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000065}
66
Douglas Gregorc147b0b2013-01-12 01:29:50 +000067Module *Decl::getOwningModuleSlow() const {
68 assert(isFromASTFile() && "Not from AST file?");
69 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
70}
71
Eli Friedman7dbab8a2008-06-07 16:52:53 +000072const char *Decl::getDeclKindName() const {
73 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000074 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +000075#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
76#define ABSTRACT_DECL(DECL)
77#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000078 }
79}
80
Douglas Gregor90d47172010-03-05 00:26:45 +000081void Decl::setInvalidDecl(bool Invalid) {
82 InvalidDecl = Invalid;
Argyrios Kyrtzidisb7d1ca22012-03-09 21:09:04 +000083 if (Invalid && !isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +000084 // Defensive maneuver for ill-formed code: we're likely not to make it to
85 // a point where we set the access specifier, so default it to "public"
86 // to avoid triggering asserts elsewhere in the front end.
87 setAccess(AS_public);
88 }
89}
90
Steve Naroff5faaef72009-01-20 19:53:53 +000091const char *DeclContext::getDeclKindName() const {
92 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000093 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +000094#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
95#define ABSTRACT_DECL(DECL)
96#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +000097 }
98}
99
Daniel Dunbar62905572012-03-05 21:42:49 +0000100bool Decl::StatisticsEnabled = false;
101void Decl::EnableStatistics() {
102 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000103}
104
105void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000106 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000107
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000108 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000109#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
110#define ABSTRACT_DECL(DECL)
111#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000112 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000113
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000114 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000115#define DECL(DERIVED, BASE) \
116 if (n##DERIVED##s > 0) { \
117 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000118 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
119 << sizeof(DERIVED##Decl) << " each (" \
120 << n##DERIVED##s * sizeof(DERIVED##Decl) \
121 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000122 }
Alexis Hunted053252010-05-30 07:21:58 +0000123#define ABSTRACT_DECL(DECL)
124#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000125
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000126 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000127}
128
Alexis Hunted053252010-05-30 07:21:58 +0000129void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000130 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000131#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
132#define ABSTRACT_DECL(DECL)
133#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000134 }
135}
136
Anders Carlssonaa73b912009-06-13 00:08:58 +0000137bool Decl::isTemplateParameterPack() const {
138 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
139 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000140 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000141 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000142 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000143 if (const TemplateTemplateParmDecl *TTP
144 = dyn_cast<TemplateTemplateParmDecl>(this))
145 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000146 return false;
147}
148
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000149bool Decl::isParameterPack() const {
150 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
151 return Parm->isParameterPack();
152
153 return isTemplateParameterPack();
154}
155
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000156bool Decl::isFunctionOrFunctionTemplate() const {
John McCall3f746822009-11-17 05:59:44 +0000157 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
Anders Carlssonf057cb22009-06-26 05:26:50 +0000158 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000160 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
161}
162
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000163bool Decl::isTemplateDecl() const {
164 return isa<TemplateDecl>(this);
165}
166
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000167const DeclContext *Decl::getParentFunctionOrMethod() const {
168 for (const DeclContext *DC = getDeclContext();
169 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000170 DC = DC->getParent())
171 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000172 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000173
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000174 return 0;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000175}
176
Douglas Gregor133eddd2011-02-17 08:47:29 +0000177
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000178//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000179// PrettyStackTraceDecl Implementation
180//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000182void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000183 SourceLocation TheLoc = Loc;
184 if (TheLoc.isInvalid() && TheDecl)
185 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattnereae6cb62009-03-05 08:00:35 +0000187 if (TheLoc.isValid()) {
188 TheLoc.print(OS, SM);
189 OS << ": ";
190 }
191
192 OS << Message;
193
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000194 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
195 OS << " '";
196 DN->printQualifiedName(OS);
197 OS << '\'';
198 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000199 OS << '\n';
200}
Mike Stump11289f42009-09-09 15:08:12 +0000201
Chris Lattnereae6cb62009-03-05 08:00:35 +0000202//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000203// Decl Implementation
204//===----------------------------------------------------------------------===//
205
Douglas Gregorb11aad82011-02-19 18:51:44 +0000206// Out-of-line virtual method providing a home for Decl.
207Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000208
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000209void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000210 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000211}
212
213void Decl::setLexicalDeclContext(DeclContext *DC) {
214 if (DC == getLexicalDeclContext())
215 return;
216
217 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000218 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000219 } else {
220 getMultipleDC()->LexicalDC = DC;
221 }
222}
223
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000224void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
225 ASTContext &Ctx) {
226 if (SemaDC == LexicalDC) {
227 DeclCtx = SemaDC;
228 } else {
229 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
230 MDC->SemanticDC = SemaDC;
231 MDC->LexicalDC = LexicalDC;
232 DeclCtx = MDC;
233 }
234}
235
John McCall4fa53422009-10-01 00:25:31 +0000236bool Decl::isInAnonymousNamespace() const {
237 const DeclContext *DC = getDeclContext();
238 do {
239 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
240 if (ND->isAnonymousNamespace())
241 return true;
242 } while ((DC = DC->getParent()));
243
244 return false;
245}
246
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000247TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000248 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
249 return TUD;
250
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000251 DeclContext *DC = getDeclContext();
252 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000253
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000254 while (!DC->isTranslationUnit()) {
255 DC = DC->getParent();
256 assert(DC && "This decl is not contained in a translation unit!");
257 }
Mike Stump11289f42009-09-09 15:08:12 +0000258
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000259 return cast<TranslationUnitDecl>(DC);
260}
261
262ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000263 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000264}
265
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000266ASTMutationListener *Decl::getASTMutationListener() const {
267 return getASTContext().getASTMutationListener();
268}
269
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000270unsigned Decl::getMaxAlignment() const {
271 if (!hasAttrs())
272 return 0;
273
274 unsigned Align = 0;
275 const AttrVec &V = getAttrs();
276 ASTContext &Ctx = getASTContext();
277 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
278 for (; I != E; ++I)
279 Align = std::max(Align, I->getAlignment(Ctx));
280 return Align;
281}
282
Douglas Gregorebada0772010-06-17 23:14:26 +0000283bool Decl::isUsed(bool CheckUsedAttr) const {
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000284 if (Used)
285 return true;
286
287 // Check for used attribute.
Douglas Gregorebada0772010-06-17 23:14:26 +0000288 if (CheckUsedAttr && hasAttr<UsedAttr>())
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000289 return true;
Rafael Espindola99e3bfb2012-11-23 16:26:30 +0000290
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000291 return false;
292}
293
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000294bool Decl::isReferenced() const {
295 if (Referenced)
296 return true;
297
298 // Check redeclarations.
299 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
300 if (I->Referenced)
301 return true;
302
303 return false;
304}
305
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000306/// \brief Determine the availability of the given declaration based on
307/// the target platform.
308///
309/// When it returns an availability result other than \c AR_Available,
310/// if the \p Message parameter is non-NULL, it will be set to a
311/// string describing why the entity is unavailable.
312///
313/// FIXME: Make these strings localizable, since they end up in
314/// diagnostics.
315static AvailabilityResult CheckAvailability(ASTContext &Context,
316 const AvailabilityAttr *A,
317 std::string *Message) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000318 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000319 StringRef PrettyPlatformName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000320 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
321 if (PrettyPlatformName.empty())
322 PrettyPlatformName = TargetPlatform;
323
Douglas Gregore8bbc122011-09-02 00:18:52 +0000324 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000325 if (TargetMinVersion.empty())
326 return AR_Available;
327
328 // Match the platform name.
329 if (A->getPlatform()->getName() != TargetPlatform)
330 return AR_Available;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000331
332 std::string HintMessage;
333 if (!A->getMessage().empty()) {
334 HintMessage = " - ";
335 HintMessage += A->getMessage();
336 }
337
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000338 // Make sure that this declaration has not been marked 'unavailable'.
339 if (A->getUnavailable()) {
340 if (Message) {
341 Message->clear();
342 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000343 Out << "not available on " << PrettyPlatformName
344 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000345 }
346
347 return AR_Unavailable;
348 }
349
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000350 // Make sure that this declaration has already been introduced.
351 if (!A->getIntroduced().empty() &&
352 TargetMinVersion < A->getIntroduced()) {
353 if (Message) {
354 Message->clear();
355 llvm::raw_string_ostream Out(*Message);
356 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000357 << A->getIntroduced() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000358 }
359
360 return AR_NotYetIntroduced;
361 }
362
363 // Make sure that this declaration hasn't been obsoleted.
364 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
365 if (Message) {
366 Message->clear();
367 llvm::raw_string_ostream Out(*Message);
368 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000369 << A->getObsoleted() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000370 }
371
372 return AR_Unavailable;
373 }
374
375 // Make sure that this declaration hasn't been deprecated.
376 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
377 if (Message) {
378 Message->clear();
379 llvm::raw_string_ostream Out(*Message);
380 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000381 << A->getDeprecated() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000382 }
383
384 return AR_Deprecated;
385 }
386
387 return AR_Available;
388}
389
390AvailabilityResult Decl::getAvailability(std::string *Message) const {
391 AvailabilityResult Result = AR_Available;
392 std::string ResultMessage;
393
394 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
395 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
396 if (Result >= AR_Deprecated)
397 continue;
398
399 if (Message)
400 ResultMessage = Deprecated->getMessage();
401
402 Result = AR_Deprecated;
403 continue;
404 }
405
406 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
407 if (Message)
408 *Message = Unavailable->getMessage();
409 return AR_Unavailable;
410 }
411
412 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
413 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
414 Message);
415
416 if (AR == AR_Unavailable)
417 return AR_Unavailable;
418
419 if (AR > Result) {
420 Result = AR;
421 if (Message)
422 ResultMessage.swap(*Message);
423 }
424 continue;
425 }
426 }
427
428 if (Message)
429 Message->swap(ResultMessage);
430 return Result;
431}
432
433bool Decl::canBeWeakImported(bool &IsDefinition) const {
434 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000435
436 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000437 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000438 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000439 IsDefinition = true;
440 return false;
441 }
John McCall5fb5df92012-06-20 06:18:46 +0000442 return true;
443
444 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000445 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
446 if (FD->hasBody()) {
447 IsDefinition = true;
448 return false;
449 }
John McCall5fb5df92012-06-20 06:18:46 +0000450 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000451
John McCall5fb5df92012-06-20 06:18:46 +0000452 // Objective-C classes, if this is the non-fragile runtime.
453 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000454 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000455 return true;
456
457 // Nothing else.
458 } else {
459 return false;
460 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000461}
462
463bool Decl::isWeakImported() const {
464 bool IsDefinition;
465 if (!canBeWeakImported(IsDefinition))
466 return false;
467
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000468 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
469 if (isa<WeakImportAttr>(*A))
470 return true;
471
472 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
473 if (CheckAvailability(getASTContext(), Availability, 0)
474 == AR_NotYetIntroduced)
475 return true;
476 }
477 }
478
479 return false;
480}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000481
Chris Lattner8e097192009-03-27 20:18:19 +0000482unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
483 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000484 case Function:
485 case CXXMethod:
486 case CXXConstructor:
487 case CXXDestructor:
488 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000489 case EnumConstant:
490 case Var:
491 case ImplicitParam:
492 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000493 case NonTypeTemplateParm:
494 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000495 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000496 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000497 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000498 case Label:
499 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000500 case IndirectField:
501 return IDNS_Ordinary | IDNS_Member;
502
John McCalle87beb22010-04-23 18:46:30 +0000503 case ObjCCompatibleAlias:
504 case ObjCInterface:
505 return IDNS_Ordinary | IDNS_Type;
506
507 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000508 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000509 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000510 case UnresolvedUsingTypename:
511 case TemplateTypeParm:
512 return IDNS_Ordinary | IDNS_Type;
513
John McCall3f746822009-11-17 05:59:44 +0000514 case UsingShadow:
515 return 0; // we'll actually overwrite this later
516
John McCalle61f2ba2009-11-18 02:36:19 +0000517 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000518 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000519
520 case Using:
521 return IDNS_Using;
522
Chris Lattner8e097192009-03-27 20:18:19 +0000523 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000524 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattner8e097192009-03-27 20:18:19 +0000526 case Field:
527 case ObjCAtDefsField:
528 case ObjCIvar:
529 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattner8e097192009-03-27 20:18:19 +0000531 case Record:
532 case CXXRecord:
533 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000534 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattner8e097192009-03-27 20:18:19 +0000536 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000537 case NamespaceAlias:
538 return IDNS_Namespace;
539
Chris Lattner8e097192009-03-27 20:18:19 +0000540 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000541 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000542 return IDNS_Ordinary;
543
Chris Lattner8e097192009-03-27 20:18:19 +0000544 case ClassTemplate:
545 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000546 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattner8e097192009-03-27 20:18:19 +0000548 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000549 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000550 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000551 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000552 case LinkageSpec:
553 case FileScopeAsm:
554 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000555 case ObjCPropertyImpl:
Chris Lattner8e097192009-03-27 20:18:19 +0000556 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000557 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000558 case TranslationUnit:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000559
Chris Lattner8e097192009-03-27 20:18:19 +0000560 case UsingDirective:
561 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000562 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000563 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000564 case VarTemplateSpecialization:
565 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000566 case ObjCImplementation:
567 case ObjCCategory:
568 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000569 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000570 case OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +0000571 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000572 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000573 return 0;
574 }
John McCall3f746822009-11-17 05:59:44 +0000575
David Blaikiee4d798f2012-01-20 21:50:17 +0000576 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000577}
578
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000579void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000580 assert(!HasAttrs && "Decl already contains attrs.");
581
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000582 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000583 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000584
585 AttrBlank = attrs;
586 HasAttrs = true;
587}
588
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000589void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000590 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000591
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000592 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000593 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000594}
595
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000596const AttrVec &Decl::getAttrs() const {
597 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000598 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000599}
600
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000601Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000602 Decl::Kind DK = D->getDeclKind();
603 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000604#define DECL(NAME, BASE)
605#define DECL_CONTEXT(NAME) \
606 case Decl::NAME: \
607 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
608#define DECL_CONTEXT_BASE(NAME)
609#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000610 default:
Alexis Hunted053252010-05-30 07:21:58 +0000611#define DECL(NAME, BASE)
612#define DECL_CONTEXT_BASE(NAME) \
613 if (DK >= first##NAME && DK <= last##NAME) \
614 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
615#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000616 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000617 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000618}
619
620DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000621 Decl::Kind DK = D->getKind();
622 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000623#define DECL(NAME, BASE)
624#define DECL_CONTEXT(NAME) \
625 case Decl::NAME: \
626 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
627#define DECL_CONTEXT_BASE(NAME)
628#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000629 default:
Alexis Hunted053252010-05-30 07:21:58 +0000630#define DECL(NAME, BASE)
631#define DECL_CONTEXT_BASE(NAME) \
632 if (DK >= first##NAME && DK <= last##NAME) \
633 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
634#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000635 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000636 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000637}
638
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000639SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000640 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
641 // FunctionDecl stores EndRangeLoc for this purpose.
642 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
643 const FunctionDecl *Definition;
644 if (FD->hasBody(Definition))
645 return Definition->getSourceRange().getEnd();
646 return SourceLocation();
647 }
648
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000649 if (Stmt *Body = getBody())
650 return Body->getSourceRange().getEnd();
651
652 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000653}
654
Anders Carlssona28908d2009-03-25 23:38:06 +0000655void Decl::CheckAccessDeclContext() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000656#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000657 // Suppress this check if any of the following hold:
658 // 1. this is the translation unit (and thus has no parent)
659 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000660 // 3. this is a non-type template parameter
661 // 4. the context is not a record
662 // 5. it's invalid
663 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000664 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000665 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000666 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000667 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000668 isInvalidDecl() ||
669 isa<StaticAssertDecl>(this) ||
670 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
671 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000672 isa<ParmVarDecl>(this) ||
673 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
674 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000675 isa<CXXRecordDecl>(this) ||
676 isa<ClassScopeFunctionSpecializationDecl>(this))
Anders Carlssonadf36b22009-08-29 20:47:47 +0000677 return;
Mike Stump11289f42009-09-09 15:08:12 +0000678
679 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000680 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000681#endif
Anders Carlssona28908d2009-03-25 23:38:06 +0000682}
683
John McCalldec348f72013-05-03 07:33:41 +0000684static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
685static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
686
687/// Starting at a given context (a Decl or DeclContext), look for a
688/// code context that is not a closure (a lambda, block, etc.).
689template <class T> static Decl *getNonClosureContext(T *D) {
690 if (getKind(D) == Decl::CXXMethod) {
691 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000692 if (MD->getOverloadedOperator() == OO_Call &&
693 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000694 return getNonClosureContext(MD->getParent()->getParent());
695 return MD;
696 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
697 return FD;
698 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
699 return MD;
700 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
701 return getNonClosureContext(BD->getParent());
702 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
703 return getNonClosureContext(CD->getParent());
704 } else {
705 return 0;
706 }
John McCallfe96e0b2011-11-06 09:01:30 +0000707}
708
John McCalldec348f72013-05-03 07:33:41 +0000709Decl *Decl::getNonClosureContext() {
710 return ::getNonClosureContext(this);
711}
John McCallb67608f2011-02-22 22:25:23 +0000712
John McCalldec348f72013-05-03 07:33:41 +0000713Decl *DeclContext::getNonClosureAncestor() {
714 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000715}
Anders Carlssona28908d2009-03-25 23:38:06 +0000716
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000717//===----------------------------------------------------------------------===//
718// DeclContext Implementation
719//===----------------------------------------------------------------------===//
720
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000721bool DeclContext::classof(const Decl *D) {
722 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000723#define DECL(NAME, BASE)
724#define DECL_CONTEXT(NAME) case Decl::NAME:
725#define DECL_CONTEXT_BASE(NAME)
726#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000727 return true;
728 default:
Alexis Hunted053252010-05-30 07:21:58 +0000729#define DECL(NAME, BASE)
730#define DECL_CONTEXT_BASE(NAME) \
731 if (D->getKind() >= Decl::first##NAME && \
732 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000733 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000734#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000735 return false;
736 }
737}
738
Douglas Gregor9c832f72010-07-25 18:38:02 +0000739DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000740
Douglas Gregor7f737c02009-09-10 16:57:35 +0000741/// \brief Find the parent context of this context that will be
742/// used for unqualified name lookup.
743///
744/// Generally, the parent lookup context is the semantic context. However, for
745/// a friend function the parent lookup context is the lexical context, which
746/// is the class in which the friend is declared.
747DeclContext *DeclContext::getLookupParent() {
748 // FIXME: Find a better way to identify friends
749 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000750 if (getParent()->getRedeclContext()->isFileContext() &&
751 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000752 return getLexicalParent();
753
754 return getParent();
755}
756
Sebastian Redlbd595762010-08-31 20:53:31 +0000757bool DeclContext::isInlineNamespace() const {
758 return isNamespace() &&
759 cast<NamespaceDecl>(this)->isInline();
760}
761
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000762bool DeclContext::isDependentContext() const {
763 if (isFileContext())
764 return false;
765
Douglas Gregor2373c592009-05-31 09:31:02 +0000766 if (isa<ClassTemplatePartialSpecializationDecl>(this))
767 return true;
768
Douglas Gregor680e9e02012-02-21 19:11:17 +0000769 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000770 if (Record->getDescribedClassTemplate())
771 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000772
773 if (Record->isDependentLambda())
774 return true;
775 }
776
John McCallc62bb642010-03-24 05:22:00 +0000777 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000778 if (Function->getDescribedFunctionTemplate())
779 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000780
John McCallc62bb642010-03-24 05:22:00 +0000781 // Friend function declarations are dependent if their *lexical*
782 // context is dependent.
783 if (cast<Decl>(this)->getFriendObjectKind())
784 return getLexicalParent()->isDependentContext();
785 }
786
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000787 return getParent() && getParent()->isDependentContext();
788}
789
Douglas Gregor07665a62009-01-05 19:45:36 +0000790bool DeclContext::isTransparentContext() const {
791 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000792 return !cast<EnumDecl>(this)->isScoped();
Douglas Gregor07665a62009-01-05 19:45:36 +0000793 else if (DeclKind == Decl::LinkageSpec)
794 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000795
796 return false;
797}
798
Sebastian Redl50c68252010-08-31 00:36:30 +0000799bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +0000800 if (getPrimaryContext() != this)
801 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +0000802
Douglas Gregore985a3b2009-08-27 06:03:53 +0000803 for (; DC; DC = DC->getParent())
804 if (DC->getPrimaryContext() == this)
805 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000806 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +0000807}
808
Steve Naroff35c62ae2009-01-08 17:28:14 +0000809DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +0000810 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000811 case Decl::TranslationUnit:
Douglas Gregor07665a62009-01-05 19:45:36 +0000812 case Decl::LinkageSpec:
Mike Stump11289f42009-09-09 15:08:12 +0000813 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000814 case Decl::Captured:
Douglas Gregor91f84212008-12-11 16:49:14 +0000815 // There is only one DeclContext for these entities.
816 return this;
817
818 case Decl::Namespace:
819 // The original namespace is our primary context.
820 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
821
Douglas Gregor91f84212008-12-11 16:49:14 +0000822 case Decl::ObjCMethod:
823 return this;
824
825 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +0000826 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
827 return Def;
828
829 return this;
830
Steve Naroff35c62ae2009-01-08 17:28:14 +0000831 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +0000832 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
833 return Def;
834
835 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +0000836
Steve Naroff35c62ae2009-01-08 17:28:14 +0000837 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +0000838 return this;
839
Steve Naroff35c62ae2009-01-08 17:28:14 +0000840 case Decl::ObjCImplementation:
841 case Decl::ObjCCategoryImpl:
842 return this;
843
Douglas Gregor91f84212008-12-11 16:49:14 +0000844 default:
Alexis Hunted053252010-05-30 07:21:58 +0000845 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +0000846 // If this is a tag type that has a definition or is currently
847 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +0000848 TagDecl *Tag = cast<TagDecl>(this);
849 assert(isa<TagType>(Tag->TypeForDecl) ||
850 isa<InjectedClassNameType>(Tag->TypeForDecl));
851
852 if (TagDecl *Def = Tag->getDefinition())
853 return Def;
854
855 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
856 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
857 if (TagTy->isBeingDefined())
858 // FIXME: is it necessarily being defined in the decl
859 // that owns the type?
860 return TagTy->getDecl();
861 }
862
863 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +0000864 }
865
Alexis Hunted053252010-05-30 07:21:58 +0000866 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +0000867 "Unknown DeclContext kind");
868 return this;
869 }
870}
871
Douglas Gregore57e7522012-01-07 09:11:48 +0000872void
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000873DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +0000874 Contexts.clear();
875
876 if (DeclKind != Decl::Namespace) {
877 Contexts.push_back(this);
878 return;
Douglas Gregor91f84212008-12-11 16:49:14 +0000879 }
Douglas Gregore57e7522012-01-07 09:11:48 +0000880
881 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +0000882 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
883 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +0000884 Contexts.push_back(N);
885
886 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +0000887}
888
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000889std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +0000890DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000891 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +0000892 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000893 Decl *FirstNewDecl = 0;
894 Decl *PrevDecl = 0;
895 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000896 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
897 continue;
898
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000899 Decl *D = Decls[I];
900 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +0000901 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000902 else
903 FirstNewDecl = D;
904
905 PrevDecl = D;
906 }
907
908 return std::make_pair(FirstNewDecl, PrevDecl);
909}
910
Richard Smith645d7552013-02-07 03:37:08 +0000911/// \brief We have just acquired external visible storage, and we already have
912/// built a lookup map. For every name in the map, pull in the new names from
913/// the external storage.
914void DeclContext::reconcileExternalVisibleStorage() {
Richard Smith86a12012013-02-11 22:02:16 +0000915 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
Richard Smith645d7552013-02-07 03:37:08 +0000916 NeedToReconcileExternalVisibleStorage = false;
917
918 StoredDeclsMap &Map = *LookupPtr.getPointer();
919 ExternalASTSource *Source = getParentASTContext().getExternalSource();
920 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
921 I->second.removeExternalDecls();
922 Source->FindExternalVisibleDeclsByName(this, I->first);
923 }
924}
925
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000926/// \brief Load the declarations within this lexical storage from an
927/// external source.
Mike Stump11289f42009-09-09 15:08:12 +0000928void
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000929DeclContext::LoadLexicalDeclsFromExternalStorage() const {
930 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000931 assert(hasExternalLexicalStorage() && Source && "No external storage?");
932
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +0000933 // Notify that we have a DeclContext that is initializing.
934 ExternalASTSource::Deserializing ADeclContext(Source);
Douglas Gregorf337ae92011-08-26 21:23:06 +0000935
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000936 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000937 SmallVector<Decl*, 64> Decls;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000938 ExternalLexicalStorage = false;
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000939 switch (Source->FindExternalLexicalDecls(this, Decls)) {
940 case ELR_Success:
941 break;
942
943 case ELR_Failure:
944 case ELR_AlreadyLoaded:
945 return;
946 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000947
948 if (Decls.empty())
949 return;
950
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000951 // We may have already loaded just the fields of this record, in which case
952 // we need to ignore them.
953 bool FieldsAlreadyLoaded = false;
954 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
955 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
956
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000957 // Splice the newly-read declarations into the beginning of the list
958 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000959 Decl *ExternalFirst, *ExternalLast;
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000960 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
961 FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +0000962 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000963 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000964 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000965 LastDecl = ExternalLast;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000966}
967
John McCall75b960e2010-06-01 09:23:16 +0000968DeclContext::lookup_result
969ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
970 DeclarationName Name) {
971 ASTContext &Context = DC->getParentASTContext();
972 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +0000973 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +0000974 Map = DC->CreateStoredDeclsMap(Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000975
Richard Smith645d7552013-02-07 03:37:08 +0000976 // Add an entry to the map for this name, if it's not already present.
977 (*Map)[Name];
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000978
John McCall75b960e2010-06-01 09:23:16 +0000979 return DeclContext::lookup_result();
980}
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000981
John McCall75b960e2010-06-01 09:23:16 +0000982DeclContext::lookup_result
983ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +0000984 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +0000985 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +0000986 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +0000987 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +0000988 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +0000989 Map = DC->CreateStoredDeclsMap(Context);
990
991 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +0000992
993 // Clear out any old external visible declarations, to avoid quadratic
994 // performance in the redeclaration checks below.
995 List.removeExternalDecls();
996
997 if (!List.isNull()) {
998 // We have both existing declarations and new declarations for this name.
999 // Some of the declarations may simply replace existing ones. Handle those
1000 // first.
1001 llvm::SmallVector<unsigned, 8> Skip;
1002 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1003 if (List.HandleRedeclaration(Decls[I]))
1004 Skip.push_back(I);
1005 Skip.push_back(Decls.size());
1006
1007 // Add in any new declarations.
1008 unsigned SkipPos = 0;
1009 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1010 if (I == Skip[SkipPos])
1011 ++SkipPos;
1012 else
1013 List.AddSubsequentDecl(Decls[I]);
1014 }
1015 } else {
1016 // Convert the array to a StoredDeclsList.
1017 for (ArrayRef<NamedDecl*>::iterator
1018 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1019 if (List.isNull())
1020 List.setOnlyValue(*I);
1021 else
1022 List.AddSubsequentDecl(*I);
1023 }
John McCall75b960e2010-06-01 09:23:16 +00001024 }
1025
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001026 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001027}
1028
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001029DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1030 return decl_iterator(FirstDecl);
1031}
1032
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001033DeclContext::decl_iterator DeclContext::decls_begin() const {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001034 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001035 LoadLexicalDeclsFromExternalStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001036
Mike Stump11289f42009-09-09 15:08:12 +00001037 return decl_iterator(FirstDecl);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001038}
1039
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001040bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001041 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001042 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001043
1044 return !FirstDecl;
1045}
1046
Sean Callanan0325fb82013-05-04 02:04:27 +00001047bool DeclContext::containsDecl(Decl *D) const {
1048 return (D->getLexicalDeclContext() == this &&
1049 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1050}
1051
John McCall84d87672009-12-10 09:41:52 +00001052void DeclContext::removeDecl(Decl *D) {
1053 assert(D->getLexicalDeclContext() == this &&
1054 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001055 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001056 "decl is not in decls list");
1057
1058 // Remove D from the decl chain. This is O(n) but hopefully rare.
1059 if (D == FirstDecl) {
1060 if (D == LastDecl)
1061 FirstDecl = LastDecl = 0;
1062 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001063 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001064 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001065 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001066 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001067 if (I->NextInContextAndBits.getPointer() == D) {
1068 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001069 if (D == LastDecl) LastDecl = I;
1070 break;
1071 }
1072 }
1073 }
1074
1075 // Mark that D is no longer in the decl chain.
Douglas Gregor781f7132012-01-06 16:59:53 +00001076 D->NextInContextAndBits.setPointer(0);
John McCall84d87672009-12-10 09:41:52 +00001077
1078 // Remove D from the lookup table if necessary.
1079 if (isa<NamedDecl>(D)) {
1080 NamedDecl *ND = cast<NamedDecl>(D);
1081
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001082 // Remove only decls that have a name
1083 if (!ND->getDeclName()) return;
1084
Richard Smithf634c902012-03-16 06:12:59 +00001085 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
John McCallc62bb642010-03-24 05:22:00 +00001086 if (!Map) return;
John McCall84d87672009-12-10 09:41:52 +00001087
John McCall84d87672009-12-10 09:41:52 +00001088 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1089 assert(Pos != Map->end() && "no lookup entry for decl");
Axel Naumannfbc7b982011-11-08 18:21:06 +00001090 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1091 Pos->second.remove(ND);
John McCall84d87672009-12-10 09:41:52 +00001092 }
1093}
1094
John McCalld1e9d832009-08-11 06:59:38 +00001095void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001096 assert(D->getLexicalDeclContext() == this &&
1097 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001098 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001099 "Decl already inserted into a DeclContext");
1100
1101 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001102 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001103 LastDecl = D;
1104 } else {
1105 FirstDecl = LastDecl = D;
1106 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001107
1108 // Notify a C++ record declaration that we've added a member, so it can
1109 // update it's class-specific state.
1110 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1111 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001112
1113 // If this is a newly-created (not de-serialized) import declaration, wire
1114 // it in to the list of local import declarations.
1115 if (!D->isFromASTFile()) {
1116 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1117 D->getASTContext().addedLocalImportDecl(Import);
1118 }
John McCalld1e9d832009-08-11 06:59:38 +00001119}
1120
1121void DeclContext::addDecl(Decl *D) {
1122 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001123
1124 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001125 ND->getDeclContext()->getPrimaryContext()->
1126 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001127}
1128
Sean Callanan95e74be2011-10-21 02:57:43 +00001129void DeclContext::addDeclInternal(Decl *D) {
1130 addHiddenDecl(D);
1131
1132 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001133 ND->getDeclContext()->getPrimaryContext()->
1134 makeDeclVisibleInContextWithFlags(ND, true, true);
1135}
1136
1137/// shouldBeHidden - Determine whether a declaration which was declared
1138/// within its semantic context should be invisible to qualified name lookup.
1139static bool shouldBeHidden(NamedDecl *D) {
1140 // Skip unnamed declarations.
1141 if (!D->getDeclName())
1142 return true;
1143
1144 // Skip entities that can't be found by name lookup into a particular
1145 // context.
1146 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1147 D->isTemplateParameter())
1148 return true;
1149
1150 // Skip template specializations.
1151 // FIXME: This feels like a hack. Should DeclarationName support
1152 // template-ids, or is there a better way to keep specializations
1153 // from being visible?
1154 if (isa<ClassTemplateSpecializationDecl>(D))
1155 return true;
1156 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1157 if (FD->isFunctionTemplateSpecialization())
1158 return true;
1159
1160 return false;
1161}
1162
1163/// buildLookup - Build the lookup data structure with all of the
1164/// declarations in this DeclContext (and any other contexts linked
1165/// to it or transparent contexts nested within it) and return it.
1166StoredDeclsMap *DeclContext::buildLookup() {
1167 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1168
Richard Smith86a12012013-02-11 22:02:16 +00001169 // FIXME: Should we keep going if hasExternalVisibleStorage?
Richard Smithf634c902012-03-16 06:12:59 +00001170 if (!LookupPtr.getInt())
1171 return LookupPtr.getPointer();
1172
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001173 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001174 collectAllContexts(Contexts);
1175 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith95d99302013-07-13 02:00:19 +00001176 buildLookupImpl<&DeclContext::decls_begin,
1177 &DeclContext::decls_end>(Contexts[I]);
Richard Smithf634c902012-03-16 06:12:59 +00001178
1179 // We no longer have any lazy decls.
1180 LookupPtr.setInt(false);
Richard Smith86a12012013-02-11 22:02:16 +00001181 NeedToReconcileExternalVisibleStorage = false;
Richard Smithf634c902012-03-16 06:12:59 +00001182 return LookupPtr.getPointer();
1183}
1184
1185/// buildLookupImpl - Build part of the lookup data structure for the
1186/// declarations contained within DCtx, which will either be this
1187/// DeclContext, a DeclContext linked to it, or a transparent context
1188/// nested within it.
Richard Smith95d99302013-07-13 02:00:19 +00001189template<DeclContext::decl_iterator (DeclContext::*Begin)() const,
1190 DeclContext::decl_iterator (DeclContext::*End)() const>
Richard Smithf634c902012-03-16 06:12:59 +00001191void DeclContext::buildLookupImpl(DeclContext *DCtx) {
Richard Smith95d99302013-07-13 02:00:19 +00001192 for (decl_iterator I = (DCtx->*Begin)(), E = (DCtx->*End)();
Richard Smithf634c902012-03-16 06:12:59 +00001193 I != E; ++I) {
1194 Decl *D = *I;
1195
1196 // Insert this declaration into the lookup structure, but only if
1197 // it's semantically within its decl context. Any other decls which
1198 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001199 //
1200 // If it's from an AST file, don't add it now. It'll get handled by
1201 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1202 // in C++, we do not track external visible decls for the TU, so in
1203 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001204 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001205 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1206 (!ND->isFromASTFile() ||
1207 (isTranslationUnit() &&
1208 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smithf634c902012-03-16 06:12:59 +00001209 makeDeclVisibleInContextImpl(ND, false);
1210
1211 // If this declaration is itself a transparent declaration context
1212 // or inline namespace, add the members of this declaration of that
1213 // context (recursively).
1214 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1215 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith95d99302013-07-13 02:00:19 +00001216 buildLookupImpl<Begin, End>(InnerCtx);
Richard Smithf634c902012-03-16 06:12:59 +00001217 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001218}
1219
Mike Stump11289f42009-09-09 15:08:12 +00001220DeclContext::lookup_result
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001221DeclContext::lookup(DeclarationName Name) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001222 assert(DeclKind != Decl::LinkageSpec &&
1223 "Should not perform lookups into linkage specs!");
1224
Steve Naroff35c62ae2009-01-08 17:28:14 +00001225 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor91f84212008-12-11 16:49:14 +00001226 if (PrimaryContext != this)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001227 return PrimaryContext->lookup(Name);
Douglas Gregor91f84212008-12-11 16:49:14 +00001228
Richard Smith05afe5e2012-03-13 03:12:56 +00001229 if (hasExternalVisibleStorage()) {
Richard Smith645d7552013-02-07 03:37:08 +00001230 StoredDeclsMap *Map = LookupPtr.getPointer();
1231 if (LookupPtr.getInt())
1232 Map = buildLookup();
Richard Smith86a12012013-02-11 22:02:16 +00001233 else if (NeedToReconcileExternalVisibleStorage)
1234 reconcileExternalVisibleStorage();
Richard Smith645d7552013-02-07 03:37:08 +00001235
Richard Smith75fc3bf2013-02-08 00:37:45 +00001236 if (!Map)
1237 Map = CreateStoredDeclsMap(getParentASTContext());
1238
Richard Smith645d7552013-02-07 03:37:08 +00001239 // If a PCH/module has a result for this name, and we have a local
1240 // declaration, we will have imported the PCH/module result when adding the
1241 // local declaration or when reconciling the module.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001242 std::pair<StoredDeclsMap::iterator, bool> R =
1243 Map->insert(std::make_pair(Name, StoredDeclsList()));
1244 if (!R.second)
1245 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001246
John McCall75b960e2010-06-01 09:23:16 +00001247 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Richard Smith9ce12e32013-02-07 03:30:24 +00001248 if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1249 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1250 StoredDeclsMap::iterator I = Map->find(Name);
1251 if (I != Map->end())
1252 return I->second.getLookupResult();
1253 }
1254 }
1255
1256 return lookup_result(lookup_iterator(0), lookup_iterator(0));
John McCall75b960e2010-06-01 09:23:16 +00001257 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001258
Richard Smithf634c902012-03-16 06:12:59 +00001259 StoredDeclsMap *Map = LookupPtr.getPointer();
1260 if (LookupPtr.getInt())
1261 Map = buildLookup();
1262
1263 if (!Map)
1264 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1265
1266 StoredDeclsMap::iterator I = Map->find(Name);
1267 if (I == Map->end())
1268 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1269
1270 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001271}
1272
Richard Smith95d99302013-07-13 02:00:19 +00001273DeclContext::lookup_result
1274DeclContext::noload_lookup(DeclarationName Name) {
1275 assert(DeclKind != Decl::LinkageSpec &&
1276 "Should not perform lookups into linkage specs!");
1277 if (!hasExternalVisibleStorage())
1278 return lookup(Name);
1279
1280 DeclContext *PrimaryContext = getPrimaryContext();
1281 if (PrimaryContext != this)
1282 return PrimaryContext->noload_lookup(Name);
1283
1284 StoredDeclsMap *Map = LookupPtr.getPointer();
1285 if (LookupPtr.getInt()) {
1286 // Carefully build the lookup map, without deserializing anything.
1287 SmallVector<DeclContext *, 2> Contexts;
1288 collectAllContexts(Contexts);
1289 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1290 buildLookupImpl<&DeclContext::noload_decls_begin,
1291 &DeclContext::noload_decls_end>(Contexts[I]);
1292
1293 // We no longer have any lazy decls.
1294 LookupPtr.setInt(false);
1295
1296 // There may now be names for which we have local decls but are
1297 // missing the external decls.
1298 NeedToReconcileExternalVisibleStorage = true;
1299
1300 Map = LookupPtr.getPointer();
1301 }
1302
1303 if (!Map)
1304 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1305
1306 StoredDeclsMap::iterator I = Map->find(Name);
1307 return I != Map->end()
1308 ? I->second.getLookupResult()
1309 : lookup_result(lookup_iterator(0), lookup_iterator(0));
1310}
1311
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001312void DeclContext::localUncachedLookup(DeclarationName Name,
1313 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001314 Results.clear();
1315
1316 // If there's no external storage, just perform a normal lookup and copy
1317 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001318 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001319 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001320 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001321 return;
1322 }
1323
1324 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith645d7552013-02-07 03:37:08 +00001325 if (Name && !LookupPtr.getInt()) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001326 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1327 StoredDeclsMap::iterator Pos = Map->find(Name);
1328 if (Pos != Map->end()) {
1329 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001330 Pos->second.getLookupResult().begin(),
1331 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001332 return;
1333 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001334 }
1335 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001336
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001337 // Slow case: grovel through the declarations in our chain looking for
1338 // matches.
1339 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1340 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1341 if (ND->getDeclName() == Name)
1342 Results.push_back(ND);
1343 }
1344}
1345
Sebastian Redl50c68252010-08-31 00:36:30 +00001346DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001347 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001348 // Skip through transparent contexts.
1349 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001350 Ctx = Ctx->getParent();
1351 return Ctx;
1352}
1353
Douglas Gregorf47b9112009-02-25 22:02:03 +00001354DeclContext *DeclContext::getEnclosingNamespaceContext() {
1355 DeclContext *Ctx = this;
1356 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001357 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001358 Ctx = Ctx->getParent();
1359 return Ctx->getPrimaryContext();
1360}
1361
Sebastian Redl50c68252010-08-31 00:36:30 +00001362bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1363 // For non-file contexts, this is equivalent to Equals.
1364 if (!isFileContext())
1365 return O->Equals(this);
1366
1367 do {
1368 if (O->Equals(this))
1369 return true;
1370
1371 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1372 if (!NS || !NS->isInline())
1373 break;
1374 O = NS->getParent();
1375 } while (O);
1376
1377 return false;
1378}
1379
Richard Smithf634c902012-03-16 06:12:59 +00001380void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1381 DeclContext *PrimaryDC = this->getPrimaryContext();
1382 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1383 // If the decl is being added outside of its semantic decl context, we
1384 // need to ensure that we eagerly build the lookup information for it.
1385 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001386}
1387
Richard Smithf634c902012-03-16 06:12:59 +00001388void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1389 bool Recoverable) {
1390 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001391
Richard Smith05afe5e2012-03-13 03:12:56 +00001392 // Skip declarations within functions.
1393 // FIXME: We shouldn't need to build lookup tables for function declarations
1394 // ever, and we can't do so correctly because we can't model the nesting of
1395 // scopes which occurs within functions. We use "qualified" lookup into
1396 // function declarations when handling friend declarations inside nested
1397 // classes, and consequently accept the following invalid code:
1398 //
1399 // void f() { void g(); { int g; struct S { friend void g(); }; } }
1400 if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1401 return;
1402
Richard Smithf634c902012-03-16 06:12:59 +00001403 // Skip declarations which should be invisible to name lookup.
1404 if (shouldBeHidden(D))
1405 return;
1406
1407 // If we already have a lookup data structure, perform the insertion into
1408 // it. If we might have externally-stored decls with this name, look them
1409 // up and perform the insertion. If this decl was declared outside its
1410 // semantic context, buildLookup won't add it, so add it now.
1411 //
1412 // FIXME: As a performance hack, don't add such decls into the translation
1413 // unit unless we're in C++, since qualified lookup into the TU is never
1414 // performed.
1415 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1416 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1417 (getParentASTContext().getLangOpts().CPlusPlus ||
1418 !isTranslationUnit()))) {
1419 // If we have lazily omitted any decls, they might have the same name as
1420 // the decl which we are adding, so build a full lookup table before adding
1421 // this decl.
1422 buildLookup();
1423 makeDeclVisibleInContextImpl(D, Internal);
1424 } else {
1425 LookupPtr.setInt(true);
1426 }
1427
1428 // If we are a transparent context or inline namespace, insert into our
1429 // parent context, too. This operation is recursive.
1430 if (isTransparentContext() || isInlineNamespace())
1431 getParent()->getPrimaryContext()->
1432 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1433
1434 Decl *DCAsDecl = cast<Decl>(this);
1435 // Notify that a decl was made visible unless we are a Tag being defined.
1436 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1437 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1438 L->AddedVisibleDecl(this, D);
1439}
1440
1441void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1442 // Find or create the stored declaration map.
1443 StoredDeclsMap *Map = LookupPtr.getPointer();
1444 if (!Map) {
1445 ASTContext *C = &getParentASTContext();
1446 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001447 }
1448
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001449 // If there is an external AST source, load any declarations it knows about
1450 // with this declaration's name.
1451 // If the lookup table contains an entry about this name it means that we
1452 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001453 if (!Internal)
1454 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1455 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001456 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001457 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001458
Douglas Gregor91f84212008-12-11 16:49:14 +00001459 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001460 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Chris Lattnercaae7162009-02-20 01:44:05 +00001461 if (DeclNameEntries.isNull()) {
1462 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001463 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001464 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001465
Richard Smithf634c902012-03-16 06:12:59 +00001466 if (DeclNameEntries.HandleRedeclaration(D)) {
1467 // This declaration has replaced an existing one for which
1468 // declarationReplaces returns true.
1469 return;
1470 }
Mike Stump11289f42009-09-09 15:08:12 +00001471
Richard Smithf634c902012-03-16 06:12:59 +00001472 // Put this declaration into the appropriate slot.
1473 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001474}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001475
1476/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1477/// this context.
Mike Stump11289f42009-09-09 15:08:12 +00001478DeclContext::udir_iterator_range
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001479DeclContext::getUsingDirectives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001480 // FIXME: Use something more efficient than normal lookup for using
1481 // directives. In C++, using directives are looked up more than anything else.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001482 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001483 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1484 reinterpret_cast<udir_iterator>(Result.end()));
Douglas Gregor889ceb72009-02-03 19:21:40 +00001485}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001486
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001487//===----------------------------------------------------------------------===//
1488// Creation and Destruction of StoredDeclsMaps. //
1489//===----------------------------------------------------------------------===//
1490
John McCallc62bb642010-03-24 05:22:00 +00001491StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smithf634c902012-03-16 06:12:59 +00001492 assert(!LookupPtr.getPointer() && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001493 assert(getPrimaryContext() == this &&
1494 "creating decls map on non-primary context");
1495
1496 StoredDeclsMap *M;
1497 bool Dependent = isDependentContext();
1498 if (Dependent)
1499 M = new DependentStoredDeclsMap();
1500 else
1501 M = new StoredDeclsMap();
1502 M->Previous = C.LastSDM;
1503 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smithf634c902012-03-16 06:12:59 +00001504 LookupPtr.setPointer(M);
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001505 return M;
1506}
1507
1508void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001509 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1510 // pointer because the subclass doesn't add anything that needs to
1511 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001512 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1513}
1514
1515void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1516 while (Map) {
1517 // Advance the iteration before we invalidate memory.
1518 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1519
1520 if (Dependent)
1521 delete static_cast<DependentStoredDeclsMap*>(Map);
1522 else
1523 delete Map;
1524
1525 Map = Next.getPointer();
1526 Dependent = Next.getInt();
1527 }
1528}
1529
John McCallc62bb642010-03-24 05:22:00 +00001530DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1531 DeclContext *Parent,
1532 const PartialDiagnostic &PDiag) {
1533 assert(Parent->isDependentContext()
1534 && "cannot iterate dependent diagnostics of non-dependent context");
1535 Parent = Parent->getPrimaryContext();
Richard Smithf634c902012-03-16 06:12:59 +00001536 if (!Parent->LookupPtr.getPointer())
John McCallc62bb642010-03-24 05:22:00 +00001537 Parent->CreateStoredDeclsMap(C);
1538
1539 DependentStoredDeclsMap *Map
Richard Smithf634c902012-03-16 06:12:59 +00001540 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
John McCallc62bb642010-03-24 05:22:00 +00001541
Douglas Gregora55530e2010-03-29 23:56:53 +00001542 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001543 // BumpPtrAllocator, rather than the ASTContext itself.
Douglas Gregora55530e2010-03-29 23:56:53 +00001544 PartialDiagnostic::Storage *DiagStorage = 0;
1545 if (PDiag.hasStorage())
1546 DiagStorage = new (C) PartialDiagnostic::Storage;
1547
1548 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001549
1550 // TODO: Maybe we shouldn't reverse the order during insertion.
1551 DD->NextDiagnostic = Map->FirstDiagnostic;
1552 Map->FirstDiagnostic = DD;
1553
1554 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001555}