blob: 6111abab646e9c6a8130786adc7c0f01ce0ae8c1 [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"
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
James Y Knight53c76162015-07-17 18:21:37 +000047#define DECL(DERIVED, BASE) \
Benjamin Kramerc3f89252016-10-20 14:27:22 +000048 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
James Y Knight53c76162015-07-17 18:21:37 +000049 "Alignment sufficient after objects prepended to " #DERIVED);
50#define ABSTRACT_DECL(DECL)
51#include "clang/AST/DeclNodes.inc"
52
Richard Smithf7981722013-11-22 09:01:48 +000053void *Decl::operator new(std::size_t Size, const ASTContext &Context,
54 unsigned ID, std::size_t Extra) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000055 // Allocate an extra 8 bytes worth of storage, which ensures that the
James Y Knight53c76162015-07-17 18:21:37 +000056 // resulting pointer will still be 8-byte aligned.
Benjamin Kramerc3f89252016-10-20 14:27:22 +000057 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
James Y Knight53c76162015-07-17 18:21:37 +000058 "Decl won't be misaligned");
Richard Smithf7981722013-11-22 09:01:48 +000059 void *Start = Context.Allocate(Size + Extra + 8);
Douglas Gregor52261fd2012-01-05 23:49:36 +000060 void *Result = (char*)Start + 8;
Richard Smithf7981722013-11-22 09:01:48 +000061
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000062 unsigned *PrefixPtr = (unsigned *)Result - 2;
Richard Smithf7981722013-11-22 09:01:48 +000063
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000064 // Zero out the first 4 bytes; this is used to store the owning module ID.
65 PrefixPtr[0] = 0;
Richard Smithf7981722013-11-22 09:01:48 +000066
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000067 // Store the global declaration ID in the second 4 bytes.
68 PrefixPtr[1] = ID;
Richard Smithf7981722013-11-22 09:01:48 +000069
Douglas Gregor64af53c2012-01-05 22:27:05 +000070 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000071}
72
Richard Smithf7981722013-11-22 09:01:48 +000073void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
74 DeclContext *Parent, std::size_t Extra) {
75 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
Richard Smith42413142015-05-15 20:05:43 +000076 // With local visibility enabled, we track the owning module even for local
77 // declarations.
78 if (Ctx.getLangOpts().ModulesLocalVisibility) {
James Y Knight53c76162015-07-17 18:21:37 +000079 // Ensure required alignment of the resulting object by adding extra
80 // padding at the start if required.
81 size_t ExtraAlign =
Benjamin Kramerc3f89252016-10-20 14:27:22 +000082 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
James Y Knight53c76162015-07-17 18:21:37 +000083 char *Buffer = reinterpret_cast<char *>(
84 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
85 Buffer += ExtraAlign;
Richard Smith42413142015-05-15 20:05:43 +000086 return new (Buffer) Module*(nullptr) + 1;
87 }
Richard Smithf7981722013-11-22 09:01:48 +000088 return ::operator new(Size + Extra, Ctx);
89}
90
Douglas Gregorc147b0b2013-01-12 01:29:50 +000091Module *Decl::getOwningModuleSlow() const {
92 assert(isFromASTFile() && "Not from AST file?");
93 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
94}
95
Richard Smith87bb5692015-06-09 00:35:49 +000096bool Decl::hasLocalOwningModuleStorage() const {
97 return getASTContext().getLangOpts().ModulesLocalVisibility;
98}
99
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000100const char *Decl::getDeclKindName() const {
101 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000102 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000103#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
104#define ABSTRACT_DECL(DECL)
105#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000106 }
107}
108
Douglas Gregor90d47172010-03-05 00:26:45 +0000109void Decl::setInvalidDecl(bool Invalid) {
110 InvalidDecl = Invalid;
Alp Tokera5d64592013-12-21 01:10:54 +0000111 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Richard Trieucbd54302016-11-11 20:51:04 +0000112 if (!Invalid) {
113 return;
114 }
115
116 if (!isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +0000117 // Defensive maneuver for ill-formed code: we're likely not to make it to
118 // a point where we set the access specifier, so default it to "public"
119 // to avoid triggering asserts elsewhere in the front end.
120 setAccess(AS_public);
121 }
Richard Trieucbd54302016-11-11 20:51:04 +0000122
123 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
124 // are invalid too.
125 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
126 for (BindingDecl *Binding : DD->bindings()) {
127 Binding->setInvalidDecl();
128 }
129 }
Douglas Gregor90d47172010-03-05 00:26:45 +0000130}
131
Steve Naroff5faaef72009-01-20 19:53:53 +0000132const char *DeclContext::getDeclKindName() const {
133 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000134 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000135#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
136#define ABSTRACT_DECL(DECL)
137#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000138 }
139}
140
Daniel Dunbar62905572012-03-05 21:42:49 +0000141bool Decl::StatisticsEnabled = false;
142void Decl::EnableStatistics() {
143 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000144}
145
146void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000147 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000148
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000149 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000150#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
151#define ABSTRACT_DECL(DECL)
152#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000153 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000154
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000155 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000156#define DECL(DERIVED, BASE) \
157 if (n##DERIVED##s > 0) { \
158 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000159 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
160 << sizeof(DERIVED##Decl) << " each (" \
161 << n##DERIVED##s * sizeof(DERIVED##Decl) \
162 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000163 }
Alexis Hunted053252010-05-30 07:21:58 +0000164#define ABSTRACT_DECL(DECL)
165#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000167 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000168}
169
Alexis Hunted053252010-05-30 07:21:58 +0000170void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000171 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000172#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
173#define ABSTRACT_DECL(DECL)
174#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000175 }
176}
177
Anders Carlssonaa73b912009-06-13 00:08:58 +0000178bool Decl::isTemplateParameterPack() const {
179 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
180 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000181 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000182 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000183 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000184 if (const TemplateTemplateParmDecl *TTP
185 = dyn_cast<TemplateTemplateParmDecl>(this))
186 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000187 return false;
188}
189
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000190bool Decl::isParameterPack() const {
191 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
192 return Parm->isParameterPack();
193
194 return isTemplateParameterPack();
195}
196
Alp Tokera2794f92014-01-22 07:29:52 +0000197FunctionDecl *Decl::getAsFunction() {
198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
199 return FD;
200 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
201 return FTD->getTemplatedDecl();
Craig Topper36250ad2014-05-12 05:36:57 +0000202 return nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000203}
204
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000205bool Decl::isTemplateDecl() const {
206 return isa<TemplateDecl>(this);
207}
208
Serge Pavlov7dcc97e2016-04-19 06:19:52 +0000209TemplateDecl *Decl::getDescribedTemplate() const {
210 if (auto *FD = dyn_cast<FunctionDecl>(this))
211 return FD->getDescribedFunctionTemplate();
212 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
213 return RD->getDescribedClassTemplate();
214 else if (auto *VD = dyn_cast<VarDecl>(this))
215 return VD->getDescribedVarTemplate();
216
217 return nullptr;
218}
219
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000220const DeclContext *Decl::getParentFunctionOrMethod() const {
221 for (const DeclContext *DC = getDeclContext();
222 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000223 DC = DC->getParent())
224 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000225 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000226
Craig Topper36250ad2014-05-12 05:36:57 +0000227 return nullptr;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000228}
229
Douglas Gregor133eddd2011-02-17 08:47:29 +0000230
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000231//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000232// PrettyStackTraceDecl Implementation
233//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000235void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000236 SourceLocation TheLoc = Loc;
237 if (TheLoc.isInvalid() && TheDecl)
238 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattnereae6cb62009-03-05 08:00:35 +0000240 if (TheLoc.isValid()) {
241 TheLoc.print(OS, SM);
242 OS << ": ";
243 }
244
245 OS << Message;
246
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000247 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
248 OS << " '";
249 DN->printQualifiedName(OS);
250 OS << '\'';
251 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000252 OS << '\n';
253}
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnereae6cb62009-03-05 08:00:35 +0000255//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000256// Decl Implementation
257//===----------------------------------------------------------------------===//
258
Douglas Gregorb11aad82011-02-19 18:51:44 +0000259// Out-of-line virtual method providing a home for Decl.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000260Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000261
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000262void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000263 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000264}
265
266void Decl::setLexicalDeclContext(DeclContext *DC) {
267 if (DC == getLexicalDeclContext())
268 return;
269
270 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000271 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000272 } else {
273 getMultipleDC()->LexicalDC = DC;
274 }
Richard Smith5327b892015-07-01 19:32:54 +0000275 Hidden = cast<Decl>(DC)->Hidden;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000276}
277
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000278void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
279 ASTContext &Ctx) {
280 if (SemaDC == LexicalDC) {
281 DeclCtx = SemaDC;
282 } else {
283 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
284 MDC->SemanticDC = SemaDC;
285 MDC->LexicalDC = LexicalDC;
286 DeclCtx = MDC;
287 }
288}
289
Serge Pavlov73c6a242015-08-23 10:22:28 +0000290bool Decl::isLexicallyWithinFunctionOrMethod() const {
291 const DeclContext *LDC = getLexicalDeclContext();
Serge Pavlovb24a7112015-08-23 11:09:40 +0000292 while (true) {
Serge Pavlov73c6a242015-08-23 10:22:28 +0000293 if (LDC->isFunctionOrMethod())
294 return true;
295 if (!isa<TagDecl>(LDC))
296 return false;
Serge Pavlovb24a7112015-08-23 11:09:40 +0000297 LDC = LDC->getLexicalParent();
298 }
Serge Pavlov73c6a242015-08-23 10:22:28 +0000299 return false;
300}
301
John McCall4fa53422009-10-01 00:25:31 +0000302bool Decl::isInAnonymousNamespace() const {
303 const DeclContext *DC = getDeclContext();
304 do {
305 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
306 if (ND->isAnonymousNamespace())
307 return true;
308 } while ((DC = DC->getParent()));
309
310 return false;
311}
312
Richard Trieuc771d5d2014-05-28 02:16:01 +0000313bool Decl::isInStdNamespace() const {
314 return getDeclContext()->isStdNamespace();
315}
316
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000317TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000318 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
319 return TUD;
320
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000321 DeclContext *DC = getDeclContext();
322 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000323
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000324 while (!DC->isTranslationUnit()) {
325 DC = DC->getParent();
326 assert(DC && "This decl is not contained in a translation unit!");
327 }
Mike Stump11289f42009-09-09 15:08:12 +0000328
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000329 return cast<TranslationUnitDecl>(DC);
330}
331
332ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000333 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000334}
335
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000336ASTMutationListener *Decl::getASTMutationListener() const {
337 return getASTContext().getASTMutationListener();
338}
339
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000340unsigned Decl::getMaxAlignment() const {
341 if (!hasAttrs())
342 return 0;
343
344 unsigned Align = 0;
345 const AttrVec &V = getAttrs();
346 ASTContext &Ctx = getASTContext();
347 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
348 for (; I != E; ++I)
349 Align = std::max(Align, I->getAlignment(Ctx));
350 return Align;
351}
352
Vassil Vassilev928c8252016-04-28 14:13:28 +0000353bool Decl::isUsed(bool CheckUsedAttr) const {
354 const Decl *CanonD = getCanonicalDecl();
355 if (CanonD->Used)
Vassil Vassileva4d7d782016-04-27 10:46:06 +0000356 return true;
357
Vassil Vassilev928c8252016-04-28 14:13:28 +0000358 // Check for used attribute.
359 // Ask the most recent decl, since attributes accumulate in the redecl chain.
360 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
361 return true;
362
363 // The information may have not been deserialized yet. Force deserialization
364 // to complete the needed information.
365 return getMostRecentDecl()->getCanonicalDecl()->Used;
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000366}
367
Eli Friedman276dd182013-09-05 00:02:25 +0000368void Decl::markUsed(ASTContext &C) {
Vassil Vassilev928c8252016-04-28 14:13:28 +0000369 if (isUsed(false))
Eli Friedman276dd182013-09-05 00:02:25 +0000370 return;
371
372 if (C.getASTMutationListener())
373 C.getASTMutationListener()->DeclarationMarkedUsed(this);
374
Vassil Vassilev928c8252016-04-28 14:13:28 +0000375 setIsUsed();
Eli Friedman276dd182013-09-05 00:02:25 +0000376}
377
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000378bool Decl::isReferenced() const {
379 if (Referenced)
380 return true;
381
382 // Check redeclarations.
Aaron Ballman86c93902014-03-06 23:45:36 +0000383 for (auto I : redecls())
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000384 if (I->Referenced)
385 return true;
386
387 return false;
388}
389
Richard Smith3b660562016-09-26 21:27:23 +0000390bool Decl::isExported() const {
391 if (isModulePrivate())
392 return false;
393 // Namespaces are always exported.
394 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
395 return true;
396 // Otherwise, this is a strictly lexical check.
397 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
398 if (cast<Decl>(DC)->isModulePrivate())
399 return false;
400 if (isa<ExportDecl>(DC))
401 return true;
402 }
403 return false;
404}
405
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000406bool Decl::hasDefiningAttr() const {
407 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
408}
409
410const Attr *Decl::getDefiningAttr() const {
411 if (AliasAttr *AA = getAttr<AliasAttr>())
412 return AA;
413 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
414 return IFA;
415 return nullptr;
416}
417
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000418/// \brief Determine the availability of the given declaration based on
419/// the target platform.
420///
421/// When it returns an availability result other than \c AR_Available,
422/// if the \p Message parameter is non-NULL, it will be set to a
423/// string describing why the entity is unavailable.
424///
425/// FIXME: Make these strings localizable, since they end up in
426/// diagnostics.
427static AvailabilityResult CheckAvailability(ASTContext &Context,
428 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000429 std::string *Message,
430 VersionTuple EnclosingVersion) {
431 if (EnclosingVersion.empty())
432 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000433
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000434 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000435 return AR_Available;
436
Bob Wilsonb111ec92015-03-02 19:01:14 +0000437 // Check if this is an App Extension "platform", and if so chop off
438 // the suffix for matching with the actual platform.
439 StringRef ActualPlatform = A->getPlatform()->getName();
440 StringRef RealizedPlatform = ActualPlatform;
441 if (Context.getLangOpts().AppExt) {
442 size_t suffix = RealizedPlatform.rfind("_app_extension");
443 if (suffix != StringRef::npos)
444 RealizedPlatform = RealizedPlatform.slice(0, suffix);
445 }
446
447 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
448
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000449 // Match the platform name.
Bob Wilsonb111ec92015-03-02 19:01:14 +0000450 if (RealizedPlatform != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000451 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000452
453 StringRef PrettyPlatformName
454 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
455
456 if (PrettyPlatformName.empty())
457 PrettyPlatformName = ActualPlatform;
458
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000459 std::string HintMessage;
460 if (!A->getMessage().empty()) {
461 HintMessage = " - ";
462 HintMessage += A->getMessage();
463 }
464
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000465 // Make sure that this declaration has not been marked 'unavailable'.
466 if (A->getUnavailable()) {
467 if (Message) {
468 Message->clear();
469 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000470 Out << "not available on " << PrettyPlatformName
471 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000472 }
473
474 return AR_Unavailable;
475 }
476
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000477 // Make sure that this declaration has already been introduced.
478 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000479 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000480 if (Message) {
481 Message->clear();
482 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000483 VersionTuple VTI(A->getIntroduced());
484 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000485 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000486 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000487 }
488
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000489 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000490 }
491
492 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000493 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000494 if (Message) {
495 Message->clear();
496 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000497 VersionTuple VTO(A->getObsoleted());
498 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000499 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000500 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000501 }
502
503 return AR_Unavailable;
504 }
505
506 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000507 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000508 if (Message) {
509 Message->clear();
510 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000511 VersionTuple VTD(A->getDeprecated());
512 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000513 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000514 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000515 }
516
517 return AR_Deprecated;
518 }
519
520 return AR_Available;
521}
522
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000523AvailabilityResult Decl::getAvailability(std::string *Message,
524 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000525 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000526 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000527
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000528 AvailabilityResult Result = AR_Available;
529 std::string ResultMessage;
530
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000531 for (const auto *A : attrs()) {
532 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000533 if (Result >= AR_Deprecated)
534 continue;
535
536 if (Message)
537 ResultMessage = Deprecated->getMessage();
538
539 Result = AR_Deprecated;
540 continue;
541 }
542
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000543 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000544 if (Message)
545 *Message = Unavailable->getMessage();
546 return AR_Unavailable;
547 }
548
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000549 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000550 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000551 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000552
553 if (AR == AR_Unavailable)
554 return AR_Unavailable;
555
556 if (AR > Result) {
557 Result = AR;
558 if (Message)
559 ResultMessage.swap(*Message);
560 }
561 continue;
562 }
563 }
564
565 if (Message)
566 Message->swap(ResultMessage);
567 return Result;
568}
569
570bool Decl::canBeWeakImported(bool &IsDefinition) const {
571 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000572
573 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000574 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000575 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000576 IsDefinition = true;
577 return false;
578 }
John McCall5fb5df92012-06-20 06:18:46 +0000579 return true;
580
581 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000582 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
583 if (FD->hasBody()) {
584 IsDefinition = true;
585 return false;
586 }
John McCall5fb5df92012-06-20 06:18:46 +0000587 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000588
John McCall5fb5df92012-06-20 06:18:46 +0000589 // Objective-C classes, if this is the non-fragile runtime.
590 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000591 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000592 return true;
593
594 // Nothing else.
595 } else {
596 return false;
597 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000598}
599
600bool Decl::isWeakImported() const {
601 bool IsDefinition;
602 if (!canBeWeakImported(IsDefinition))
603 return false;
604
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000605 for (const auto *A : attrs()) {
606 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000607 return true;
608
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000609 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000610 if (CheckAvailability(getASTContext(), Availability, nullptr,
611 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000612 return true;
613 }
614 }
615
616 return false;
617}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000618
Chris Lattner8e097192009-03-27 20:18:19 +0000619unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
620 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000621 case Function:
622 case CXXMethod:
623 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000624 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000625 case CXXDestructor:
626 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000627 case EnumConstant:
628 case Var:
Richard Smithbdb84f32016-07-22 23:36:59 +0000629 case Binding:
Chris Lattner8e097192009-03-27 20:18:19 +0000630 case ImplicitParam:
631 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000632 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000633 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000634 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000635 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000636 case Label:
637 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000638 case IndirectField:
639 return IDNS_Ordinary | IDNS_Member;
640
Richard Smith9f951822016-01-06 22:49:11 +0000641 case NonTypeTemplateParm:
642 // Non-type template parameters are not found by lookups that ignore
643 // non-types, but they are found by redeclaration lookups for tag types,
644 // so we include them in the tag namespace.
645 return IDNS_Ordinary | IDNS_Tag;
646
John McCalle87beb22010-04-23 18:46:30 +0000647 case ObjCCompatibleAlias:
648 case ObjCInterface:
649 return IDNS_Ordinary | IDNS_Type;
650
651 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000652 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000653 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000654 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000655 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000656 return IDNS_Ordinary | IDNS_Type;
657
Richard Smith151c4562016-12-20 21:35:28 +0000658 case UnresolvedUsingTypename:
659 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
660
John McCall3f746822009-11-17 05:59:44 +0000661 case UsingShadow:
662 return 0; // we'll actually overwrite this later
663
John McCalle61f2ba2009-11-18 02:36:19 +0000664 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000665 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000666
667 case Using:
Richard Smith151c4562016-12-20 21:35:28 +0000668 case UsingPack:
John McCall3f746822009-11-17 05:59:44 +0000669 return IDNS_Using;
670
Chris Lattner8e097192009-03-27 20:18:19 +0000671 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000672 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattner8e097192009-03-27 20:18:19 +0000674 case Field:
675 case ObjCAtDefsField:
676 case ObjCIvar:
677 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattner8e097192009-03-27 20:18:19 +0000679 case Record:
680 case CXXRecord:
681 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000682 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner8e097192009-03-27 20:18:19 +0000684 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000685 case NamespaceAlias:
686 return IDNS_Namespace;
687
Chris Lattner8e097192009-03-27 20:18:19 +0000688 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000689 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000690 return IDNS_Ordinary;
691
Chris Lattner8e097192009-03-27 20:18:19 +0000692 case ClassTemplate:
693 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000694 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000695
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000696 case OMPDeclareReduction:
697 return IDNS_OMPReduction;
698
Chris Lattner8e097192009-03-27 20:18:19 +0000699 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000700 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000701 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000702 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000703 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000704 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000705 case FileScopeAsm:
706 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000707 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000708 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000709 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000710 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000711 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000712 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000713 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000714 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000715
Chris Lattner8e097192009-03-27 20:18:19 +0000716 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000717 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000718 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000719 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000720 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000721 case VarTemplateSpecialization:
722 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000723 case ObjCImplementation:
724 case ObjCCategory:
725 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000726 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000727 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000728 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000729 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000730 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000731 return 0;
732 }
John McCall3f746822009-11-17 05:59:44 +0000733
David Blaikiee4d798f2012-01-20 21:50:17 +0000734 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000735}
736
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000737void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000738 assert(!HasAttrs && "Decl already contains attrs.");
739
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000740 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000741 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000742
743 AttrBlank = attrs;
744 HasAttrs = true;
745}
746
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000747void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000748 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000749
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000750 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000751 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000752}
753
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000754const AttrVec &Decl::getAttrs() const {
755 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000756 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000757}
758
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000759Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000760 Decl::Kind DK = D->getDeclKind();
761 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000762#define DECL(NAME, BASE)
763#define DECL_CONTEXT(NAME) \
764 case Decl::NAME: \
765 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
766#define DECL_CONTEXT_BASE(NAME)
767#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000768 default:
Alexis Hunted053252010-05-30 07:21:58 +0000769#define DECL(NAME, BASE)
770#define DECL_CONTEXT_BASE(NAME) \
771 if (DK >= first##NAME && DK <= last##NAME) \
772 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
773#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000774 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000775 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000776}
777
778DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000779 Decl::Kind DK = D->getKind();
780 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000781#define DECL(NAME, BASE)
782#define DECL_CONTEXT(NAME) \
783 case Decl::NAME: \
784 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
785#define DECL_CONTEXT_BASE(NAME)
786#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000787 default:
Alexis Hunted053252010-05-30 07:21:58 +0000788#define DECL(NAME, BASE)
789#define DECL_CONTEXT_BASE(NAME) \
790 if (DK >= first##NAME && DK <= last##NAME) \
791 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
792#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000793 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000794 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000795}
796
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000797SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000798 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
799 // FunctionDecl stores EndRangeLoc for this purpose.
800 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
801 const FunctionDecl *Definition;
802 if (FD->hasBody(Definition))
803 return Definition->getSourceRange().getEnd();
804 return SourceLocation();
805 }
806
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000807 if (Stmt *Body = getBody())
808 return Body->getSourceRange().getEnd();
809
810 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000811}
812
Alp Tokerc1086762013-12-07 13:51:35 +0000813bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000814#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000815 // Suppress this check if any of the following hold:
816 // 1. this is the translation unit (and thus has no parent)
817 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000818 // 3. this is a non-type template parameter
819 // 4. the context is not a record
820 // 5. it's invalid
821 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000822 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000823 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000824 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000825 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000826 isInvalidDecl() ||
827 isa<StaticAssertDecl>(this) ||
828 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
829 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000830 isa<ParmVarDecl>(this) ||
831 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
832 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000833 isa<CXXRecordDecl>(this) ||
834 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000835 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000836
837 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000838 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000839#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000840 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000841}
842
John McCalldec348f72013-05-03 07:33:41 +0000843static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
844static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
845
Aaron Ballman12b9f652014-01-16 13:55:42 +0000846const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
847 QualType Ty;
848 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
849 Ty = D->getType();
850 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
851 Ty = D->getUnderlyingType();
852 else
Craig Topper36250ad2014-05-12 05:36:57 +0000853 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000854
855 if (Ty->isFunctionPointerType())
856 Ty = Ty->getAs<PointerType>()->getPointeeType();
857 else if (BlocksToo && Ty->isBlockPointerType())
858 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
859
860 return Ty->getAs<FunctionType>();
861}
862
863
John McCalldec348f72013-05-03 07:33:41 +0000864/// Starting at a given context (a Decl or DeclContext), look for a
865/// code context that is not a closure (a lambda, block, etc.).
866template <class T> static Decl *getNonClosureContext(T *D) {
867 if (getKind(D) == Decl::CXXMethod) {
868 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000869 if (MD->getOverloadedOperator() == OO_Call &&
870 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000871 return getNonClosureContext(MD->getParent()->getParent());
872 return MD;
873 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
874 return FD;
875 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
876 return MD;
877 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
878 return getNonClosureContext(BD->getParent());
879 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
880 return getNonClosureContext(CD->getParent());
881 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000882 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000883 }
John McCallfe96e0b2011-11-06 09:01:30 +0000884}
885
John McCalldec348f72013-05-03 07:33:41 +0000886Decl *Decl::getNonClosureContext() {
887 return ::getNonClosureContext(this);
888}
John McCallb67608f2011-02-22 22:25:23 +0000889
John McCalldec348f72013-05-03 07:33:41 +0000890Decl *DeclContext::getNonClosureAncestor() {
891 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000892}
Anders Carlssona28908d2009-03-25 23:38:06 +0000893
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000894//===----------------------------------------------------------------------===//
895// DeclContext Implementation
896//===----------------------------------------------------------------------===//
897
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000898bool DeclContext::classof(const Decl *D) {
899 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000900#define DECL(NAME, BASE)
901#define DECL_CONTEXT(NAME) case Decl::NAME:
902#define DECL_CONTEXT_BASE(NAME)
903#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000904 return true;
905 default:
Alexis Hunted053252010-05-30 07:21:58 +0000906#define DECL(NAME, BASE)
907#define DECL_CONTEXT_BASE(NAME) \
908 if (D->getKind() >= Decl::first##NAME && \
909 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000910 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000911#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000912 return false;
913 }
914}
915
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000916DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000917
Douglas Gregor7f737c02009-09-10 16:57:35 +0000918/// \brief Find the parent context of this context that will be
919/// used for unqualified name lookup.
920///
921/// Generally, the parent lookup context is the semantic context. However, for
922/// a friend function the parent lookup context is the lexical context, which
923/// is the class in which the friend is declared.
924DeclContext *DeclContext::getLookupParent() {
925 // FIXME: Find a better way to identify friends
926 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000927 if (getParent()->getRedeclContext()->isFileContext() &&
928 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000929 return getLexicalParent();
930
931 return getParent();
932}
933
Sebastian Redlbd595762010-08-31 20:53:31 +0000934bool DeclContext::isInlineNamespace() const {
935 return isNamespace() &&
936 cast<NamespaceDecl>(this)->isInline();
937}
938
Richard Trieuc771d5d2014-05-28 02:16:01 +0000939bool DeclContext::isStdNamespace() const {
940 if (!isNamespace())
941 return false;
942
943 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
944 if (ND->isInline()) {
945 return ND->getParent()->isStdNamespace();
946 }
947
948 if (!getParent()->getRedeclContext()->isTranslationUnit())
949 return false;
950
951 const IdentifierInfo *II = ND->getIdentifier();
952 return II && II->isStr("std");
953}
954
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000955bool DeclContext::isDependentContext() const {
956 if (isFileContext())
957 return false;
958
Douglas Gregor2373c592009-05-31 09:31:02 +0000959 if (isa<ClassTemplatePartialSpecializationDecl>(this))
960 return true;
961
Douglas Gregor680e9e02012-02-21 19:11:17 +0000962 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000963 if (Record->getDescribedClassTemplate())
964 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000965
966 if (Record->isDependentLambda())
967 return true;
968 }
969
John McCallc62bb642010-03-24 05:22:00 +0000970 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000971 if (Function->getDescribedFunctionTemplate())
972 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000973
John McCallc62bb642010-03-24 05:22:00 +0000974 // Friend function declarations are dependent if their *lexical*
975 // context is dependent.
976 if (cast<Decl>(this)->getFriendObjectKind())
977 return getLexicalParent()->isDependentContext();
978 }
979
Richard Smith2b560572015-02-07 03:11:11 +0000980 // FIXME: A variable template is a dependent context, but is not a
981 // DeclContext. A context within it (such as a lambda-expression)
982 // should be considered dependent.
983
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000984 return getParent() && getParent()->isDependentContext();
985}
986
Douglas Gregor07665a62009-01-05 19:45:36 +0000987bool DeclContext::isTransparentContext() const {
988 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +0000989 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +0000990 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +0000991 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +0000992
993 return false;
994}
995
Serge Pavlov3cb80222013-11-14 02:13:03 +0000996static bool isLinkageSpecContext(const DeclContext *DC,
997 LinkageSpecDecl::LanguageIDs ID) {
998 while (DC->getDeclKind() != Decl::TranslationUnit) {
999 if (DC->getDeclKind() == Decl::LinkageSpec)
1000 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +00001001 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +00001002 }
1003 return false;
1004}
1005
1006bool DeclContext::isExternCContext() const {
1007 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1008}
1009
Alex Lorenz560ae562016-11-02 15:46:34 +00001010const LinkageSpecDecl *DeclContext::getExternCContext() const {
1011 const DeclContext *DC = this;
1012 while (DC->getDeclKind() != Decl::TranslationUnit) {
1013 if (DC->getDeclKind() == Decl::LinkageSpec &&
1014 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1015 clang::LinkageSpecDecl::lang_c)
1016 return cast<LinkageSpecDecl>(DC);
1017 DC = DC->getLexicalParent();
1018 }
1019 return nullptr;
1020}
1021
Serge Pavlov3cb80222013-11-14 02:13:03 +00001022bool DeclContext::isExternCXXContext() const {
1023 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1024}
1025
Sebastian Redl50c68252010-08-31 00:36:30 +00001026bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001027 if (getPrimaryContext() != this)
1028 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001029
Douglas Gregore985a3b2009-08-27 06:03:53 +00001030 for (; DC; DC = DC->getParent())
1031 if (DC->getPrimaryContext() == this)
1032 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001033 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001034}
1035
Steve Naroff35c62ae2009-01-08 17:28:14 +00001036DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001037 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001038 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001039 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001040 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001041 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001042 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001043 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001044 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001045 // There is only one DeclContext for these entities.
1046 return this;
1047
1048 case Decl::Namespace:
1049 // The original namespace is our primary context.
1050 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1051
Douglas Gregor91f84212008-12-11 16:49:14 +00001052 case Decl::ObjCMethod:
1053 return this;
1054
1055 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001056 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1057 return Def;
1058
1059 return this;
1060
Steve Naroff35c62ae2009-01-08 17:28:14 +00001061 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001062 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1063 return Def;
1064
1065 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001066
Steve Naroff35c62ae2009-01-08 17:28:14 +00001067 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001068 return this;
1069
Steve Naroff35c62ae2009-01-08 17:28:14 +00001070 case Decl::ObjCImplementation:
1071 case Decl::ObjCCategoryImpl:
1072 return this;
1073
Douglas Gregor91f84212008-12-11 16:49:14 +00001074 default:
Alexis Hunted053252010-05-30 07:21:58 +00001075 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001076 // If this is a tag type that has a definition or is currently
1077 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001078 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001079
1080 if (TagDecl *Def = Tag->getDefinition())
1081 return Def;
1082
Richard Smith5b21db82014-04-23 18:20:42 +00001083 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1084 // Note, TagType::getDecl returns the (partial) definition one exists.
1085 TagDecl *PossiblePartialDef = TagTy->getDecl();
1086 if (PossiblePartialDef->isBeingDefined())
1087 return PossiblePartialDef;
1088 } else {
1089 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001090 }
1091
1092 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001093 }
1094
Alexis Hunted053252010-05-30 07:21:58 +00001095 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001096 "Unknown DeclContext kind");
1097 return this;
1098 }
1099}
1100
Douglas Gregore57e7522012-01-07 09:11:48 +00001101void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001102DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001103 Contexts.clear();
1104
1105 if (DeclKind != Decl::Namespace) {
1106 Contexts.push_back(this);
1107 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001108 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001109
1110 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001111 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1112 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001113 Contexts.push_back(N);
1114
1115 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001116}
1117
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001118std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001119DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001120 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001121 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001122 Decl *FirstNewDecl = nullptr;
1123 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001124 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001125 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1126 continue;
1127
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001128 Decl *D = Decls[I];
1129 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001130 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001131 else
1132 FirstNewDecl = D;
1133
1134 PrevDecl = D;
1135 }
1136
1137 return std::make_pair(FirstNewDecl, PrevDecl);
1138}
1139
Richard Smith645d7552013-02-07 03:37:08 +00001140/// \brief We have just acquired external visible storage, and we already have
1141/// built a lookup map. For every name in the map, pull in the new names from
1142/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001143void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001144 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001145 NeedToReconcileExternalVisibleStorage = false;
1146
Richard Smith9e2341d2015-03-23 03:25:59 +00001147 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001148 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001149}
1150
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001151/// \brief Load the declarations within this lexical storage from an
1152/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001153/// \return \c true if any declarations were added.
1154bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001155DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1156 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001157 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1158
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001159 // Notify that we have a DeclContext that is initializing.
1160 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001161
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001162 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001163 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001164 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001165 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001166
1167 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001168 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001169
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001170 // We may have already loaded just the fields of this record, in which case
1171 // we need to ignore them.
1172 bool FieldsAlreadyLoaded = false;
1173 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1174 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1175
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001176 // Splice the newly-read declarations into the beginning of the list
1177 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001178 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001179 std::tie(ExternalFirst, ExternalLast) =
1180 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001181 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001182 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001183 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001184 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001185 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001186}
1187
John McCall75b960e2010-06-01 09:23:16 +00001188DeclContext::lookup_result
1189ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1190 DeclarationName Name) {
1191 ASTContext &Context = DC->getParentASTContext();
1192 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001193 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001194 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001195 if (DC->NeedToReconcileExternalVisibleStorage)
1196 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001197
Richard Smith4abe0a82013-09-09 07:34:56 +00001198 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001199
John McCall75b960e2010-06-01 09:23:16 +00001200 return DeclContext::lookup_result();
1201}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001202
John McCall75b960e2010-06-01 09:23:16 +00001203DeclContext::lookup_result
1204ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001205 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001206 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001207 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001208 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001209 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001210 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001211 if (DC->NeedToReconcileExternalVisibleStorage)
1212 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001213
1214 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001215
1216 // Clear out any old external visible declarations, to avoid quadratic
1217 // performance in the redeclaration checks below.
1218 List.removeExternalDecls();
1219
1220 if (!List.isNull()) {
1221 // We have both existing declarations and new declarations for this name.
1222 // Some of the declarations may simply replace existing ones. Handle those
1223 // first.
1224 llvm::SmallVector<unsigned, 8> Skip;
1225 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001226 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001227 Skip.push_back(I);
1228 Skip.push_back(Decls.size());
1229
1230 // Add in any new declarations.
1231 unsigned SkipPos = 0;
1232 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1233 if (I == Skip[SkipPos])
1234 ++SkipPos;
1235 else
1236 List.AddSubsequentDecl(Decls[I]);
1237 }
1238 } else {
1239 // Convert the array to a StoredDeclsList.
1240 for (ArrayRef<NamedDecl*>::iterator
1241 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1242 if (List.isNull())
1243 List.setOnlyValue(*I);
1244 else
1245 List.AddSubsequentDecl(*I);
1246 }
John McCall75b960e2010-06-01 09:23:16 +00001247 }
1248
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001249 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001250}
1251
Aaron Ballmanda634f12014-03-07 22:17:20 +00001252DeclContext::decl_iterator DeclContext::decls_begin() const {
1253 if (hasExternalLexicalStorage())
1254 LoadLexicalDeclsFromExternalStorage();
1255 return decl_iterator(FirstDecl);
1256}
1257
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001258bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001259 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001260 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001261
1262 return !FirstDecl;
1263}
1264
Sean Callanan0325fb82013-05-04 02:04:27 +00001265bool DeclContext::containsDecl(Decl *D) const {
1266 return (D->getLexicalDeclContext() == this &&
1267 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1268}
1269
John McCall84d87672009-12-10 09:41:52 +00001270void DeclContext::removeDecl(Decl *D) {
1271 assert(D->getLexicalDeclContext() == this &&
1272 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001273 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001274 "decl is not in decls list");
1275
1276 // Remove D from the decl chain. This is O(n) but hopefully rare.
1277 if (D == FirstDecl) {
1278 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001279 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001280 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001281 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001282 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001283 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001284 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001285 if (I->NextInContextAndBits.getPointer() == D) {
1286 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001287 if (D == LastDecl) LastDecl = I;
1288 break;
1289 }
1290 }
1291 }
1292
1293 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001294 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001295
1296 // Remove D from the lookup table if necessary.
1297 if (isa<NamedDecl>(D)) {
1298 NamedDecl *ND = cast<NamedDecl>(D);
1299
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001300 // Remove only decls that have a name
1301 if (!ND->getDeclName()) return;
1302
Richard Smith26210db2015-11-13 03:52:13 +00001303 auto *DC = this;
1304 do {
1305 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1306 if (Map) {
1307 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1308 assert(Pos != Map->end() && "no lookup entry for decl");
1309 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1310 Pos->second.remove(ND);
1311 }
1312 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001313 }
1314}
1315
John McCalld1e9d832009-08-11 06:59:38 +00001316void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001317 assert(D->getLexicalDeclContext() == this &&
1318 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001319 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001320 "Decl already inserted into a DeclContext");
1321
1322 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001323 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001324 LastDecl = D;
1325 } else {
1326 FirstDecl = LastDecl = D;
1327 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001328
1329 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001330 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001331 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1332 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001333
1334 // If this is a newly-created (not de-serialized) import declaration, wire
1335 // it in to the list of local import declarations.
1336 if (!D->isFromASTFile()) {
1337 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1338 D->getASTContext().addedLocalImportDecl(Import);
1339 }
John McCalld1e9d832009-08-11 06:59:38 +00001340}
1341
1342void DeclContext::addDecl(Decl *D) {
1343 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001344
1345 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001346 ND->getDeclContext()->getPrimaryContext()->
1347 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001348}
1349
Sean Callanan95e74be2011-10-21 02:57:43 +00001350void DeclContext::addDeclInternal(Decl *D) {
1351 addHiddenDecl(D);
1352
1353 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001354 ND->getDeclContext()->getPrimaryContext()->
1355 makeDeclVisibleInContextWithFlags(ND, true, true);
1356}
1357
1358/// shouldBeHidden - Determine whether a declaration which was declared
1359/// within its semantic context should be invisible to qualified name lookup.
1360static bool shouldBeHidden(NamedDecl *D) {
1361 // Skip unnamed declarations.
1362 if (!D->getDeclName())
1363 return true;
1364
1365 // Skip entities that can't be found by name lookup into a particular
1366 // context.
1367 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1368 D->isTemplateParameter())
1369 return true;
1370
1371 // Skip template specializations.
1372 // FIXME: This feels like a hack. Should DeclarationName support
1373 // template-ids, or is there a better way to keep specializations
1374 // from being visible?
1375 if (isa<ClassTemplateSpecializationDecl>(D))
1376 return true;
1377 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1378 if (FD->isFunctionTemplateSpecialization())
1379 return true;
1380
1381 return false;
1382}
1383
1384/// buildLookup - Build the lookup data structure with all of the
1385/// declarations in this DeclContext (and any other contexts linked
1386/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001387///
1388/// Note that the produced map may miss out declarations from an
1389/// external source. If it does, those entries will be marked with
1390/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001391StoredDeclsMap *DeclContext::buildLookup() {
1392 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1393
Richard Smith9e2341d2015-03-23 03:25:59 +00001394 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1395 return LookupPtr;
1396
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001397 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001398 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001399
1400 if (HasLazyExternalLexicalLookups) {
1401 HasLazyExternalLexicalLookups = false;
1402 for (auto *DC : Contexts) {
1403 if (DC->hasExternalLexicalStorage())
1404 HasLazyLocalLexicalLookups |=
1405 DC->LoadLexicalDeclsFromExternalStorage();
1406 }
1407
1408 if (!HasLazyLocalLexicalLookups)
1409 return LookupPtr;
1410 }
1411
1412 for (auto *DC : Contexts)
1413 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001414
1415 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001416 HasLazyLocalLexicalLookups = false;
1417 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001418}
1419
1420/// buildLookupImpl - Build part of the lookup data structure for the
1421/// declarations contained within DCtx, which will either be this
1422/// DeclContext, a DeclContext linked to it, or a transparent context
1423/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001424void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001425 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001426 // Insert this declaration into the lookup structure, but only if
1427 // it's semantically within its decl context. Any other decls which
1428 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001429 //
1430 // If it's from an AST file, don't add it now. It'll get handled by
1431 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1432 // in C++, we do not track external visible decls for the TU, so in
1433 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001434 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001435 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1436 (!ND->isFromASTFile() ||
1437 (isTranslationUnit() &&
1438 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001439 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001440
1441 // If this declaration is itself a transparent declaration context
1442 // or inline namespace, add the members of this declaration of that
1443 // context (recursively).
1444 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1445 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001446 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001447 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001448}
1449
Richard Smith40c78062015-02-21 02:31:57 +00001450NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1451
Mike Stump11289f42009-09-09 15:08:12 +00001452DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001453DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001454 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1455 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001456
Manman Ren7d2f5c42016-09-09 19:03:07 +00001457 const DeclContext *PrimaryContext = getPrimaryContext();
1458 if (PrimaryContext != this)
1459 return PrimaryContext->lookup(Name);
1460
Richard Smith8cebe372015-02-25 22:20:13 +00001461 // If we have an external source, ensure that any later redeclarations of this
1462 // context have been loaded, since they may add names to the result of this
1463 // lookup (or add external visible storage).
1464 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1465 if (Source)
1466 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001467
Richard Smith05afe5e2012-03-13 03:12:56 +00001468 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001469 assert(Source && "external visible storage but no external source?");
1470
Richard Smitha8b74592014-03-25 00:34:21 +00001471 if (NeedToReconcileExternalVisibleStorage)
1472 reconcileExternalVisibleStorage();
1473
Richard Smith9e2341d2015-03-23 03:25:59 +00001474 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001475
Richard Smith9e2341d2015-03-23 03:25:59 +00001476 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001477 // FIXME: Make buildLookup const?
1478 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001479
Richard Smith75fc3bf2013-02-08 00:37:45 +00001480 if (!Map)
1481 Map = CreateStoredDeclsMap(getParentASTContext());
1482
Richard Smith4abe0a82013-09-09 07:34:56 +00001483 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001484 std::pair<StoredDeclsMap::iterator, bool> R =
1485 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001486 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001487 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001488
Richard Smith309271b2014-03-04 00:21:14 +00001489 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001490 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001491 StoredDeclsMap::iterator I = Map->find(Name);
1492 if (I != Map->end())
1493 return I->second.getLookupResult();
1494 }
1495 }
1496
Richard Smith40c78062015-02-21 02:31:57 +00001497 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001498 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001499
Richard Smith9e2341d2015-03-23 03:25:59 +00001500 StoredDeclsMap *Map = LookupPtr;
1501 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001502 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001503
1504 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001505 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001506
1507 StoredDeclsMap::iterator I = Map->find(Name);
1508 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001509 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001510
1511 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001512}
1513
Richard Smith95d99302013-07-13 02:00:19 +00001514DeclContext::lookup_result
1515DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001516 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1517 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001518
1519 DeclContext *PrimaryContext = getPrimaryContext();
1520 if (PrimaryContext != this)
1521 return PrimaryContext->noload_lookup(Name);
1522
Richard Smith9e2341d2015-03-23 03:25:59 +00001523 // If we have any lazy lexical declarations not in our lookup map, add them
1524 // now. Don't import any external declarations, not even if we know we have
1525 // some missing from the external visible lookups.
1526 if (HasLazyLocalLexicalLookups) {
Vince Harrona3ea9a42015-03-22 05:59:59 +00001527 SmallVector<DeclContext *, 2> Contexts;
1528 collectAllContexts(Contexts);
1529 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith9e2341d2015-03-23 03:25:59 +00001530 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1531 HasLazyLocalLexicalLookups = false;
Vince Harrona3ea9a42015-03-22 05:59:59 +00001532 }
1533
Richard Smith9e2341d2015-03-23 03:25:59 +00001534 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001535 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001536 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001537
1538 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001539 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001540 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001541}
1542
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001543void DeclContext::localUncachedLookup(DeclarationName Name,
1544 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001545 Results.clear();
1546
1547 // If there's no external storage, just perform a normal lookup and copy
1548 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001549 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001550 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001551 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001552 return;
1553 }
1554
1555 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001556 // FIXME: Should we be checking these flags on the primary context?
1557 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1558 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001559 StoredDeclsMap::iterator Pos = Map->find(Name);
1560 if (Pos != Map->end()) {
1561 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001562 Pos->second.getLookupResult().begin(),
1563 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001564 return;
1565 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001566 }
1567 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001568
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001569 // Slow case: grovel through the declarations in our chain looking for
1570 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001571 // FIXME: If we have lazy external declarations, this will not find them!
1572 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001573 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1574 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1575 if (ND->getDeclName() == Name)
1576 Results.push_back(ND);
1577 }
1578}
1579
Sebastian Redl50c68252010-08-31 00:36:30 +00001580DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001581 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001582 // Skip through transparent contexts.
1583 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001584 Ctx = Ctx->getParent();
1585 return Ctx;
1586}
1587
Douglas Gregorf47b9112009-02-25 22:02:03 +00001588DeclContext *DeclContext::getEnclosingNamespaceContext() {
1589 DeclContext *Ctx = this;
1590 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001591 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001592 Ctx = Ctx->getParent();
1593 return Ctx->getPrimaryContext();
1594}
1595
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001596RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1597 // Loop until we find a non-record context.
1598 RecordDecl *OutermostRD = nullptr;
1599 DeclContext *DC = this;
1600 while (DC->isRecord()) {
1601 OutermostRD = cast<RecordDecl>(DC);
1602 DC = DC->getLexicalParent();
1603 }
1604 return OutermostRD;
1605}
1606
Sebastian Redl50c68252010-08-31 00:36:30 +00001607bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1608 // For non-file contexts, this is equivalent to Equals.
1609 if (!isFileContext())
1610 return O->Equals(this);
1611
1612 do {
1613 if (O->Equals(this))
1614 return true;
1615
1616 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1617 if (!NS || !NS->isInline())
1618 break;
1619 O = NS->getParent();
1620 } while (O);
1621
1622 return false;
1623}
1624
Richard Smithf634c902012-03-16 06:12:59 +00001625void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1626 DeclContext *PrimaryDC = this->getPrimaryContext();
1627 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1628 // If the decl is being added outside of its semantic decl context, we
1629 // need to ensure that we eagerly build the lookup information for it.
1630 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001631}
1632
Richard Smithf634c902012-03-16 06:12:59 +00001633void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1634 bool Recoverable) {
1635 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001636
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001637 if (!isLookupContext()) {
1638 if (isTransparentContext())
1639 getParent()->getPrimaryContext()
1640 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001641 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001642 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001643
Richard Smithf634c902012-03-16 06:12:59 +00001644 // Skip declarations which should be invisible to name lookup.
1645 if (shouldBeHidden(D))
1646 return;
1647
1648 // If we already have a lookup data structure, perform the insertion into
1649 // it. If we might have externally-stored decls with this name, look them
1650 // up and perform the insertion. If this decl was declared outside its
1651 // semantic context, buildLookup won't add it, so add it now.
1652 //
1653 // FIXME: As a performance hack, don't add such decls into the translation
1654 // unit unless we're in C++, since qualified lookup into the TU is never
1655 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001656 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001657 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1658 (getParentASTContext().getLangOpts().CPlusPlus ||
1659 !isTranslationUnit()))) {
1660 // If we have lazily omitted any decls, they might have the same name as
1661 // the decl which we are adding, so build a full lookup table before adding
1662 // this decl.
1663 buildLookup();
1664 makeDeclVisibleInContextImpl(D, Internal);
1665 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001666 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001667 }
1668
1669 // If we are a transparent context or inline namespace, insert into our
1670 // parent context, too. This operation is recursive.
1671 if (isTransparentContext() || isInlineNamespace())
1672 getParent()->getPrimaryContext()->
1673 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1674
1675 Decl *DCAsDecl = cast<Decl>(this);
1676 // Notify that a decl was made visible unless we are a Tag being defined.
1677 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1678 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1679 L->AddedVisibleDecl(this, D);
1680}
1681
1682void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1683 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001684 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001685 if (!Map) {
1686 ASTContext *C = &getParentASTContext();
1687 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001688 }
1689
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001690 // If there is an external AST source, load any declarations it knows about
1691 // with this declaration's name.
1692 // If the lookup table contains an entry about this name it means that we
1693 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001694 if (!Internal)
1695 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1696 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001697 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001698 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001699
Douglas Gregor91f84212008-12-11 16:49:14 +00001700 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001701 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001702
1703 if (Internal) {
1704 // If this is being added as part of loading an external declaration,
1705 // this may not be the only external declaration with this name.
1706 // In this case, we never try to replace an existing declaration; we'll
1707 // handle that when we finalize the list of declarations for this name.
1708 DeclNameEntries.setHasExternalDecls();
1709 DeclNameEntries.AddSubsequentDecl(D);
1710 return;
1711 }
1712
Richard Smitha3271c12015-02-07 00:45:52 +00001713 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001714 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001715 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001716 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001717
Richard Smithe8292b12015-02-10 03:28:10 +00001718 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001719 // This declaration has replaced an existing one for which
1720 // declarationReplaces returns true.
1721 return;
1722 }
Mike Stump11289f42009-09-09 15:08:12 +00001723
Richard Smithf634c902012-03-16 06:12:59 +00001724 // Put this declaration into the appropriate slot.
1725 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001726}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001727
Richard Smith40c78062015-02-21 02:31:57 +00001728UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1729 return cast<UsingDirectiveDecl>(*I);
1730}
1731
Douglas Gregor889ceb72009-02-03 19:21:40 +00001732/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1733/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001734DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001735 // FIXME: Use something more efficient than normal lookup for using
1736 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001737 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001738 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001739}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001740
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001741//===----------------------------------------------------------------------===//
1742// Creation and Destruction of StoredDeclsMaps. //
1743//===----------------------------------------------------------------------===//
1744
John McCallc62bb642010-03-24 05:22:00 +00001745StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001746 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001747 assert(getPrimaryContext() == this &&
1748 "creating decls map on non-primary context");
1749
1750 StoredDeclsMap *M;
1751 bool Dependent = isDependentContext();
1752 if (Dependent)
1753 M = new DependentStoredDeclsMap();
1754 else
1755 M = new StoredDeclsMap();
1756 M->Previous = C.LastSDM;
1757 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001758 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001759 return M;
1760}
1761
1762void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001763 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1764 // pointer because the subclass doesn't add anything that needs to
1765 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001766 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1767}
1768
1769void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1770 while (Map) {
1771 // Advance the iteration before we invalidate memory.
1772 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1773
1774 if (Dependent)
1775 delete static_cast<DependentStoredDeclsMap*>(Map);
1776 else
1777 delete Map;
1778
1779 Map = Next.getPointer();
1780 Dependent = Next.getInt();
1781 }
1782}
1783
John McCallc62bb642010-03-24 05:22:00 +00001784DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1785 DeclContext *Parent,
1786 const PartialDiagnostic &PDiag) {
1787 assert(Parent->isDependentContext()
1788 && "cannot iterate dependent diagnostics of non-dependent context");
1789 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001790 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001791 Parent->CreateStoredDeclsMap(C);
1792
Richard Smith9e2341d2015-03-23 03:25:59 +00001793 DependentStoredDeclsMap *Map =
1794 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001795
Douglas Gregora55530e2010-03-29 23:56:53 +00001796 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001797 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001798 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001799 if (PDiag.hasStorage())
1800 DiagStorage = new (C) PartialDiagnostic::Storage;
1801
1802 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001803
1804 // TODO: Maybe we shouldn't reverse the order during insertion.
1805 DD->NextDiagnostic = Map->FirstDiagnostic;
1806 Map->FirstDiagnostic = DD;
1807
1808 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001809}