blob: f6f81692611df6eaee0a28c0d5a59de25de9fb71 [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.
Richard Smith26342f92017-05-17 00:24:14 +000078 if (Ctx.getLangOpts().trackLocalOwningModule()) {
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 Smith26342f92017-05-17 00:24:14 +000086 auto *ParentModule =
87 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
88 return new (Buffer) Module*(ParentModule) + 1;
Richard Smith42413142015-05-15 20:05:43 +000089 }
Richard Smithf7981722013-11-22 09:01:48 +000090 return ::operator new(Size + Extra, Ctx);
91}
92
Douglas Gregorc147b0b2013-01-12 01:29:50 +000093Module *Decl::getOwningModuleSlow() const {
94 assert(isFromASTFile() && "Not from AST file?");
95 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
96}
97
Richard Smith87bb5692015-06-09 00:35:49 +000098bool Decl::hasLocalOwningModuleStorage() const {
Richard Smith26342f92017-05-17 00:24:14 +000099 return getASTContext().getLangOpts().trackLocalOwningModule();
Richard Smith87bb5692015-06-09 00:35:49 +0000100}
101
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000102const char *Decl::getDeclKindName() const {
103 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000104 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000105#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
106#define ABSTRACT_DECL(DECL)
107#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000108 }
109}
110
Douglas Gregor90d47172010-03-05 00:26:45 +0000111void Decl::setInvalidDecl(bool Invalid) {
112 InvalidDecl = Invalid;
Alp Tokera5d64592013-12-21 01:10:54 +0000113 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Richard Trieucbd54302016-11-11 20:51:04 +0000114 if (!Invalid) {
115 return;
116 }
117
118 if (!isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +0000119 // Defensive maneuver for ill-formed code: we're likely not to make it to
120 // a point where we set the access specifier, so default it to "public"
121 // to avoid triggering asserts elsewhere in the front end.
122 setAccess(AS_public);
123 }
Richard Trieucbd54302016-11-11 20:51:04 +0000124
125 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
126 // are invalid too.
127 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
128 for (BindingDecl *Binding : DD->bindings()) {
129 Binding->setInvalidDecl();
130 }
131 }
Douglas Gregor90d47172010-03-05 00:26:45 +0000132}
133
Steve Naroff5faaef72009-01-20 19:53:53 +0000134const char *DeclContext::getDeclKindName() const {
135 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000136 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000137#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
138#define ABSTRACT_DECL(DECL)
139#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000140 }
141}
142
Daniel Dunbar62905572012-03-05 21:42:49 +0000143bool Decl::StatisticsEnabled = false;
144void Decl::EnableStatistics() {
145 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000146}
147
148void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000149 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000150
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000151 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000152#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
153#define ABSTRACT_DECL(DECL)
154#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000155 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000156
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000157 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000158#define DECL(DERIVED, BASE) \
159 if (n##DERIVED##s > 0) { \
160 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000161 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
162 << sizeof(DERIVED##Decl) << " each (" \
163 << n##DERIVED##s * sizeof(DERIVED##Decl) \
164 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000165 }
Alexis Hunted053252010-05-30 07:21:58 +0000166#define ABSTRACT_DECL(DECL)
167#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000168
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000169 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000170}
171
Alexis Hunted053252010-05-30 07:21:58 +0000172void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000173 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000174#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
175#define ABSTRACT_DECL(DECL)
176#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000177 }
178}
179
Anders Carlssonaa73b912009-06-13 00:08:58 +0000180bool Decl::isTemplateParameterPack() const {
181 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
182 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000183 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000184 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000185 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000186 if (const TemplateTemplateParmDecl *TTP
187 = dyn_cast<TemplateTemplateParmDecl>(this))
188 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000189 return false;
190}
191
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000192bool Decl::isParameterPack() const {
193 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
194 return Parm->isParameterPack();
195
196 return isTemplateParameterPack();
197}
198
Alp Tokera2794f92014-01-22 07:29:52 +0000199FunctionDecl *Decl::getAsFunction() {
200 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
201 return FD;
202 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
203 return FTD->getTemplatedDecl();
Craig Topper36250ad2014-05-12 05:36:57 +0000204 return nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000205}
206
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000207bool Decl::isTemplateDecl() const {
208 return isa<TemplateDecl>(this);
209}
210
Serge Pavlov7dcc97e2016-04-19 06:19:52 +0000211TemplateDecl *Decl::getDescribedTemplate() const {
212 if (auto *FD = dyn_cast<FunctionDecl>(this))
213 return FD->getDescribedFunctionTemplate();
214 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
215 return RD->getDescribedClassTemplate();
216 else if (auto *VD = dyn_cast<VarDecl>(this))
217 return VD->getDescribedVarTemplate();
218
219 return nullptr;
220}
221
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000222const DeclContext *Decl::getParentFunctionOrMethod() const {
223 for (const DeclContext *DC = getDeclContext();
224 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000225 DC = DC->getParent())
226 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000227 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000228
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000230}
231
Douglas Gregor133eddd2011-02-17 08:47:29 +0000232
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000233//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000234// PrettyStackTraceDecl Implementation
235//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000238 SourceLocation TheLoc = Loc;
239 if (TheLoc.isInvalid() && TheDecl)
240 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattnereae6cb62009-03-05 08:00:35 +0000242 if (TheLoc.isValid()) {
243 TheLoc.print(OS, SM);
244 OS << ": ";
245 }
246
247 OS << Message;
248
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000249 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
250 OS << " '";
251 DN->printQualifiedName(OS);
252 OS << '\'';
253 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000254 OS << '\n';
255}
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattnereae6cb62009-03-05 08:00:35 +0000257//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000258// Decl Implementation
259//===----------------------------------------------------------------------===//
260
Douglas Gregorb11aad82011-02-19 18:51:44 +0000261// Out-of-line virtual method providing a home for Decl.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000262Decl::~Decl() { }
Douglas Gregora43942a2011-02-17 07:02:32 +0000263
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000264void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000265 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000266}
267
268void Decl::setLexicalDeclContext(DeclContext *DC) {
269 if (DC == getLexicalDeclContext())
270 return;
271
272 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000273 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000274 } else {
275 getMultipleDC()->LexicalDC = DC;
276 }
Richard Smith5327b892015-07-01 19:32:54 +0000277 Hidden = cast<Decl>(DC)->Hidden;
Richard Smith26342f92017-05-17 00:24:14 +0000278 if (Hidden && !isFromASTFile() && hasLocalOwningModuleStorage())
279 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000280}
281
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000282void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
283 ASTContext &Ctx) {
284 if (SemaDC == LexicalDC) {
285 DeclCtx = SemaDC;
286 } else {
287 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
288 MDC->SemanticDC = SemaDC;
289 MDC->LexicalDC = LexicalDC;
290 DeclCtx = MDC;
291 }
292}
293
Serge Pavlov73c6a242015-08-23 10:22:28 +0000294bool Decl::isLexicallyWithinFunctionOrMethod() const {
295 const DeclContext *LDC = getLexicalDeclContext();
Serge Pavlovb24a7112015-08-23 11:09:40 +0000296 while (true) {
Serge Pavlov73c6a242015-08-23 10:22:28 +0000297 if (LDC->isFunctionOrMethod())
298 return true;
299 if (!isa<TagDecl>(LDC))
300 return false;
Serge Pavlovb24a7112015-08-23 11:09:40 +0000301 LDC = LDC->getLexicalParent();
302 }
Serge Pavlov73c6a242015-08-23 10:22:28 +0000303 return false;
304}
305
John McCall4fa53422009-10-01 00:25:31 +0000306bool Decl::isInAnonymousNamespace() const {
307 const DeclContext *DC = getDeclContext();
308 do {
309 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
310 if (ND->isAnonymousNamespace())
311 return true;
312 } while ((DC = DC->getParent()));
313
314 return false;
315}
316
Richard Trieuc771d5d2014-05-28 02:16:01 +0000317bool Decl::isInStdNamespace() const {
318 return getDeclContext()->isStdNamespace();
319}
320
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000321TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000322 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
323 return TUD;
324
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000325 DeclContext *DC = getDeclContext();
326 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000327
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000328 while (!DC->isTranslationUnit()) {
329 DC = DC->getParent();
330 assert(DC && "This decl is not contained in a translation unit!");
331 }
Mike Stump11289f42009-09-09 15:08:12 +0000332
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000333 return cast<TranslationUnitDecl>(DC);
334}
335
336ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000337 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000338}
339
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000340ASTMutationListener *Decl::getASTMutationListener() const {
341 return getASTContext().getASTMutationListener();
342}
343
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000344unsigned Decl::getMaxAlignment() const {
345 if (!hasAttrs())
346 return 0;
347
348 unsigned Align = 0;
349 const AttrVec &V = getAttrs();
350 ASTContext &Ctx = getASTContext();
351 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
352 for (; I != E; ++I)
353 Align = std::max(Align, I->getAlignment(Ctx));
354 return Align;
355}
356
Vassil Vassilev928c8252016-04-28 14:13:28 +0000357bool Decl::isUsed(bool CheckUsedAttr) const {
358 const Decl *CanonD = getCanonicalDecl();
359 if (CanonD->Used)
Vassil Vassileva4d7d782016-04-27 10:46:06 +0000360 return true;
361
Vassil Vassilev928c8252016-04-28 14:13:28 +0000362 // Check for used attribute.
363 // Ask the most recent decl, since attributes accumulate in the redecl chain.
364 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
365 return true;
366
367 // The information may have not been deserialized yet. Force deserialization
368 // to complete the needed information.
369 return getMostRecentDecl()->getCanonicalDecl()->Used;
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000370}
371
Eli Friedman276dd182013-09-05 00:02:25 +0000372void Decl::markUsed(ASTContext &C) {
Vassil Vassilev928c8252016-04-28 14:13:28 +0000373 if (isUsed(false))
Eli Friedman276dd182013-09-05 00:02:25 +0000374 return;
375
376 if (C.getASTMutationListener())
377 C.getASTMutationListener()->DeclarationMarkedUsed(this);
378
Vassil Vassilev928c8252016-04-28 14:13:28 +0000379 setIsUsed();
Eli Friedman276dd182013-09-05 00:02:25 +0000380}
381
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000382bool Decl::isReferenced() const {
383 if (Referenced)
384 return true;
385
386 // Check redeclarations.
Aaron Ballman86c93902014-03-06 23:45:36 +0000387 for (auto I : redecls())
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000388 if (I->Referenced)
389 return true;
390
391 return false;
392}
393
Richard Smith3b660562016-09-26 21:27:23 +0000394bool Decl::isExported() const {
395 if (isModulePrivate())
396 return false;
397 // Namespaces are always exported.
398 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
399 return true;
400 // Otherwise, this is a strictly lexical check.
401 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
402 if (cast<Decl>(DC)->isModulePrivate())
403 return false;
404 if (isa<ExportDecl>(DC))
405 return true;
406 }
407 return false;
408}
409
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000410bool Decl::hasDefiningAttr() const {
411 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
412}
413
414const Attr *Decl::getDefiningAttr() const {
415 if (AliasAttr *AA = getAttr<AliasAttr>())
416 return AA;
417 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
418 return IFA;
419 return nullptr;
420}
421
Alex Lorenza8a372d2017-04-27 10:43:48 +0000422StringRef getRealizedPlatform(const AvailabilityAttr *A,
423 const ASTContext &Context) {
424 // Check if this is an App Extension "platform", and if so chop off
425 // the suffix for matching with the actual platform.
426 StringRef RealizedPlatform = A->getPlatform()->getName();
427 if (!Context.getLangOpts().AppExt)
428 return RealizedPlatform;
429 size_t suffix = RealizedPlatform.rfind("_app_extension");
430 if (suffix != StringRef::npos)
431 return RealizedPlatform.slice(0, suffix);
432 return RealizedPlatform;
433}
434
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000435/// \brief Determine the availability of the given declaration based on
436/// the target platform.
437///
438/// When it returns an availability result other than \c AR_Available,
439/// if the \p Message parameter is non-NULL, it will be set to a
440/// string describing why the entity is unavailable.
441///
442/// FIXME: Make these strings localizable, since they end up in
443/// diagnostics.
444static AvailabilityResult CheckAvailability(ASTContext &Context,
445 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000446 std::string *Message,
447 VersionTuple EnclosingVersion) {
448 if (EnclosingVersion.empty())
449 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000450
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000451 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000452 return AR_Available;
453
Bob Wilsonb111ec92015-03-02 19:01:14 +0000454 StringRef ActualPlatform = A->getPlatform()->getName();
Bob Wilsonb111ec92015-03-02 19:01:14 +0000455 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
456
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000457 // Match the platform name.
Alex Lorenza8a372d2017-04-27 10:43:48 +0000458 if (getRealizedPlatform(A, Context) != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000459 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000460
461 StringRef PrettyPlatformName
462 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
463
464 if (PrettyPlatformName.empty())
465 PrettyPlatformName = ActualPlatform;
466
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000467 std::string HintMessage;
468 if (!A->getMessage().empty()) {
469 HintMessage = " - ";
470 HintMessage += A->getMessage();
471 }
472
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000473 // Make sure that this declaration has not been marked 'unavailable'.
474 if (A->getUnavailable()) {
475 if (Message) {
476 Message->clear();
477 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000478 Out << "not available on " << PrettyPlatformName
479 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000480 }
481
482 return AR_Unavailable;
483 }
484
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000485 // Make sure that this declaration has already been introduced.
486 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000487 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000488 if (Message) {
489 Message->clear();
490 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000491 VersionTuple VTI(A->getIntroduced());
492 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000493 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000494 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000495 }
496
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000497 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000498 }
499
500 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000501 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000502 if (Message) {
503 Message->clear();
504 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000505 VersionTuple VTO(A->getObsoleted());
506 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000507 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000508 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000509 }
510
511 return AR_Unavailable;
512 }
513
514 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000515 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000516 if (Message) {
517 Message->clear();
518 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000519 VersionTuple VTD(A->getDeprecated());
520 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000521 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000522 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000523 }
524
525 return AR_Deprecated;
526 }
527
528 return AR_Available;
529}
530
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000531AvailabilityResult Decl::getAvailability(std::string *Message,
532 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000533 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000534 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000535
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000536 AvailabilityResult Result = AR_Available;
537 std::string ResultMessage;
538
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000539 for (const auto *A : attrs()) {
540 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000541 if (Result >= AR_Deprecated)
542 continue;
543
544 if (Message)
545 ResultMessage = Deprecated->getMessage();
546
547 Result = AR_Deprecated;
548 continue;
549 }
550
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000551 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000552 if (Message)
553 *Message = Unavailable->getMessage();
554 return AR_Unavailable;
555 }
556
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000557 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000558 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000559 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000560
561 if (AR == AR_Unavailable)
562 return AR_Unavailable;
563
564 if (AR > Result) {
565 Result = AR;
566 if (Message)
567 ResultMessage.swap(*Message);
568 }
569 continue;
570 }
571 }
572
573 if (Message)
574 Message->swap(ResultMessage);
575 return Result;
576}
577
Alex Lorenza8a372d2017-04-27 10:43:48 +0000578VersionTuple Decl::getVersionIntroduced() const {
579 const ASTContext &Context = getASTContext();
580 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
581 for (const auto *A : attrs()) {
582 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
583 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
584 continue;
585 if (!Availability->getIntroduced().empty())
586 return Availability->getIntroduced();
587 }
588 }
589 return VersionTuple();
590}
591
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000592bool Decl::canBeWeakImported(bool &IsDefinition) const {
593 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000594
595 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000596 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000597 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000598 IsDefinition = true;
599 return false;
600 }
John McCall5fb5df92012-06-20 06:18:46 +0000601 return true;
602
603 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000604 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
605 if (FD->hasBody()) {
606 IsDefinition = true;
607 return false;
608 }
John McCall5fb5df92012-06-20 06:18:46 +0000609 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000610
John McCall5fb5df92012-06-20 06:18:46 +0000611 // Objective-C classes, if this is the non-fragile runtime.
612 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000613 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000614 return true;
615
616 // Nothing else.
617 } else {
618 return false;
619 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000620}
621
622bool Decl::isWeakImported() const {
623 bool IsDefinition;
624 if (!canBeWeakImported(IsDefinition))
625 return false;
626
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000627 for (const auto *A : attrs()) {
628 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000629 return true;
630
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000631 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000632 if (CheckAvailability(getASTContext(), Availability, nullptr,
633 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000634 return true;
635 }
636 }
637
638 return false;
639}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000640
Chris Lattner8e097192009-03-27 20:18:19 +0000641unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
642 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000643 case Function:
Richard Smithbc491202017-02-17 20:05:37 +0000644 case CXXDeductionGuide:
John McCall3f746822009-11-17 05:59:44 +0000645 case CXXMethod:
646 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000647 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000648 case CXXDestructor:
649 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000650 case EnumConstant:
651 case Var:
Richard Smithbdb84f32016-07-22 23:36:59 +0000652 case Binding:
Chris Lattner8e097192009-03-27 20:18:19 +0000653 case ImplicitParam:
654 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000655 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000656 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000657 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000658 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000659 case Label:
660 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000661 case IndirectField:
662 return IDNS_Ordinary | IDNS_Member;
663
Richard Smith9f951822016-01-06 22:49:11 +0000664 case NonTypeTemplateParm:
665 // Non-type template parameters are not found by lookups that ignore
666 // non-types, but they are found by redeclaration lookups for tag types,
667 // so we include them in the tag namespace.
668 return IDNS_Ordinary | IDNS_Tag;
669
John McCalle87beb22010-04-23 18:46:30 +0000670 case ObjCCompatibleAlias:
671 case ObjCInterface:
672 return IDNS_Ordinary | IDNS_Type;
673
674 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000675 case TypeAlias:
Richard Smith3f1b5d02011-05-05 21:57:07 +0000676 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000677 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000678 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000679 return IDNS_Ordinary | IDNS_Type;
680
Richard Smith151c4562016-12-20 21:35:28 +0000681 case UnresolvedUsingTypename:
682 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
683
John McCall3f746822009-11-17 05:59:44 +0000684 case UsingShadow:
685 return 0; // we'll actually overwrite this later
686
John McCalle61f2ba2009-11-18 02:36:19 +0000687 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000688 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000689
690 case Using:
Richard Smith151c4562016-12-20 21:35:28 +0000691 case UsingPack:
John McCall3f746822009-11-17 05:59:44 +0000692 return IDNS_Using;
693
Chris Lattner8e097192009-03-27 20:18:19 +0000694 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000695 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattner8e097192009-03-27 20:18:19 +0000697 case Field:
698 case ObjCAtDefsField:
699 case ObjCIvar:
700 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattner8e097192009-03-27 20:18:19 +0000702 case Record:
703 case CXXRecord:
704 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000705 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner8e097192009-03-27 20:18:19 +0000707 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000708 case NamespaceAlias:
709 return IDNS_Namespace;
710
Chris Lattner8e097192009-03-27 20:18:19 +0000711 case FunctionTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000712 case VarTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000713 return IDNS_Ordinary;
714
Chris Lattner8e097192009-03-27 20:18:19 +0000715 case ClassTemplate:
716 case TemplateTemplateParm:
John McCalle87beb22010-04-23 18:46:30 +0000717 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000718
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000719 case OMPDeclareReduction:
720 return IDNS_OMPReduction;
721
Chris Lattner8e097192009-03-27 20:18:19 +0000722 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000723 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000724 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000725 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000726 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000727 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000728 case FileScopeAsm:
729 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000730 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000731 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000732 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000733 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000734 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000735 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000736 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000737 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000738
Chris Lattner8e097192009-03-27 20:18:19 +0000739 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000740 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000741 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000742 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000743 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000744 case VarTemplateSpecialization:
745 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000746 case ObjCImplementation:
747 case ObjCCategory:
748 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000749 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000750 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000751 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000752 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000753 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000754 return 0;
755 }
John McCall3f746822009-11-17 05:59:44 +0000756
David Blaikiee4d798f2012-01-20 21:50:17 +0000757 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000758}
759
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000760void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000761 assert(!HasAttrs && "Decl already contains attrs.");
762
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000763 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000764 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000765
766 AttrBlank = attrs;
767 HasAttrs = true;
768}
769
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000770void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000771 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000773 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000774 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000775}
776
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000777const AttrVec &Decl::getAttrs() const {
778 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000779 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000780}
781
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000782Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000783 Decl::Kind DK = D->getDeclKind();
784 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000785#define DECL(NAME, BASE)
786#define DECL_CONTEXT(NAME) \
787 case Decl::NAME: \
788 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
789#define DECL_CONTEXT_BASE(NAME)
790#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000791 default:
Alexis Hunted053252010-05-30 07:21:58 +0000792#define DECL(NAME, BASE)
793#define DECL_CONTEXT_BASE(NAME) \
794 if (DK >= first##NAME && DK <= last##NAME) \
795 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
796#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000797 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000798 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000799}
800
801DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000802 Decl::Kind DK = D->getKind();
803 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000804#define DECL(NAME, BASE)
805#define DECL_CONTEXT(NAME) \
806 case Decl::NAME: \
807 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
808#define DECL_CONTEXT_BASE(NAME)
809#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000810 default:
Alexis Hunted053252010-05-30 07:21:58 +0000811#define DECL(NAME, BASE)
812#define DECL_CONTEXT_BASE(NAME) \
813 if (DK >= first##NAME && DK <= last##NAME) \
814 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
815#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000816 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000817 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000818}
819
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000820SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000821 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
822 // FunctionDecl stores EndRangeLoc for this purpose.
823 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
824 const FunctionDecl *Definition;
825 if (FD->hasBody(Definition))
826 return Definition->getSourceRange().getEnd();
827 return SourceLocation();
828 }
829
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000830 if (Stmt *Body = getBody())
831 return Body->getSourceRange().getEnd();
832
833 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000834}
835
Alp Tokerc1086762013-12-07 13:51:35 +0000836bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000837#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000838 // Suppress this check if any of the following hold:
839 // 1. this is the translation unit (and thus has no parent)
840 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000841 // 3. this is a non-type template parameter
842 // 4. the context is not a record
843 // 5. it's invalid
844 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000845 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000846 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000847 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000848 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000849 isInvalidDecl() ||
850 isa<StaticAssertDecl>(this) ||
851 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
852 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000853 isa<ParmVarDecl>(this) ||
854 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
855 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000856 isa<CXXRecordDecl>(this) ||
857 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000858 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000859
860 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000861 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000862#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000863 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000864}
865
John McCalldec348f72013-05-03 07:33:41 +0000866static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
867static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
868
Aaron Ballman12b9f652014-01-16 13:55:42 +0000869const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
870 QualType Ty;
871 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
872 Ty = D->getType();
873 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
874 Ty = D->getUnderlyingType();
875 else
Craig Topper36250ad2014-05-12 05:36:57 +0000876 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000877
878 if (Ty->isFunctionPointerType())
879 Ty = Ty->getAs<PointerType>()->getPointeeType();
880 else if (BlocksToo && Ty->isBlockPointerType())
881 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
882
883 return Ty->getAs<FunctionType>();
884}
885
886
John McCalldec348f72013-05-03 07:33:41 +0000887/// Starting at a given context (a Decl or DeclContext), look for a
888/// code context that is not a closure (a lambda, block, etc.).
889template <class T> static Decl *getNonClosureContext(T *D) {
890 if (getKind(D) == Decl::CXXMethod) {
891 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000892 if (MD->getOverloadedOperator() == OO_Call &&
893 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000894 return getNonClosureContext(MD->getParent()->getParent());
895 return MD;
896 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
897 return FD;
898 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
899 return MD;
900 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
901 return getNonClosureContext(BD->getParent());
902 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
903 return getNonClosureContext(CD->getParent());
904 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000905 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000906 }
John McCallfe96e0b2011-11-06 09:01:30 +0000907}
908
John McCalldec348f72013-05-03 07:33:41 +0000909Decl *Decl::getNonClosureContext() {
910 return ::getNonClosureContext(this);
911}
John McCallb67608f2011-02-22 22:25:23 +0000912
John McCalldec348f72013-05-03 07:33:41 +0000913Decl *DeclContext::getNonClosureAncestor() {
914 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000915}
Anders Carlssona28908d2009-03-25 23:38:06 +0000916
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000917//===----------------------------------------------------------------------===//
918// DeclContext Implementation
919//===----------------------------------------------------------------------===//
920
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000921bool DeclContext::classof(const Decl *D) {
922 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000923#define DECL(NAME, BASE)
924#define DECL_CONTEXT(NAME) case Decl::NAME:
925#define DECL_CONTEXT_BASE(NAME)
926#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000927 return true;
928 default:
Alexis Hunted053252010-05-30 07:21:58 +0000929#define DECL(NAME, BASE)
930#define DECL_CONTEXT_BASE(NAME) \
931 if (D->getKind() >= Decl::first##NAME && \
932 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000933 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000934#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000935 return false;
936 }
937}
938
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000939DeclContext::~DeclContext() { }
Douglas Gregor91f84212008-12-11 16:49:14 +0000940
Douglas Gregor7f737c02009-09-10 16:57:35 +0000941/// \brief Find the parent context of this context that will be
942/// used for unqualified name lookup.
943///
944/// Generally, the parent lookup context is the semantic context. However, for
945/// a friend function the parent lookup context is the lexical context, which
946/// is the class in which the friend is declared.
947DeclContext *DeclContext::getLookupParent() {
948 // FIXME: Find a better way to identify friends
949 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000950 if (getParent()->getRedeclContext()->isFileContext() &&
951 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +0000952 return getLexicalParent();
953
954 return getParent();
955}
956
Sebastian Redlbd595762010-08-31 20:53:31 +0000957bool DeclContext::isInlineNamespace() const {
958 return isNamespace() &&
959 cast<NamespaceDecl>(this)->isInline();
960}
961
Richard Trieuc771d5d2014-05-28 02:16:01 +0000962bool DeclContext::isStdNamespace() const {
963 if (!isNamespace())
964 return false;
965
966 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
967 if (ND->isInline()) {
968 return ND->getParent()->isStdNamespace();
969 }
970
971 if (!getParent()->getRedeclContext()->isTranslationUnit())
972 return false;
973
974 const IdentifierInfo *II = ND->getIdentifier();
975 return II && II->isStr("std");
976}
977
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000978bool DeclContext::isDependentContext() const {
979 if (isFileContext())
980 return false;
981
Douglas Gregor2373c592009-05-31 09:31:02 +0000982 if (isa<ClassTemplatePartialSpecializationDecl>(this))
983 return true;
984
Douglas Gregor680e9e02012-02-21 19:11:17 +0000985 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000986 if (Record->getDescribedClassTemplate())
987 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +0000988
989 if (Record->isDependentLambda())
990 return true;
991 }
992
John McCallc62bb642010-03-24 05:22:00 +0000993 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +0000994 if (Function->getDescribedFunctionTemplate())
995 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000996
John McCallc62bb642010-03-24 05:22:00 +0000997 // Friend function declarations are dependent if their *lexical*
998 // context is dependent.
999 if (cast<Decl>(this)->getFriendObjectKind())
1000 return getLexicalParent()->isDependentContext();
1001 }
1002
Richard Smith2b560572015-02-07 03:11:11 +00001003 // FIXME: A variable template is a dependent context, but is not a
1004 // DeclContext. A context within it (such as a lambda-expression)
1005 // should be considered dependent.
1006
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001007 return getParent() && getParent()->isDependentContext();
1008}
1009
Douglas Gregor07665a62009-01-05 19:45:36 +00001010bool DeclContext::isTransparentContext() const {
1011 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +00001012 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +00001013 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +00001014 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +00001015
1016 return false;
1017}
1018
Serge Pavlov3cb80222013-11-14 02:13:03 +00001019static bool isLinkageSpecContext(const DeclContext *DC,
1020 LinkageSpecDecl::LanguageIDs ID) {
1021 while (DC->getDeclKind() != Decl::TranslationUnit) {
1022 if (DC->getDeclKind() == Decl::LinkageSpec)
1023 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +00001024 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +00001025 }
1026 return false;
1027}
1028
1029bool DeclContext::isExternCContext() const {
1030 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_c);
1031}
1032
Alex Lorenz560ae562016-11-02 15:46:34 +00001033const LinkageSpecDecl *DeclContext::getExternCContext() const {
1034 const DeclContext *DC = this;
1035 while (DC->getDeclKind() != Decl::TranslationUnit) {
1036 if (DC->getDeclKind() == Decl::LinkageSpec &&
1037 cast<LinkageSpecDecl>(DC)->getLanguage() ==
1038 clang::LinkageSpecDecl::lang_c)
1039 return cast<LinkageSpecDecl>(DC);
1040 DC = DC->getLexicalParent();
1041 }
1042 return nullptr;
1043}
1044
Serge Pavlov3cb80222013-11-14 02:13:03 +00001045bool DeclContext::isExternCXXContext() const {
1046 return isLinkageSpecContext(this, clang::LinkageSpecDecl::lang_cxx);
1047}
1048
Sebastian Redl50c68252010-08-31 00:36:30 +00001049bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001050 if (getPrimaryContext() != this)
1051 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Douglas Gregore985a3b2009-08-27 06:03:53 +00001053 for (; DC; DC = DC->getParent())
1054 if (DC->getPrimaryContext() == this)
1055 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001056 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001057}
1058
Steve Naroff35c62ae2009-01-08 17:28:14 +00001059DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001060 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001061 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001062 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001063 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001064 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001065 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001066 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001067 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001068 // There is only one DeclContext for these entities.
1069 return this;
1070
1071 case Decl::Namespace:
1072 // The original namespace is our primary context.
1073 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1074
Douglas Gregor91f84212008-12-11 16:49:14 +00001075 case Decl::ObjCMethod:
1076 return this;
1077
1078 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001079 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1080 return Def;
1081
1082 return this;
1083
Steve Naroff35c62ae2009-01-08 17:28:14 +00001084 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001085 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1086 return Def;
1087
1088 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001089
Steve Naroff35c62ae2009-01-08 17:28:14 +00001090 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001091 return this;
1092
Steve Naroff35c62ae2009-01-08 17:28:14 +00001093 case Decl::ObjCImplementation:
1094 case Decl::ObjCCategoryImpl:
1095 return this;
1096
Douglas Gregor91f84212008-12-11 16:49:14 +00001097 default:
Alexis Hunted053252010-05-30 07:21:58 +00001098 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001099 // If this is a tag type that has a definition or is currently
1100 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001101 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001102
1103 if (TagDecl *Def = Tag->getDefinition())
1104 return Def;
1105
Richard Smith5b21db82014-04-23 18:20:42 +00001106 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1107 // Note, TagType::getDecl returns the (partial) definition one exists.
1108 TagDecl *PossiblePartialDef = TagTy->getDecl();
1109 if (PossiblePartialDef->isBeingDefined())
1110 return PossiblePartialDef;
1111 } else {
1112 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001113 }
1114
1115 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001116 }
1117
Alexis Hunted053252010-05-30 07:21:58 +00001118 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001119 "Unknown DeclContext kind");
1120 return this;
1121 }
1122}
1123
Douglas Gregore57e7522012-01-07 09:11:48 +00001124void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001125DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001126 Contexts.clear();
1127
1128 if (DeclKind != Decl::Namespace) {
1129 Contexts.push_back(this);
1130 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001131 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001132
1133 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001134 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1135 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001136 Contexts.push_back(N);
1137
1138 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001139}
1140
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001141std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001142DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001143 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001144 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001145 Decl *FirstNewDecl = nullptr;
1146 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001147 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001148 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1149 continue;
1150
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001151 Decl *D = Decls[I];
1152 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001153 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001154 else
1155 FirstNewDecl = D;
1156
1157 PrevDecl = D;
1158 }
1159
1160 return std::make_pair(FirstNewDecl, PrevDecl);
1161}
1162
Richard Smith645d7552013-02-07 03:37:08 +00001163/// \brief We have just acquired external visible storage, and we already have
1164/// built a lookup map. For every name in the map, pull in the new names from
1165/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001166void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001167 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001168 NeedToReconcileExternalVisibleStorage = false;
1169
Richard Smith9e2341d2015-03-23 03:25:59 +00001170 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001171 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001172}
1173
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001174/// \brief Load the declarations within this lexical storage from an
1175/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001176/// \return \c true if any declarations were added.
1177bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001178DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1179 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001180 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1181
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001182 // Notify that we have a DeclContext that is initializing.
1183 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001184
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001185 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001186 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001187 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001188 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001189
1190 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001191 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001192
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001193 // We may have already loaded just the fields of this record, in which case
1194 // we need to ignore them.
1195 bool FieldsAlreadyLoaded = false;
1196 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1197 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1198
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001199 // Splice the newly-read declarations into the beginning of the list
1200 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001201 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001202 std::tie(ExternalFirst, ExternalLast) =
1203 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001204 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001205 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001206 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001207 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001208 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001209}
1210
John McCall75b960e2010-06-01 09:23:16 +00001211DeclContext::lookup_result
1212ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1213 DeclarationName Name) {
1214 ASTContext &Context = DC->getParentASTContext();
1215 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001216 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001217 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001218 if (DC->NeedToReconcileExternalVisibleStorage)
1219 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001220
Richard Smith4abe0a82013-09-09 07:34:56 +00001221 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001222
John McCall75b960e2010-06-01 09:23:16 +00001223 return DeclContext::lookup_result();
1224}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001225
John McCall75b960e2010-06-01 09:23:16 +00001226DeclContext::lookup_result
1227ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001228 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001229 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001230 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001231 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001232 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001233 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001234 if (DC->NeedToReconcileExternalVisibleStorage)
1235 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001236
1237 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001238
1239 // Clear out any old external visible declarations, to avoid quadratic
1240 // performance in the redeclaration checks below.
1241 List.removeExternalDecls();
1242
1243 if (!List.isNull()) {
1244 // We have both existing declarations and new declarations for this name.
1245 // Some of the declarations may simply replace existing ones. Handle those
1246 // first.
1247 llvm::SmallVector<unsigned, 8> Skip;
1248 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001249 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001250 Skip.push_back(I);
1251 Skip.push_back(Decls.size());
1252
1253 // Add in any new declarations.
1254 unsigned SkipPos = 0;
1255 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1256 if (I == Skip[SkipPos])
1257 ++SkipPos;
1258 else
1259 List.AddSubsequentDecl(Decls[I]);
1260 }
1261 } else {
1262 // Convert the array to a StoredDeclsList.
1263 for (ArrayRef<NamedDecl*>::iterator
1264 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1265 if (List.isNull())
1266 List.setOnlyValue(*I);
1267 else
1268 List.AddSubsequentDecl(*I);
1269 }
John McCall75b960e2010-06-01 09:23:16 +00001270 }
1271
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001272 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001273}
1274
Aaron Ballmanda634f12014-03-07 22:17:20 +00001275DeclContext::decl_iterator DeclContext::decls_begin() const {
1276 if (hasExternalLexicalStorage())
1277 LoadLexicalDeclsFromExternalStorage();
1278 return decl_iterator(FirstDecl);
1279}
1280
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001281bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001282 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001283 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001284
1285 return !FirstDecl;
1286}
1287
Sean Callanan0325fb82013-05-04 02:04:27 +00001288bool DeclContext::containsDecl(Decl *D) const {
1289 return (D->getLexicalDeclContext() == this &&
1290 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1291}
1292
John McCall84d87672009-12-10 09:41:52 +00001293void DeclContext::removeDecl(Decl *D) {
1294 assert(D->getLexicalDeclContext() == this &&
1295 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001296 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001297 "decl is not in decls list");
1298
1299 // Remove D from the decl chain. This is O(n) but hopefully rare.
1300 if (D == FirstDecl) {
1301 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001302 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001303 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001304 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001305 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001306 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001307 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001308 if (I->NextInContextAndBits.getPointer() == D) {
1309 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001310 if (D == LastDecl) LastDecl = I;
1311 break;
1312 }
1313 }
1314 }
1315
1316 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001317 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001318
1319 // Remove D from the lookup table if necessary.
1320 if (isa<NamedDecl>(D)) {
1321 NamedDecl *ND = cast<NamedDecl>(D);
1322
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001323 // Remove only decls that have a name
1324 if (!ND->getDeclName()) return;
1325
Richard Smith26210db2015-11-13 03:52:13 +00001326 auto *DC = this;
1327 do {
1328 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1329 if (Map) {
1330 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1331 assert(Pos != Map->end() && "no lookup entry for decl");
1332 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1333 Pos->second.remove(ND);
1334 }
1335 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001336 }
1337}
1338
John McCalld1e9d832009-08-11 06:59:38 +00001339void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001340 assert(D->getLexicalDeclContext() == this &&
1341 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001342 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001343 "Decl already inserted into a DeclContext");
1344
1345 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001346 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001347 LastDecl = D;
1348 } else {
1349 FirstDecl = LastDecl = D;
1350 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001351
1352 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001353 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001354 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1355 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001356
1357 // If this is a newly-created (not de-serialized) import declaration, wire
1358 // it in to the list of local import declarations.
1359 if (!D->isFromASTFile()) {
1360 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1361 D->getASTContext().addedLocalImportDecl(Import);
1362 }
John McCalld1e9d832009-08-11 06:59:38 +00001363}
1364
1365void DeclContext::addDecl(Decl *D) {
1366 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001367
1368 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001369 ND->getDeclContext()->getPrimaryContext()->
1370 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001371}
1372
Sean Callanan95e74be2011-10-21 02:57:43 +00001373void DeclContext::addDeclInternal(Decl *D) {
1374 addHiddenDecl(D);
1375
1376 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001377 ND->getDeclContext()->getPrimaryContext()->
1378 makeDeclVisibleInContextWithFlags(ND, true, true);
1379}
1380
1381/// shouldBeHidden - Determine whether a declaration which was declared
1382/// within its semantic context should be invisible to qualified name lookup.
1383static bool shouldBeHidden(NamedDecl *D) {
1384 // Skip unnamed declarations.
1385 if (!D->getDeclName())
1386 return true;
1387
1388 // Skip entities that can't be found by name lookup into a particular
1389 // context.
1390 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1391 D->isTemplateParameter())
1392 return true;
1393
1394 // Skip template specializations.
1395 // FIXME: This feels like a hack. Should DeclarationName support
1396 // template-ids, or is there a better way to keep specializations
1397 // from being visible?
1398 if (isa<ClassTemplateSpecializationDecl>(D))
1399 return true;
1400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1401 if (FD->isFunctionTemplateSpecialization())
1402 return true;
1403
1404 return false;
1405}
1406
1407/// buildLookup - Build the lookup data structure with all of the
1408/// declarations in this DeclContext (and any other contexts linked
1409/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001410///
1411/// Note that the produced map may miss out declarations from an
1412/// external source. If it does, those entries will be marked with
1413/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001414StoredDeclsMap *DeclContext::buildLookup() {
1415 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1416
Richard Smith9e2341d2015-03-23 03:25:59 +00001417 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1418 return LookupPtr;
1419
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001420 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001421 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001422
1423 if (HasLazyExternalLexicalLookups) {
1424 HasLazyExternalLexicalLookups = false;
1425 for (auto *DC : Contexts) {
1426 if (DC->hasExternalLexicalStorage())
1427 HasLazyLocalLexicalLookups |=
1428 DC->LoadLexicalDeclsFromExternalStorage();
1429 }
1430
1431 if (!HasLazyLocalLexicalLookups)
1432 return LookupPtr;
1433 }
1434
1435 for (auto *DC : Contexts)
1436 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001437
1438 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001439 HasLazyLocalLexicalLookups = false;
1440 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001441}
1442
1443/// buildLookupImpl - Build part of the lookup data structure for the
1444/// declarations contained within DCtx, which will either be this
1445/// DeclContext, a DeclContext linked to it, or a transparent context
1446/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001447void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001448 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001449 // Insert this declaration into the lookup structure, but only if
1450 // it's semantically within its decl context. Any other decls which
1451 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001452 //
1453 // If it's from an AST file, don't add it now. It'll get handled by
1454 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1455 // in C++, we do not track external visible decls for the TU, so in
1456 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001457 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001458 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1459 (!ND->isFromASTFile() ||
1460 (isTranslationUnit() &&
1461 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001462 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001463
1464 // If this declaration is itself a transparent declaration context
1465 // or inline namespace, add the members of this declaration of that
1466 // context (recursively).
1467 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1468 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001469 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001470 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001471}
1472
Richard Smith40c78062015-02-21 02:31:57 +00001473NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1474
Mike Stump11289f42009-09-09 15:08:12 +00001475DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001476DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001477 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1478 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001479
Manman Ren7d2f5c42016-09-09 19:03:07 +00001480 const DeclContext *PrimaryContext = getPrimaryContext();
1481 if (PrimaryContext != this)
1482 return PrimaryContext->lookup(Name);
1483
Richard Smith8cebe372015-02-25 22:20:13 +00001484 // If we have an external source, ensure that any later redeclarations of this
1485 // context have been loaded, since they may add names to the result of this
1486 // lookup (or add external visible storage).
1487 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1488 if (Source)
1489 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001490
Richard Smith05afe5e2012-03-13 03:12:56 +00001491 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001492 assert(Source && "external visible storage but no external source?");
1493
Richard Smitha8b74592014-03-25 00:34:21 +00001494 if (NeedToReconcileExternalVisibleStorage)
1495 reconcileExternalVisibleStorage();
1496
Richard Smith9e2341d2015-03-23 03:25:59 +00001497 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001498
Richard Smith9e2341d2015-03-23 03:25:59 +00001499 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001500 // FIXME: Make buildLookup const?
1501 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001502
Richard Smith75fc3bf2013-02-08 00:37:45 +00001503 if (!Map)
1504 Map = CreateStoredDeclsMap(getParentASTContext());
1505
Richard Smith4abe0a82013-09-09 07:34:56 +00001506 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001507 std::pair<StoredDeclsMap::iterator, bool> R =
1508 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001509 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001510 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001511
Richard Smith309271b2014-03-04 00:21:14 +00001512 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001513 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001514 StoredDeclsMap::iterator I = Map->find(Name);
1515 if (I != Map->end())
1516 return I->second.getLookupResult();
1517 }
1518 }
1519
Richard Smith40c78062015-02-21 02:31:57 +00001520 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001521 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001522
Richard Smith9e2341d2015-03-23 03:25:59 +00001523 StoredDeclsMap *Map = LookupPtr;
1524 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001525 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001526
1527 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001528 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001529
1530 StoredDeclsMap::iterator I = Map->find(Name);
1531 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001532 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001533
1534 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001535}
1536
Richard Smith95d99302013-07-13 02:00:19 +00001537DeclContext::lookup_result
1538DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001539 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1540 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001541
1542 DeclContext *PrimaryContext = getPrimaryContext();
1543 if (PrimaryContext != this)
1544 return PrimaryContext->noload_lookup(Name);
1545
Richard Smith9e2341d2015-03-23 03:25:59 +00001546 // If we have any lazy lexical declarations not in our lookup map, add them
1547 // now. Don't import any external declarations, not even if we know we have
1548 // some missing from the external visible lookups.
1549 if (HasLazyLocalLexicalLookups) {
Vince Harrona3ea9a42015-03-22 05:59:59 +00001550 SmallVector<DeclContext *, 2> Contexts;
1551 collectAllContexts(Contexts);
1552 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
Richard Smith9e2341d2015-03-23 03:25:59 +00001553 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1554 HasLazyLocalLexicalLookups = false;
Vince Harrona3ea9a42015-03-22 05:59:59 +00001555 }
1556
Richard Smith9e2341d2015-03-23 03:25:59 +00001557 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001558 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001559 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001560
1561 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001562 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001563 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001564}
1565
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001566void DeclContext::localUncachedLookup(DeclarationName Name,
1567 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001568 Results.clear();
1569
1570 // If there's no external storage, just perform a normal lookup and copy
1571 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001572 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001573 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001574 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001575 return;
1576 }
1577
1578 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001579 // FIXME: Should we be checking these flags on the primary context?
1580 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1581 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001582 StoredDeclsMap::iterator Pos = Map->find(Name);
1583 if (Pos != Map->end()) {
1584 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001585 Pos->second.getLookupResult().begin(),
1586 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001587 return;
1588 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001589 }
1590 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001591
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001592 // Slow case: grovel through the declarations in our chain looking for
1593 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001594 // FIXME: If we have lazy external declarations, this will not find them!
1595 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001596 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1597 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1598 if (ND->getDeclName() == Name)
1599 Results.push_back(ND);
1600 }
1601}
1602
Sebastian Redl50c68252010-08-31 00:36:30 +00001603DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001604 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001605 // Skip through transparent contexts.
1606 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001607 Ctx = Ctx->getParent();
1608 return Ctx;
1609}
1610
Douglas Gregorf47b9112009-02-25 22:02:03 +00001611DeclContext *DeclContext::getEnclosingNamespaceContext() {
1612 DeclContext *Ctx = this;
1613 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001614 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001615 Ctx = Ctx->getParent();
1616 return Ctx->getPrimaryContext();
1617}
1618
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001619RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1620 // Loop until we find a non-record context.
1621 RecordDecl *OutermostRD = nullptr;
1622 DeclContext *DC = this;
1623 while (DC->isRecord()) {
1624 OutermostRD = cast<RecordDecl>(DC);
1625 DC = DC->getLexicalParent();
1626 }
1627 return OutermostRD;
1628}
1629
Sebastian Redl50c68252010-08-31 00:36:30 +00001630bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1631 // For non-file contexts, this is equivalent to Equals.
1632 if (!isFileContext())
1633 return O->Equals(this);
1634
1635 do {
1636 if (O->Equals(this))
1637 return true;
1638
1639 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1640 if (!NS || !NS->isInline())
1641 break;
1642 O = NS->getParent();
1643 } while (O);
1644
1645 return false;
1646}
1647
Richard Smithf634c902012-03-16 06:12:59 +00001648void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1649 DeclContext *PrimaryDC = this->getPrimaryContext();
1650 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1651 // If the decl is being added outside of its semantic decl context, we
1652 // need to ensure that we eagerly build the lookup information for it.
1653 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001654}
1655
Richard Smithf634c902012-03-16 06:12:59 +00001656void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1657 bool Recoverable) {
1658 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001659
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001660 if (!isLookupContext()) {
1661 if (isTransparentContext())
1662 getParent()->getPrimaryContext()
1663 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001664 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001665 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001666
Richard Smithf634c902012-03-16 06:12:59 +00001667 // Skip declarations which should be invisible to name lookup.
1668 if (shouldBeHidden(D))
1669 return;
1670
1671 // If we already have a lookup data structure, perform the insertion into
1672 // it. If we might have externally-stored decls with this name, look them
1673 // up and perform the insertion. If this decl was declared outside its
1674 // semantic context, buildLookup won't add it, so add it now.
1675 //
1676 // FIXME: As a performance hack, don't add such decls into the translation
1677 // unit unless we're in C++, since qualified lookup into the TU is never
1678 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001679 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001680 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1681 (getParentASTContext().getLangOpts().CPlusPlus ||
1682 !isTranslationUnit()))) {
1683 // If we have lazily omitted any decls, they might have the same name as
1684 // the decl which we are adding, so build a full lookup table before adding
1685 // this decl.
1686 buildLookup();
1687 makeDeclVisibleInContextImpl(D, Internal);
1688 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001689 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001690 }
1691
1692 // If we are a transparent context or inline namespace, insert into our
1693 // parent context, too. This operation is recursive.
1694 if (isTransparentContext() || isInlineNamespace())
1695 getParent()->getPrimaryContext()->
1696 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1697
1698 Decl *DCAsDecl = cast<Decl>(this);
1699 // Notify that a decl was made visible unless we are a Tag being defined.
1700 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1701 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1702 L->AddedVisibleDecl(this, D);
1703}
1704
1705void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1706 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001707 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001708 if (!Map) {
1709 ASTContext *C = &getParentASTContext();
1710 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001711 }
1712
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001713 // If there is an external AST source, load any declarations it knows about
1714 // with this declaration's name.
1715 // If the lookup table contains an entry about this name it means that we
1716 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001717 if (!Internal)
1718 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1719 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001720 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001721 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001722
Douglas Gregor91f84212008-12-11 16:49:14 +00001723 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001724 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001725
1726 if (Internal) {
1727 // If this is being added as part of loading an external declaration,
1728 // this may not be the only external declaration with this name.
1729 // In this case, we never try to replace an existing declaration; we'll
1730 // handle that when we finalize the list of declarations for this name.
1731 DeclNameEntries.setHasExternalDecls();
1732 DeclNameEntries.AddSubsequentDecl(D);
1733 return;
1734 }
1735
Richard Smitha3271c12015-02-07 00:45:52 +00001736 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001737 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001738 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001739 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001740
Richard Smithe8292b12015-02-10 03:28:10 +00001741 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001742 // This declaration has replaced an existing one for which
1743 // declarationReplaces returns true.
1744 return;
1745 }
Mike Stump11289f42009-09-09 15:08:12 +00001746
Richard Smithf634c902012-03-16 06:12:59 +00001747 // Put this declaration into the appropriate slot.
1748 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001749}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001750
Richard Smith40c78062015-02-21 02:31:57 +00001751UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1752 return cast<UsingDirectiveDecl>(*I);
1753}
1754
Douglas Gregor889ceb72009-02-03 19:21:40 +00001755/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1756/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001757DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001758 // FIXME: Use something more efficient than normal lookup for using
1759 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001760 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001761 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001762}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001763
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001764//===----------------------------------------------------------------------===//
1765// Creation and Destruction of StoredDeclsMaps. //
1766//===----------------------------------------------------------------------===//
1767
John McCallc62bb642010-03-24 05:22:00 +00001768StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001769 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001770 assert(getPrimaryContext() == this &&
1771 "creating decls map on non-primary context");
1772
1773 StoredDeclsMap *M;
1774 bool Dependent = isDependentContext();
1775 if (Dependent)
1776 M = new DependentStoredDeclsMap();
1777 else
1778 M = new StoredDeclsMap();
1779 M->Previous = C.LastSDM;
1780 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001781 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001782 return M;
1783}
1784
1785void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001786 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1787 // pointer because the subclass doesn't add anything that needs to
1788 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001789 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1790}
1791
1792void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1793 while (Map) {
1794 // Advance the iteration before we invalidate memory.
1795 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1796
1797 if (Dependent)
1798 delete static_cast<DependentStoredDeclsMap*>(Map);
1799 else
1800 delete Map;
1801
1802 Map = Next.getPointer();
1803 Dependent = Next.getInt();
1804 }
1805}
1806
John McCallc62bb642010-03-24 05:22:00 +00001807DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1808 DeclContext *Parent,
1809 const PartialDiagnostic &PDiag) {
1810 assert(Parent->isDependentContext()
1811 && "cannot iterate dependent diagnostics of non-dependent context");
1812 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001813 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001814 Parent->CreateStoredDeclsMap(C);
1815
Richard Smith9e2341d2015-03-23 03:25:59 +00001816 DependentStoredDeclsMap *Map =
1817 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001818
Douglas Gregora55530e2010-03-29 23:56:53 +00001819 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001820 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001821 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001822 if (PDiag.hasStorage())
1823 DiagStorage = new (C) PartialDiagnostic::Storage;
1824
1825 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001826
1827 // TODO: Maybe we shouldn't reverse the order during insertion.
1828 DD->NextDiagnostic = Map->FirstDiagnostic;
1829 Map->FirstDiagnostic = DD;
1830
1831 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001832}