blob: f675436fc5f25d0fdb4b1f98871d186c037287f0 [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"
23#include "clang/AST/DeclTemplate.h"
John McCallc62bb642010-03-24 05:22:00 +000024#include "clang/AST/DependentDiagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/ExternalASTSource.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000026#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/Type.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000029#include "clang/Basic/TargetInfo.h"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000030#include "llvm/ADT/DenseMap.h"
Chris Lattnereae6cb62009-03-05 08:00:35 +000031#include "llvm/Support/raw_ostream.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000032#include <algorithm>
Eli Friedman7dbab8a2008-06-07 16:52:53 +000033using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// Statistics
37//===----------------------------------------------------------------------===//
38
Alexis Hunted053252010-05-30 07:21:58 +000039#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
40#define ABSTRACT_DECL(DECL)
41#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000042
Douglas Gregor7dab26b2013-02-09 01:35:03 +000043void Decl::updateOutOfDate(IdentifierInfo &II) const {
44 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
45}
46
Douglas Gregor72172e92012-01-05 21:55:30 +000047void *Decl::AllocateDeserializedDecl(const ASTContext &Context,
48 unsigned ID,
49 unsigned Size) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000050 // Allocate an extra 8 bytes worth of storage, which ensures that the
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000051 // resulting pointer will still be 8-byte aligned.
Douglas Gregor52261fd2012-01-05 23:49:36 +000052 void *Start = Context.Allocate(Size + 8);
53 void *Result = (char*)Start + 8;
Douglas Gregor64af53c2012-01-05 22:27:05 +000054
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000055 unsigned *PrefixPtr = (unsigned *)Result - 2;
56
57 // Zero out the first 4 bytes; this is used to store the owning module ID.
58 PrefixPtr[0] = 0;
59
60 // Store the global declaration ID in the second 4 bytes.
61 PrefixPtr[1] = ID;
Douglas Gregor64af53c2012-01-05 22:27:05 +000062
63 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000064}
65
Douglas Gregorc147b0b2013-01-12 01:29:50 +000066Module *Decl::getOwningModuleSlow() const {
67 assert(isFromASTFile() && "Not from AST file?");
68 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
69}
70
Eli Friedman7dbab8a2008-06-07 16:52:53 +000071const char *Decl::getDeclKindName() const {
72 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000073 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +000074#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
75#define ABSTRACT_DECL(DECL)
76#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000077 }
78}
79
Douglas Gregor90d47172010-03-05 00:26:45 +000080void Decl::setInvalidDecl(bool Invalid) {
81 InvalidDecl = Invalid;
Argyrios Kyrtzidisb7d1ca22012-03-09 21:09:04 +000082 if (Invalid && !isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +000083 // Defensive maneuver for ill-formed code: we're likely not to make it to
84 // a point where we set the access specifier, so default it to "public"
85 // to avoid triggering asserts elsewhere in the front end.
86 setAccess(AS_public);
87 }
88}
89
Steve Naroff5faaef72009-01-20 19:53:53 +000090const char *DeclContext::getDeclKindName() const {
91 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +000092 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +000093#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
94#define ABSTRACT_DECL(DECL)
95#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +000096 }
97}
98
Daniel Dunbar62905572012-03-05 21:42:49 +000099bool Decl::StatisticsEnabled = false;
100void Decl::EnableStatistics() {
101 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000102}
103
104void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000105 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000106
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000107 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000108#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
109#define ABSTRACT_DECL(DECL)
110#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000111 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000112
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000113 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000114#define DECL(DERIVED, BASE) \
115 if (n##DERIVED##s > 0) { \
116 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000117 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
118 << sizeof(DERIVED##Decl) << " each (" \
119 << n##DERIVED##s * sizeof(DERIVED##Decl) \
120 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000121 }
Alexis Hunted053252010-05-30 07:21:58 +0000122#define ABSTRACT_DECL(DECL)
123#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000124
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000125 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000126}
127
Alexis Hunted053252010-05-30 07:21:58 +0000128void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000129 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000130#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
131#define ABSTRACT_DECL(DECL)
132#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000133 }
134}
135
Anders Carlssonaa73b912009-06-13 00:08:58 +0000136bool Decl::isTemplateParameterPack() const {
137 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
138 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000139 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000140 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000141 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000142 if (const TemplateTemplateParmDecl *TTP
143 = dyn_cast<TemplateTemplateParmDecl>(this))
144 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000145 return false;
146}
147
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000148bool Decl::isParameterPack() const {
149 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
150 return Parm->isParameterPack();
151
152 return isTemplateParameterPack();
153}
154
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000155bool Decl::isFunctionOrFunctionTemplate() const {
John McCall3f746822009-11-17 05:59:44 +0000156 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this))
Anders Carlssonf057cb22009-06-26 05:26:50 +0000157 return UD->getTargetDecl()->isFunctionOrFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000158
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000159 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this);
160}
161
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000162bool Decl::isTemplateDecl() const {
163 return isa<TemplateDecl>(this);
164}
165
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000166const DeclContext *Decl::getParentFunctionOrMethod() const {
167 for (const DeclContext *DC = getDeclContext();
168 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000169 DC = DC->getParent())
170 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000171 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000172
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000173 return 0;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000174}
175
Douglas Gregor133eddd2011-02-17 08:47:29 +0000176
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000177//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000178// PrettyStackTraceDecl Implementation
179//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000181void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000182 SourceLocation TheLoc = Loc;
183 if (TheLoc.isInvalid() && TheDecl)
184 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000185
Chris Lattnereae6cb62009-03-05 08:00:35 +0000186 if (TheLoc.isValid()) {
187 TheLoc.print(OS, SM);
188 OS << ": ";
189 }
190
191 OS << Message;
192
Daniel Dunbar4f1054e2009-11-21 09:05:59 +0000193 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
Chris Lattnereae6cb62009-03-05 08:00:35 +0000194 OS << " '" << DN->getQualifiedNameAsString() << '\'';
195 OS << '\n';
196}
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattnereae6cb62009-03-05 08:00:35 +0000198//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000199// Decl Implementation
200//===----------------------------------------------------------------------===//
201
Douglas Gregorb11aad82011-02-19 18:51:44 +0000202// Out-of-line virtual method providing a home for Decl.
203Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000204
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000205void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000206 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000207}
208
209void Decl::setLexicalDeclContext(DeclContext *DC) {
210 if (DC == getLexicalDeclContext())
211 return;
212
213 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000214 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000215 } else {
216 getMultipleDC()->LexicalDC = DC;
217 }
218}
219
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000220void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
221 ASTContext &Ctx) {
222 if (SemaDC == LexicalDC) {
223 DeclCtx = SemaDC;
224 } else {
225 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
226 MDC->SemanticDC = SemaDC;
227 MDC->LexicalDC = LexicalDC;
228 DeclCtx = MDC;
229 }
230}
231
John McCall4fa53422009-10-01 00:25:31 +0000232bool 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
240 return false;
241}
242
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000243TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000244 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
245 return TUD;
246
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000247 DeclContext *DC = getDeclContext();
248 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000249
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000250 while (!DC->isTranslationUnit()) {
251 DC = DC->getParent();
252 assert(DC && "This decl is not contained in a translation unit!");
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000255 return cast<TranslationUnitDecl>(DC);
256}
257
258ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000259 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000260}
261
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000262ASTMutationListener *Decl::getASTMutationListener() const {
263 return getASTContext().getASTMutationListener();
264}
265
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000266unsigned Decl::getMaxAlignment() const {
267 if (!hasAttrs())
268 return 0;
269
270 unsigned Align = 0;
271 const AttrVec &V = getAttrs();
272 ASTContext &Ctx = getASTContext();
273 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
274 for (; I != E; ++I)
275 Align = std::max(Align, I->getAlignment(Ctx));
276 return Align;
277}
278
Douglas Gregorebada0772010-06-17 23:14:26 +0000279bool Decl::isUsed(bool CheckUsedAttr) const {
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000280 if (Used)
281 return true;
282
283 // Check for used attribute.
Douglas Gregorebada0772010-06-17 23:14:26 +0000284 if (CheckUsedAttr && hasAttr<UsedAttr>())
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000285 return true;
Rafael Espindola99e3bfb2012-11-23 16:26:30 +0000286
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000287 return false;
288}
289
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000290bool Decl::isReferenced() const {
291 if (Referenced)
292 return true;
293
294 // Check redeclarations.
295 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
296 if (I->Referenced)
297 return true;
298
299 return false;
300}
301
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000302/// \brief Determine the availability of the given declaration based on
303/// the target platform.
304///
305/// When it returns an availability result other than \c AR_Available,
306/// if the \p Message parameter is non-NULL, it will be set to a
307/// string describing why the entity is unavailable.
308///
309/// FIXME: Make these strings localizable, since they end up in
310/// diagnostics.
311static AvailabilityResult CheckAvailability(ASTContext &Context,
312 const AvailabilityAttr *A,
313 std::string *Message) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000314 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000315 StringRef PrettyPlatformName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000316 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform);
317 if (PrettyPlatformName.empty())
318 PrettyPlatformName = TargetPlatform;
319
Douglas Gregore8bbc122011-09-02 00:18:52 +0000320 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000321 if (TargetMinVersion.empty())
322 return AR_Available;
323
324 // Match the platform name.
325 if (A->getPlatform()->getName() != TargetPlatform)
326 return AR_Available;
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000327
328 std::string HintMessage;
329 if (!A->getMessage().empty()) {
330 HintMessage = " - ";
331 HintMessage += A->getMessage();
332 }
333
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000334 // 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);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000339 Out << "not available on " << PrettyPlatformName
340 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000341 }
342
343 return AR_Unavailable;
344 }
345
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000346 // Make sure that this declaration has already been introduced.
347 if (!A->getIntroduced().empty() &&
348 TargetMinVersion < A->getIntroduced()) {
349 if (Message) {
350 Message->clear();
351 llvm::raw_string_ostream Out(*Message);
352 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000353 << A->getIntroduced() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000354 }
355
356 return AR_NotYetIntroduced;
357 }
358
359 // Make sure that this declaration hasn't been obsoleted.
360 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) {
361 if (Message) {
362 Message->clear();
363 llvm::raw_string_ostream Out(*Message);
364 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000365 << A->getObsoleted() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000366 }
367
368 return AR_Unavailable;
369 }
370
371 // Make sure that this declaration hasn't been deprecated.
372 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) {
373 if (Message) {
374 Message->clear();
375 llvm::raw_string_ostream Out(*Message);
376 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000377 << A->getDeprecated() << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000378 }
379
380 return AR_Deprecated;
381 }
382
383 return AR_Available;
384}
385
386AvailabilityResult Decl::getAvailability(std::string *Message) const {
387 AvailabilityResult Result = AR_Available;
388 std::string ResultMessage;
389
390 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
391 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) {
392 if (Result >= AR_Deprecated)
393 continue;
394
395 if (Message)
396 ResultMessage = Deprecated->getMessage();
397
398 Result = AR_Deprecated;
399 continue;
400 }
401
402 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) {
403 if (Message)
404 *Message = Unavailable->getMessage();
405 return AR_Unavailable;
406 }
407
408 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
409 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
410 Message);
411
412 if (AR == AR_Unavailable)
413 return AR_Unavailable;
414
415 if (AR > Result) {
416 Result = AR;
417 if (Message)
418 ResultMessage.swap(*Message);
419 }
420 continue;
421 }
422 }
423
424 if (Message)
425 Message->swap(ResultMessage);
426 return Result;
427}
428
429bool Decl::canBeWeakImported(bool &IsDefinition) const {
430 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000431
432 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000433 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
434 if (!Var->hasExternalStorage() || Var->getInit()) {
435 IsDefinition = true;
436 return false;
437 }
John McCall5fb5df92012-06-20 06:18:46 +0000438 return true;
439
440 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000441 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
442 if (FD->hasBody()) {
443 IsDefinition = true;
444 return false;
445 }
John McCall5fb5df92012-06-20 06:18:46 +0000446 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000447
John McCall5fb5df92012-06-20 06:18:46 +0000448 // Objective-C classes, if this is the non-fragile runtime.
449 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000450 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000451 return true;
452
453 // Nothing else.
454 } else {
455 return false;
456 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000457}
458
459bool Decl::isWeakImported() const {
460 bool IsDefinition;
461 if (!canBeWeakImported(IsDefinition))
462 return false;
463
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000464 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) {
465 if (isa<WeakImportAttr>(*A))
466 return true;
467
468 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) {
469 if (CheckAvailability(getASTContext(), Availability, 0)
470 == AR_NotYetIntroduced)
471 return true;
472 }
473 }
474
475 return false;
476}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000477
Chris Lattner8e097192009-03-27 20:18:19 +0000478unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
479 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000480 case Function:
481 case CXXMethod:
482 case CXXConstructor:
483 case CXXDestructor:
484 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000485 case EnumConstant:
486 case Var:
487 case ImplicitParam:
488 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000489 case NonTypeTemplateParm:
490 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000491 case ObjCProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000492 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000493 case Label:
494 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000495 case IndirectField:
496 return IDNS_Ordinary | IDNS_Member;
497
John McCalle87beb22010-04-23 18:46:30 +0000498 case ObjCCompatibleAlias:
499 case ObjCInterface:
500 return IDNS_Ordinary | IDNS_Type;
501
502 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000503 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000504 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000505 case UnresolvedUsingTypename:
506 case TemplateTypeParm:
507 return IDNS_Ordinary | IDNS_Type;
508
John McCall3f746822009-11-17 05:59:44 +0000509 case UsingShadow:
510 return 0; // we'll actually overwrite this later
511
John McCalle61f2ba2009-11-18 02:36:19 +0000512 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000513 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000514
515 case Using:
516 return IDNS_Using;
517
Chris Lattner8e097192009-03-27 20:18:19 +0000518 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000519 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chris Lattner8e097192009-03-27 20:18:19 +0000521 case Field:
522 case ObjCAtDefsField:
523 case ObjCIvar:
524 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattner8e097192009-03-27 20:18:19 +0000526 case Record:
527 case CXXRecord:
528 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000529 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattner8e097192009-03-27 20:18:19 +0000531 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000532 case NamespaceAlias:
533 return IDNS_Namespace;
534
Chris Lattner8e097192009-03-27 20:18:19 +0000535 case FunctionTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000536 return IDNS_Ordinary;
537
Chris Lattner8e097192009-03-27 20:18:19 +0000538 case ClassTemplate:
539 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000540 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000541
Chris Lattner8e097192009-03-27 20:18:19 +0000542 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000543 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000544 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000545 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000546 case LinkageSpec:
547 case FileScopeAsm:
548 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000549 case ObjCPropertyImpl:
Chris Lattner8e097192009-03-27 20:18:19 +0000550 case Block:
551 case TranslationUnit:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000552
Chris Lattner8e097192009-03-27 20:18:19 +0000553 case UsingDirective:
554 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000555 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000556 case ClassScopeFunctionSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000557 case ObjCImplementation:
558 case ObjCCategory:
559 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000560 case Import:
Douglas Gregore93525e2010-04-22 23:19:50 +0000561 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000562 return 0;
563 }
John McCall3f746822009-11-17 05:59:44 +0000564
David Blaikiee4d798f2012-01-20 21:50:17 +0000565 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000566}
567
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000568void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000569 assert(!HasAttrs && "Decl already contains attrs.");
570
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000571 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000572 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000573
574 AttrBlank = attrs;
575 HasAttrs = true;
576}
577
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000578void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000579 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000580
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000581 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000582 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000583}
584
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000585const AttrVec &Decl::getAttrs() const {
586 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000587 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000588}
589
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000590void Decl::swapAttrs(Decl *RHS) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000591 bool HasLHSAttr = this->HasAttrs;
592 bool HasRHSAttr = RHS->HasAttrs;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000594 // Usually, neither decl has attrs, nothing to do.
595 if (!HasLHSAttr && !HasRHSAttr) return;
Mike Stump11289f42009-09-09 15:08:12 +0000596
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000597 // If 'this' has no attrs, swap the other way.
598 if (!HasLHSAttr)
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000599 return RHS->swapAttrs(this);
Mike Stump11289f42009-09-09 15:08:12 +0000600
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000601 ASTContext &Context = getASTContext();
Mike Stump11289f42009-09-09 15:08:12 +0000602
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000603 // Handle the case when both decls have attrs.
604 if (HasRHSAttr) {
Douglas Gregor78bd61f2009-06-18 16:11:24 +0000605 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS));
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000606 return;
607 }
Mike Stump11289f42009-09-09 15:08:12 +0000608
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000609 // Otherwise, LHS has an attr and RHS doesn't.
Douglas Gregor78bd61f2009-06-18 16:11:24 +0000610 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this);
611 Context.eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000612 this->HasAttrs = false;
613 RHS->HasAttrs = true;
614}
615
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000616Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000617 Decl::Kind DK = D->getDeclKind();
618 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000619#define DECL(NAME, BASE)
620#define DECL_CONTEXT(NAME) \
621 case Decl::NAME: \
622 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
623#define DECL_CONTEXT_BASE(NAME)
624#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000625 default:
Alexis Hunted053252010-05-30 07:21:58 +0000626#define DECL(NAME, BASE)
627#define DECL_CONTEXT_BASE(NAME) \
628 if (DK >= first##NAME && DK <= last##NAME) \
629 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
630#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000631 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000632 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000633}
634
635DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000636 Decl::Kind DK = D->getKind();
637 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000638#define DECL(NAME, BASE)
639#define DECL_CONTEXT(NAME) \
640 case Decl::NAME: \
641 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
642#define DECL_CONTEXT_BASE(NAME)
643#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000644 default:
Alexis Hunted053252010-05-30 07:21:58 +0000645#define DECL(NAME, BASE)
646#define DECL_CONTEXT_BASE(NAME) \
647 if (DK >= first##NAME && DK <= last##NAME) \
648 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
649#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000650 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000651 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000652}
653
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000654SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000655 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
656 // FunctionDecl stores EndRangeLoc for this purpose.
657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
658 const FunctionDecl *Definition;
659 if (FD->hasBody(Definition))
660 return Definition->getSourceRange().getEnd();
661 return SourceLocation();
662 }
663
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000664 if (Stmt *Body = getBody())
665 return Body->getSourceRange().getEnd();
666
667 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000668}
669
Anders Carlssona28908d2009-03-25 23:38:06 +0000670void Decl::CheckAccessDeclContext() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000671#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000672 // Suppress this check if any of the following hold:
673 // 1. this is the translation unit (and thus has no parent)
674 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000675 // 3. this is a non-type template parameter
676 // 4. the context is not a record
677 // 5. it's invalid
678 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000679 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000680 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000681 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000682 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000683 isInvalidDecl() ||
684 isa<StaticAssertDecl>(this) ||
685 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
686 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000687 isa<ParmVarDecl>(this) ||
688 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
689 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000690 isa<CXXRecordDecl>(this) ||
691 isa<ClassScopeFunctionSpecializationDecl>(this))
Anders Carlssonadf36b22009-08-29 20:47:47 +0000692 return;
Mike Stump11289f42009-09-09 15:08:12 +0000693
694 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000695 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000696#endif
Anders Carlssona28908d2009-03-25 23:38:06 +0000697}
698
John McCallb67608f2011-02-22 22:25:23 +0000699DeclContext *Decl::getNonClosureContext() {
John McCallfe96e0b2011-11-06 09:01:30 +0000700 return getDeclContext()->getNonClosureAncestor();
701}
702
703DeclContext *DeclContext::getNonClosureAncestor() {
704 DeclContext *DC = this;
John McCallb67608f2011-02-22 22:25:23 +0000705
706 // This is basically "while (DC->isClosure()) DC = DC->getParent();"
707 // except that it's significantly more efficient to cast to a known
708 // decl type and call getDeclContext() than to call getParent().
John McCall63b45fe2011-06-23 21:18:31 +0000709 while (isa<BlockDecl>(DC))
710 DC = cast<BlockDecl>(DC)->getDeclContext();
John McCallb67608f2011-02-22 22:25:23 +0000711
712 assert(!DC->isClosure());
713 return DC;
714}
Anders Carlssona28908d2009-03-25 23:38:06 +0000715
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000716//===----------------------------------------------------------------------===//
717// DeclContext Implementation
718//===----------------------------------------------------------------------===//
719
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000720bool DeclContext::classof(const Decl *D) {
721 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000722#define DECL(NAME, BASE)
723#define DECL_CONTEXT(NAME) case Decl::NAME:
724#define DECL_CONTEXT_BASE(NAME)
725#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000726 return true;
727 default:
Alexis Hunted053252010-05-30 07:21:58 +0000728#define DECL(NAME, BASE)
729#define DECL_CONTEXT_BASE(NAME) \
730 if (D->getKind() >= Decl::first##NAME && \
731 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000732 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000733#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000734 return false;
735 }
736}
737
Douglas Gregor9c832f72010-07-25 18:38:02 +0000738DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000739
Douglas Gregor7f737c02009-09-10 16:57:35 +0000740/// \brief Find the parent context of this context that will be
741/// used for unqualified name lookup.
742///
743/// Generally, the parent lookup context is the semantic context. However, for
744/// a friend function the parent lookup context is the lexical context, which
745/// is the class in which the friend is declared.
746DeclContext *DeclContext::getLookupParent() {
747 // FIXME: Find a better way to identify friends
748 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000749 if (getParent()->getRedeclContext()->isFileContext() &&
750 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000751 return getLexicalParent();
752
753 return getParent();
754}
755
Sebastian Redlbd595762010-08-31 20:53:31 +0000756bool DeclContext::isInlineNamespace() const {
757 return isNamespace() &&
758 cast<NamespaceDecl>(this)->isInline();
759}
760
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000761bool DeclContext::isDependentContext() const {
762 if (isFileContext())
763 return false;
764
Douglas Gregor2373c592009-05-31 09:31:02 +0000765 if (isa<ClassTemplatePartialSpecializationDecl>(this))
766 return true;
767
Douglas Gregor680e9e02012-02-21 19:11:17 +0000768 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000769 if (Record->getDescribedClassTemplate())
770 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000771
772 if (Record->isDependentLambda())
773 return true;
774 }
775
John McCallc62bb642010-03-24 05:22:00 +0000776 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000777 if (Function->getDescribedFunctionTemplate())
778 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCallc62bb642010-03-24 05:22:00 +0000780 // Friend function declarations are dependent if their *lexical*
781 // context is dependent.
782 if (cast<Decl>(this)->getFriendObjectKind())
783 return getLexicalParent()->isDependentContext();
784 }
785
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000786 return getParent() && getParent()->isDependentContext();
787}
788
Douglas Gregor07665a62009-01-05 19:45:36 +0000789bool DeclContext::isTransparentContext() const {
790 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000791 return !cast<EnumDecl>(this)->isScoped();
Douglas Gregor07665a62009-01-05 19:45:36 +0000792 else if (DeclKind == Decl::LinkageSpec)
793 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000794
795 return false;
796}
797
John McCall5fe84122010-10-26 04:59:26 +0000798bool DeclContext::isExternCContext() const {
799 const DeclContext *DC = this;
800 while (DC->DeclKind != Decl::TranslationUnit) {
801 if (DC->DeclKind == Decl::LinkageSpec)
802 return cast<LinkageSpecDecl>(DC)->getLanguage()
803 == LinkageSpecDecl::lang_c;
804 DC = DC->getParent();
805 }
806 return false;
807}
808
Rafael Espindolaf4187652013-02-14 01:18:37 +0000809bool DeclContext::isExternCXXContext() const {
810 const DeclContext *DC = this;
811 while (DC->DeclKind != Decl::TranslationUnit) {
812 if (DC->DeclKind == Decl::LinkageSpec)
813 return cast<LinkageSpecDecl>(DC)->getLanguage()
814 == LinkageSpecDecl::lang_cxx;
815 DC = DC->getParent();
816 }
817 return false;
818}
819
Sebastian Redl50c68252010-08-31 00:36:30 +0000820bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +0000821 if (getPrimaryContext() != this)
822 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +0000823
Douglas Gregore985a3b2009-08-27 06:03:53 +0000824 for (; DC; DC = DC->getParent())
825 if (DC->getPrimaryContext() == this)
826 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000827 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +0000828}
829
Steve Naroff35c62ae2009-01-08 17:28:14 +0000830DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +0000831 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000832 case Decl::TranslationUnit:
Douglas Gregor07665a62009-01-05 19:45:36 +0000833 case Decl::LinkageSpec:
Mike Stump11289f42009-09-09 15:08:12 +0000834 case Decl::Block:
Douglas Gregor91f84212008-12-11 16:49:14 +0000835 // There is only one DeclContext for these entities.
836 return this;
837
838 case Decl::Namespace:
839 // The original namespace is our primary context.
840 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
841
Douglas Gregor91f84212008-12-11 16:49:14 +0000842 case Decl::ObjCMethod:
843 return this;
844
845 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +0000846 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
847 return Def;
848
849 return this;
850
Steve Naroff35c62ae2009-01-08 17:28:14 +0000851 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +0000852 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
853 return Def;
854
855 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +0000856
Steve Naroff35c62ae2009-01-08 17:28:14 +0000857 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +0000858 return this;
859
Steve Naroff35c62ae2009-01-08 17:28:14 +0000860 case Decl::ObjCImplementation:
861 case Decl::ObjCCategoryImpl:
862 return this;
863
Douglas Gregor91f84212008-12-11 16:49:14 +0000864 default:
Alexis Hunted053252010-05-30 07:21:58 +0000865 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +0000866 // If this is a tag type that has a definition or is currently
867 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +0000868 TagDecl *Tag = cast<TagDecl>(this);
869 assert(isa<TagType>(Tag->TypeForDecl) ||
870 isa<InjectedClassNameType>(Tag->TypeForDecl));
871
872 if (TagDecl *Def = Tag->getDefinition())
873 return Def;
874
875 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) {
876 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl);
877 if (TagTy->isBeingDefined())
878 // FIXME: is it necessarily being defined in the decl
879 // that owns the type?
880 return TagTy->getDecl();
881 }
882
883 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +0000884 }
885
Alexis Hunted053252010-05-30 07:21:58 +0000886 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +0000887 "Unknown DeclContext kind");
888 return this;
889 }
890}
891
Douglas Gregore57e7522012-01-07 09:11:48 +0000892void
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000893DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +0000894 Contexts.clear();
895
896 if (DeclKind != Decl::Namespace) {
897 Contexts.push_back(this);
898 return;
Douglas Gregor91f84212008-12-11 16:49:14 +0000899 }
Douglas Gregore57e7522012-01-07 09:11:48 +0000900
901 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +0000902 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
903 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +0000904 Contexts.push_back(N);
905
906 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +0000907}
908
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000909std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +0000910DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000911 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +0000912 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000913 Decl *FirstNewDecl = 0;
914 Decl *PrevDecl = 0;
915 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000916 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
917 continue;
918
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000919 Decl *D = Decls[I];
920 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +0000921 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000922 else
923 FirstNewDecl = D;
924
925 PrevDecl = D;
926 }
927
928 return std::make_pair(FirstNewDecl, PrevDecl);
929}
930
Richard Smith645d7552013-02-07 03:37:08 +0000931/// \brief We have just acquired external visible storage, and we already have
932/// built a lookup map. For every name in the map, pull in the new names from
933/// the external storage.
934void DeclContext::reconcileExternalVisibleStorage() {
Richard Smith86a12012013-02-11 22:02:16 +0000935 assert(NeedToReconcileExternalVisibleStorage && LookupPtr.getPointer());
Richard Smith645d7552013-02-07 03:37:08 +0000936 NeedToReconcileExternalVisibleStorage = false;
937
938 StoredDeclsMap &Map = *LookupPtr.getPointer();
939 ExternalASTSource *Source = getParentASTContext().getExternalSource();
940 for (StoredDeclsMap::iterator I = Map.begin(); I != Map.end(); ++I) {
941 I->second.removeExternalDecls();
942 Source->FindExternalVisibleDeclsByName(this, I->first);
943 }
944}
945
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000946/// \brief Load the declarations within this lexical storage from an
947/// external source.
Mike Stump11289f42009-09-09 15:08:12 +0000948void
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000949DeclContext::LoadLexicalDeclsFromExternalStorage() const {
950 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000951 assert(hasExternalLexicalStorage() && Source && "No external storage?");
952
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +0000953 // Notify that we have a DeclContext that is initializing.
954 ExternalASTSource::Deserializing ADeclContext(Source);
Douglas Gregorf337ae92011-08-26 21:23:06 +0000955
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000956 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000957 SmallVector<Decl*, 64> Decls;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000958 ExternalLexicalStorage = false;
Douglas Gregor3d0adb32011-07-15 21:46:17 +0000959 switch (Source->FindExternalLexicalDecls(this, Decls)) {
960 case ELR_Success:
961 break;
962
963 case ELR_Failure:
964 case ELR_AlreadyLoaded:
965 return;
966 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000967
968 if (Decls.empty())
969 return;
970
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000971 // We may have already loaded just the fields of this record, in which case
972 // we need to ignore them.
973 bool FieldsAlreadyLoaded = false;
974 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
975 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
976
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000977 // Splice the newly-read declarations into the beginning of the list
978 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000979 Decl *ExternalFirst, *ExternalLast;
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +0000980 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls,
981 FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +0000982 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000983 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000984 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +0000985 LastDecl = ExternalLast;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000986}
987
John McCall75b960e2010-06-01 09:23:16 +0000988DeclContext::lookup_result
989ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
990 DeclarationName Name) {
991 ASTContext &Context = DC->getParentASTContext();
992 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +0000993 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +0000994 Map = DC->CreateStoredDeclsMap(Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000995
Richard Smith645d7552013-02-07 03:37:08 +0000996 // Add an entry to the map for this name, if it's not already present.
997 (*Map)[Name];
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000998
John McCall75b960e2010-06-01 09:23:16 +0000999 return DeclContext::lookup_result();
1000}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001001
John McCall75b960e2010-06-01 09:23:16 +00001002DeclContext::lookup_result
1003ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001004 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001005 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001006 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001007 StoredDeclsMap *Map;
Richard Smithf634c902012-03-16 06:12:59 +00001008 if (!(Map = DC->LookupPtr.getPointer()))
John McCall75b960e2010-06-01 09:23:16 +00001009 Map = DC->CreateStoredDeclsMap(Context);
1010
1011 StoredDeclsList &List = (*Map)[Name];
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001012 for (ArrayRef<NamedDecl*>::iterator
1013 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
John McCall75b960e2010-06-01 09:23:16 +00001014 if (List.isNull())
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001015 List.setOnlyValue(*I);
John McCall75b960e2010-06-01 09:23:16 +00001016 else
Richard Smith645d7552013-02-07 03:37:08 +00001017 // FIXME: Need declarationReplaces handling for redeclarations in modules.
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001018 List.AddSubsequentDecl(*I);
John McCall75b960e2010-06-01 09:23:16 +00001019 }
1020
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001021 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001022}
1023
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001024DeclContext::decl_iterator DeclContext::noload_decls_begin() const {
1025 return decl_iterator(FirstDecl);
1026}
1027
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001028DeclContext::decl_iterator DeclContext::decls_begin() const {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001029 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001030 LoadLexicalDeclsFromExternalStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001031
Mike Stump11289f42009-09-09 15:08:12 +00001032 return decl_iterator(FirstDecl);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001033}
1034
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001035bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001036 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001037 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001038
1039 return !FirstDecl;
1040}
1041
John McCall84d87672009-12-10 09:41:52 +00001042void DeclContext::removeDecl(Decl *D) {
1043 assert(D->getLexicalDeclContext() == this &&
1044 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001045 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001046 "decl is not in decls list");
1047
1048 // Remove D from the decl chain. This is O(n) but hopefully rare.
1049 if (D == FirstDecl) {
1050 if (D == LastDecl)
1051 FirstDecl = LastDecl = 0;
1052 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001053 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001054 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001055 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001056 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001057 if (I->NextInContextAndBits.getPointer() == D) {
1058 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001059 if (D == LastDecl) LastDecl = I;
1060 break;
1061 }
1062 }
1063 }
1064
1065 // Mark that D is no longer in the decl chain.
Douglas Gregor781f7132012-01-06 16:59:53 +00001066 D->NextInContextAndBits.setPointer(0);
John McCall84d87672009-12-10 09:41:52 +00001067
1068 // Remove D from the lookup table if necessary.
1069 if (isa<NamedDecl>(D)) {
1070 NamedDecl *ND = cast<NamedDecl>(D);
1071
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001072 // Remove only decls that have a name
1073 if (!ND->getDeclName()) return;
1074
Richard Smithf634c902012-03-16 06:12:59 +00001075 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr.getPointer();
John McCallc62bb642010-03-24 05:22:00 +00001076 if (!Map) return;
John McCall84d87672009-12-10 09:41:52 +00001077
John McCall84d87672009-12-10 09:41:52 +00001078 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1079 assert(Pos != Map->end() && "no lookup entry for decl");
Axel Naumannfbc7b982011-11-08 18:21:06 +00001080 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1081 Pos->second.remove(ND);
John McCall84d87672009-12-10 09:41:52 +00001082 }
1083}
1084
John McCalld1e9d832009-08-11 06:59:38 +00001085void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001086 assert(D->getLexicalDeclContext() == this &&
1087 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001088 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001089 "Decl already inserted into a DeclContext");
1090
1091 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001092 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001093 LastDecl = D;
1094 } else {
1095 FirstDecl = LastDecl = D;
1096 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001097
1098 // Notify a C++ record declaration that we've added a member, so it can
1099 // update it's class-specific state.
1100 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1101 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001102
1103 // If this is a newly-created (not de-serialized) import declaration, wire
1104 // it in to the list of local import declarations.
1105 if (!D->isFromASTFile()) {
1106 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1107 D->getASTContext().addedLocalImportDecl(Import);
1108 }
John McCalld1e9d832009-08-11 06:59:38 +00001109}
1110
1111void DeclContext::addDecl(Decl *D) {
1112 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001113
1114 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001115 ND->getDeclContext()->getPrimaryContext()->
1116 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001117}
1118
Sean Callanan95e74be2011-10-21 02:57:43 +00001119void DeclContext::addDeclInternal(Decl *D) {
1120 addHiddenDecl(D);
1121
1122 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001123 ND->getDeclContext()->getPrimaryContext()->
1124 makeDeclVisibleInContextWithFlags(ND, true, true);
1125}
1126
1127/// shouldBeHidden - Determine whether a declaration which was declared
1128/// within its semantic context should be invisible to qualified name lookup.
1129static bool shouldBeHidden(NamedDecl *D) {
1130 // Skip unnamed declarations.
1131 if (!D->getDeclName())
1132 return true;
1133
1134 // Skip entities that can't be found by name lookup into a particular
1135 // context.
1136 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1137 D->isTemplateParameter())
1138 return true;
1139
1140 // Skip template specializations.
1141 // FIXME: This feels like a hack. Should DeclarationName support
1142 // template-ids, or is there a better way to keep specializations
1143 // from being visible?
1144 if (isa<ClassTemplateSpecializationDecl>(D))
1145 return true;
1146 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1147 if (FD->isFunctionTemplateSpecialization())
1148 return true;
1149
1150 return false;
1151}
1152
1153/// buildLookup - Build the lookup data structure with all of the
1154/// declarations in this DeclContext (and any other contexts linked
1155/// to it or transparent contexts nested within it) and return it.
1156StoredDeclsMap *DeclContext::buildLookup() {
1157 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1158
Richard Smith86a12012013-02-11 22:02:16 +00001159 // FIXME: Should we keep going if hasExternalVisibleStorage?
Richard Smithf634c902012-03-16 06:12:59 +00001160 if (!LookupPtr.getInt())
1161 return LookupPtr.getPointer();
1162
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001163 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001164 collectAllContexts(Contexts);
1165 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1166 buildLookupImpl(Contexts[I]);
1167
1168 // We no longer have any lazy decls.
1169 LookupPtr.setInt(false);
Richard Smith86a12012013-02-11 22:02:16 +00001170 NeedToReconcileExternalVisibleStorage = false;
Richard Smithf634c902012-03-16 06:12:59 +00001171 return LookupPtr.getPointer();
1172}
1173
1174/// buildLookupImpl - Build part of the lookup data structure for the
1175/// declarations contained within DCtx, which will either be this
1176/// DeclContext, a DeclContext linked to it, or a transparent context
1177/// nested within it.
1178void DeclContext::buildLookupImpl(DeclContext *DCtx) {
1179 for (decl_iterator I = DCtx->decls_begin(), E = DCtx->decls_end();
1180 I != E; ++I) {
1181 Decl *D = *I;
1182
1183 // Insert this declaration into the lookup structure, but only if
1184 // it's semantically within its decl context. Any other decls which
1185 // should be found in this context are added eagerly.
1186 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1187 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND))
1188 makeDeclVisibleInContextImpl(ND, false);
1189
1190 // If this declaration is itself a transparent declaration context
1191 // or inline namespace, add the members of this declaration of that
1192 // context (recursively).
1193 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1194 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1195 buildLookupImpl(InnerCtx);
1196 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001197}
1198
Mike Stump11289f42009-09-09 15:08:12 +00001199DeclContext::lookup_result
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001200DeclContext::lookup(DeclarationName Name) {
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001201 assert(DeclKind != Decl::LinkageSpec &&
1202 "Should not perform lookups into linkage specs!");
1203
Steve Naroff35c62ae2009-01-08 17:28:14 +00001204 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor91f84212008-12-11 16:49:14 +00001205 if (PrimaryContext != this)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001206 return PrimaryContext->lookup(Name);
Douglas Gregor91f84212008-12-11 16:49:14 +00001207
Richard Smith05afe5e2012-03-13 03:12:56 +00001208 if (hasExternalVisibleStorage()) {
Richard Smith645d7552013-02-07 03:37:08 +00001209 StoredDeclsMap *Map = LookupPtr.getPointer();
1210 if (LookupPtr.getInt())
1211 Map = buildLookup();
Richard Smith86a12012013-02-11 22:02:16 +00001212 else if (NeedToReconcileExternalVisibleStorage)
1213 reconcileExternalVisibleStorage();
Richard Smith645d7552013-02-07 03:37:08 +00001214
Richard Smith75fc3bf2013-02-08 00:37:45 +00001215 if (!Map)
1216 Map = CreateStoredDeclsMap(getParentASTContext());
1217
Richard Smith645d7552013-02-07 03:37:08 +00001218 // If a PCH/module has a result for this name, and we have a local
1219 // declaration, we will have imported the PCH/module result when adding the
1220 // local declaration or when reconciling the module.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001221 std::pair<StoredDeclsMap::iterator, bool> R =
1222 Map->insert(std::make_pair(Name, StoredDeclsList()));
1223 if (!R.second)
1224 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001225
John McCall75b960e2010-06-01 09:23:16 +00001226 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Richard Smith9ce12e32013-02-07 03:30:24 +00001227 if (Source->FindExternalVisibleDeclsByName(this, Name)) {
1228 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1229 StoredDeclsMap::iterator I = Map->find(Name);
1230 if (I != Map->end())
1231 return I->second.getLookupResult();
1232 }
1233 }
1234
1235 return lookup_result(lookup_iterator(0), lookup_iterator(0));
John McCall75b960e2010-06-01 09:23:16 +00001236 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001237
Richard Smithf634c902012-03-16 06:12:59 +00001238 StoredDeclsMap *Map = LookupPtr.getPointer();
1239 if (LookupPtr.getInt())
1240 Map = buildLookup();
1241
1242 if (!Map)
1243 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1244
1245 StoredDeclsMap::iterator I = Map->find(Name);
1246 if (I == Map->end())
1247 return lookup_result(lookup_iterator(0), lookup_iterator(0));
1248
1249 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001250}
1251
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001252void DeclContext::localUncachedLookup(DeclarationName Name,
1253 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001254 Results.clear();
1255
1256 // If there's no external storage, just perform a normal lookup and copy
1257 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001258 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001259 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001260 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001261 return;
1262 }
1263
1264 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith645d7552013-02-07 03:37:08 +00001265 if (Name && !LookupPtr.getInt()) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001266 if (StoredDeclsMap *Map = LookupPtr.getPointer()) {
1267 StoredDeclsMap::iterator Pos = Map->find(Name);
1268 if (Pos != Map->end()) {
1269 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001270 Pos->second.getLookupResult().begin(),
1271 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001272 return;
1273 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001274 }
1275 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001276
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001277 // Slow case: grovel through the declarations in our chain looking for
1278 // matches.
1279 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1280 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1281 if (ND->getDeclName() == Name)
1282 Results.push_back(ND);
1283 }
1284}
1285
Sebastian Redl50c68252010-08-31 00:36:30 +00001286DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001287 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001288 // Skip through transparent contexts.
1289 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001290 Ctx = Ctx->getParent();
1291 return Ctx;
1292}
1293
Douglas Gregorf47b9112009-02-25 22:02:03 +00001294DeclContext *DeclContext::getEnclosingNamespaceContext() {
1295 DeclContext *Ctx = this;
1296 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001297 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001298 Ctx = Ctx->getParent();
1299 return Ctx->getPrimaryContext();
1300}
1301
Sebastian Redl50c68252010-08-31 00:36:30 +00001302bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1303 // For non-file contexts, this is equivalent to Equals.
1304 if (!isFileContext())
1305 return O->Equals(this);
1306
1307 do {
1308 if (O->Equals(this))
1309 return true;
1310
1311 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1312 if (!NS || !NS->isInline())
1313 break;
1314 O = NS->getParent();
1315 } while (O);
1316
1317 return false;
1318}
1319
Richard Smithf634c902012-03-16 06:12:59 +00001320void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1321 DeclContext *PrimaryDC = this->getPrimaryContext();
1322 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1323 // If the decl is being added outside of its semantic decl context, we
1324 // need to ensure that we eagerly build the lookup information for it.
1325 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001326}
1327
Richard Smithf634c902012-03-16 06:12:59 +00001328void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1329 bool Recoverable) {
1330 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001331
Richard Smith05afe5e2012-03-13 03:12:56 +00001332 // Skip declarations within functions.
1333 // FIXME: We shouldn't need to build lookup tables for function declarations
1334 // ever, and we can't do so correctly because we can't model the nesting of
1335 // scopes which occurs within functions. We use "qualified" lookup into
1336 // function declarations when handling friend declarations inside nested
1337 // classes, and consequently accept the following invalid code:
1338 //
1339 // void f() { void g(); { int g; struct S { friend void g(); }; } }
1340 if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
1341 return;
1342
Richard Smithf634c902012-03-16 06:12:59 +00001343 // Skip declarations which should be invisible to name lookup.
1344 if (shouldBeHidden(D))
1345 return;
1346
1347 // If we already have a lookup data structure, perform the insertion into
1348 // it. If we might have externally-stored decls with this name, look them
1349 // up and perform the insertion. If this decl was declared outside its
1350 // semantic context, buildLookup won't add it, so add it now.
1351 //
1352 // FIXME: As a performance hack, don't add such decls into the translation
1353 // unit unless we're in C++, since qualified lookup into the TU is never
1354 // performed.
1355 if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
1356 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1357 (getParentASTContext().getLangOpts().CPlusPlus ||
1358 !isTranslationUnit()))) {
1359 // If we have lazily omitted any decls, they might have the same name as
1360 // the decl which we are adding, so build a full lookup table before adding
1361 // this decl.
1362 buildLookup();
1363 makeDeclVisibleInContextImpl(D, Internal);
1364 } else {
1365 LookupPtr.setInt(true);
1366 }
1367
1368 // If we are a transparent context or inline namespace, insert into our
1369 // parent context, too. This operation is recursive.
1370 if (isTransparentContext() || isInlineNamespace())
1371 getParent()->getPrimaryContext()->
1372 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1373
1374 Decl *DCAsDecl = cast<Decl>(this);
1375 // Notify that a decl was made visible unless we are a Tag being defined.
1376 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1377 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1378 L->AddedVisibleDecl(this, D);
1379}
1380
1381void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1382 // Find or create the stored declaration map.
1383 StoredDeclsMap *Map = LookupPtr.getPointer();
1384 if (!Map) {
1385 ASTContext *C = &getParentASTContext();
1386 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001387 }
1388
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001389 // If there is an external AST source, load any declarations it knows about
1390 // with this declaration's name.
1391 // If the lookup table contains an entry about this name it means that we
1392 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001393 if (!Internal)
1394 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1395 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001396 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001397 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001398
Douglas Gregor91f84212008-12-11 16:49:14 +00001399 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001400 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Chris Lattnercaae7162009-02-20 01:44:05 +00001401 if (DeclNameEntries.isNull()) {
1402 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001403 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001404 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001405
Richard Smithf634c902012-03-16 06:12:59 +00001406 if (DeclNameEntries.HandleRedeclaration(D)) {
1407 // This declaration has replaced an existing one for which
1408 // declarationReplaces returns true.
1409 return;
1410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
Richard Smithf634c902012-03-16 06:12:59 +00001412 // Put this declaration into the appropriate slot.
1413 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001414}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001415
1416/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1417/// this context.
Mike Stump11289f42009-09-09 15:08:12 +00001418DeclContext::udir_iterator_range
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001419DeclContext::getUsingDirectives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001420 // FIXME: Use something more efficient than normal lookup for using
1421 // directives. In C++, using directives are looked up more than anything else.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001422 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001423 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.begin()),
1424 reinterpret_cast<udir_iterator>(Result.end()));
Douglas Gregor889ceb72009-02-03 19:21:40 +00001425}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001426
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001427//===----------------------------------------------------------------------===//
1428// Creation and Destruction of StoredDeclsMaps. //
1429//===----------------------------------------------------------------------===//
1430
John McCallc62bb642010-03-24 05:22:00 +00001431StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smithf634c902012-03-16 06:12:59 +00001432 assert(!LookupPtr.getPointer() && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001433 assert(getPrimaryContext() == this &&
1434 "creating decls map on non-primary context");
1435
1436 StoredDeclsMap *M;
1437 bool Dependent = isDependentContext();
1438 if (Dependent)
1439 M = new DependentStoredDeclsMap();
1440 else
1441 M = new StoredDeclsMap();
1442 M->Previous = C.LastSDM;
1443 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smithf634c902012-03-16 06:12:59 +00001444 LookupPtr.setPointer(M);
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001445 return M;
1446}
1447
1448void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001449 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1450 // pointer because the subclass doesn't add anything that needs to
1451 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001452 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1453}
1454
1455void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1456 while (Map) {
1457 // Advance the iteration before we invalidate memory.
1458 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1459
1460 if (Dependent)
1461 delete static_cast<DependentStoredDeclsMap*>(Map);
1462 else
1463 delete Map;
1464
1465 Map = Next.getPointer();
1466 Dependent = Next.getInt();
1467 }
1468}
1469
John McCallc62bb642010-03-24 05:22:00 +00001470DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1471 DeclContext *Parent,
1472 const PartialDiagnostic &PDiag) {
1473 assert(Parent->isDependentContext()
1474 && "cannot iterate dependent diagnostics of non-dependent context");
1475 Parent = Parent->getPrimaryContext();
Richard Smithf634c902012-03-16 06:12:59 +00001476 if (!Parent->LookupPtr.getPointer())
John McCallc62bb642010-03-24 05:22:00 +00001477 Parent->CreateStoredDeclsMap(C);
1478
1479 DependentStoredDeclsMap *Map
Richard Smithf634c902012-03-16 06:12:59 +00001480 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer());
John McCallc62bb642010-03-24 05:22:00 +00001481
Douglas Gregora55530e2010-03-29 23:56:53 +00001482 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001483 // BumpPtrAllocator, rather than the ASTContext itself.
Douglas Gregora55530e2010-03-29 23:56:53 +00001484 PartialDiagnostic::Storage *DiagStorage = 0;
1485 if (PDiag.hasStorage())
1486 DiagStorage = new (C) PartialDiagnostic::Storage;
1487
1488 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001489
1490 // TODO: Maybe we shouldn't reverse the order during insertion.
1491 DD->NextDiagnostic = Map->FirstDiagnostic;
1492 Map->FirstDiagnostic = DD;
1493
1494 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001495}