blob: fe8bd92f27ecb1e7a22d24a209b978cf1f6d1a96 [file] [log] [blame]
Eugene Zelenko0d00c892017-11-08 00:39:18 +00001//===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +00002//
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"
Eugene Zelenko0d00c892017-11-08 00:39:18 +000018#include "clang/AST/AttrIterator.h"
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +000019#include "clang/AST/Decl.h"
Argyrios Kyrtzidis2951e142008-06-09 21:05:31 +000020#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/DeclContextInternals.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000022#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclObjC.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000024#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000025#include "clang/AST/DeclTemplate.h"
John McCallc62bb642010-03-24 05:22:00 +000026#include "clang/AST/DependentDiagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "clang/AST/ExternalASTSource.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000028#include "clang/AST/Stmt.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/Type.h"
Eugene Zelenko0d00c892017-11-08 00:39:18 +000030#include "clang/Basic/IdentifierTable.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/LangOptions.h"
33#include "clang/Basic/ObjCRuntime.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceLocation.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000036#include "clang/Basic/TargetInfo.h"
Eugene Zelenko0d00c892017-11-08 00:39:18 +000037#include "clang/Basic/VersionTuple.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/MathExtras.h"
Chris Lattnereae6cb62009-03-05 08:00:35 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000046#include <algorithm>
Eugene Zelenko0d00c892017-11-08 00:39:18 +000047#include <cassert>
48#include <cstddef>
49#include <string>
50#include <tuple>
51#include <utility>
52
Eli Friedman7dbab8a2008-06-07 16:52:53 +000053using namespace clang;
54
55//===----------------------------------------------------------------------===//
56// Statistics
57//===----------------------------------------------------------------------===//
58
Alexis Hunted053252010-05-30 07:21:58 +000059#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
60#define ABSTRACT_DECL(DECL)
61#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +000062
Douglas Gregor7dab26b2013-02-09 01:35:03 +000063void Decl::updateOutOfDate(IdentifierInfo &II) const {
64 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
65}
66
James Y Knight53c76162015-07-17 18:21:37 +000067#define DECL(DERIVED, BASE) \
Benjamin Kramerc3f89252016-10-20 14:27:22 +000068 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
James Y Knight53c76162015-07-17 18:21:37 +000069 "Alignment sufficient after objects prepended to " #DERIVED);
70#define ABSTRACT_DECL(DECL)
71#include "clang/AST/DeclNodes.inc"
72
Richard Smithf7981722013-11-22 09:01:48 +000073void *Decl::operator new(std::size_t Size, const ASTContext &Context,
74 unsigned ID, std::size_t Extra) {
Douglas Gregor52261fd2012-01-05 23:49:36 +000075 // Allocate an extra 8 bytes worth of storage, which ensures that the
James Y Knight53c76162015-07-17 18:21:37 +000076 // resulting pointer will still be 8-byte aligned.
Benjamin Kramerc3f89252016-10-20 14:27:22 +000077 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
James Y Knight53c76162015-07-17 18:21:37 +000078 "Decl won't be misaligned");
Richard Smithf7981722013-11-22 09:01:48 +000079 void *Start = Context.Allocate(Size + Extra + 8);
Douglas Gregor52261fd2012-01-05 23:49:36 +000080 void *Result = (char*)Start + 8;
Richard Smithf7981722013-11-22 09:01:48 +000081
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000082 unsigned *PrefixPtr = (unsigned *)Result - 2;
Richard Smithf7981722013-11-22 09:01:48 +000083
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000084 // Zero out the first 4 bytes; this is used to store the owning module ID.
85 PrefixPtr[0] = 0;
Richard Smithf7981722013-11-22 09:01:48 +000086
Douglas Gregorcfe7dc62012-01-09 17:30:44 +000087 // Store the global declaration ID in the second 4 bytes.
88 PrefixPtr[1] = ID;
Richard Smithf7981722013-11-22 09:01:48 +000089
Douglas Gregor64af53c2012-01-05 22:27:05 +000090 return Result;
Douglas Gregor72172e92012-01-05 21:55:30 +000091}
92
Richard Smithf7981722013-11-22 09:01:48 +000093void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94 DeclContext *Parent, std::size_t Extra) {
95 assert(!Parent || &Parent->getParentASTContext() == &Ctx);
Richard Smith42413142015-05-15 20:05:43 +000096 // With local visibility enabled, we track the owning module even for local
Richard Smithdebbaef2017-09-05 00:50:19 +000097 // declarations. We create the TU decl early and may not yet know what the
98 // LangOpts are, so conservatively allocate the storage.
99 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
James Y Knight53c76162015-07-17 18:21:37 +0000100 // Ensure required alignment of the resulting object by adding extra
101 // padding at the start if required.
102 size_t ExtraAlign =
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000103 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
James Y Knight53c76162015-07-17 18:21:37 +0000104 char *Buffer = reinterpret_cast<char *>(
105 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106 Buffer += ExtraAlign;
Richard Smith26342f92017-05-17 00:24:14 +0000107 auto *ParentModule =
108 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
109 return new (Buffer) Module*(ParentModule) + 1;
Richard Smith42413142015-05-15 20:05:43 +0000110 }
Richard Smithf7981722013-11-22 09:01:48 +0000111 return ::operator new(Size + Extra, Ctx);
112}
113
Douglas Gregorc147b0b2013-01-12 01:29:50 +0000114Module *Decl::getOwningModuleSlow() const {
115 assert(isFromASTFile() && "Not from AST file?");
116 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
117}
118
Richard Smith87bb5692015-06-09 00:35:49 +0000119bool Decl::hasLocalOwningModuleStorage() const {
Richard Smith26342f92017-05-17 00:24:14 +0000120 return getASTContext().getLangOpts().trackLocalOwningModule();
Richard Smith87bb5692015-06-09 00:35:49 +0000121}
122
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000123const char *Decl::getDeclKindName() const {
124 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000125 default: llvm_unreachable("Declaration not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000126#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127#define ABSTRACT_DECL(DECL)
128#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000129 }
130}
131
Douglas Gregor90d47172010-03-05 00:26:45 +0000132void Decl::setInvalidDecl(bool Invalid) {
133 InvalidDecl = Invalid;
Alp Tokera5d64592013-12-21 01:10:54 +0000134 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
Richard Trieucbd54302016-11-11 20:51:04 +0000135 if (!Invalid) {
136 return;
137 }
138
139 if (!isa<ParmVarDecl>(this)) {
Douglas Gregor90d47172010-03-05 00:26:45 +0000140 // Defensive maneuver for ill-formed code: we're likely not to make it to
141 // a point where we set the access specifier, so default it to "public"
142 // to avoid triggering asserts elsewhere in the front end.
143 setAccess(AS_public);
144 }
Richard Trieucbd54302016-11-11 20:51:04 +0000145
146 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
147 // are invalid too.
148 if (DecompositionDecl *DD = dyn_cast<DecompositionDecl>(this)) {
149 for (BindingDecl *Binding : DD->bindings()) {
150 Binding->setInvalidDecl();
151 }
152 }
Douglas Gregor90d47172010-03-05 00:26:45 +0000153}
154
Steve Naroff5faaef72009-01-20 19:53:53 +0000155const char *DeclContext::getDeclKindName() const {
156 switch (DeclKind) {
David Blaikie83d382b2011-09-23 05:06:16 +0000157 default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
Alexis Hunted053252010-05-30 07:21:58 +0000158#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
159#define ABSTRACT_DECL(DECL)
160#include "clang/AST/DeclNodes.inc"
Steve Naroff5faaef72009-01-20 19:53:53 +0000161 }
162}
163
Daniel Dunbar62905572012-03-05 21:42:49 +0000164bool Decl::StatisticsEnabled = false;
165void Decl::EnableStatistics() {
166 StatisticsEnabled = true;
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000167}
168
169void Decl::PrintStats() {
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000170 llvm::errs() << "\n*** Decl Stats:\n";
Mike Stump11289f42009-09-09 15:08:12 +0000171
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000172 int totalDecls = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000173#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
174#define ABSTRACT_DECL(DECL)
175#include "clang/AST/DeclNodes.inc"
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000176 llvm::errs() << " " << totalDecls << " decls total.\n";
Mike Stump11289f42009-09-09 15:08:12 +0000177
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000178 int totalBytes = 0;
Alexis Hunted053252010-05-30 07:21:58 +0000179#define DECL(DERIVED, BASE) \
180 if (n##DERIVED##s > 0) { \
181 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000182 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
183 << sizeof(DERIVED##Decl) << " each (" \
184 << n##DERIVED##s * sizeof(DERIVED##Decl) \
185 << " bytes)\n"; \
Douglas Gregor8bd3c2e2009-02-02 23:39:07 +0000186 }
Alexis Hunted053252010-05-30 07:21:58 +0000187#define ABSTRACT_DECL(DECL)
188#include "clang/AST/DeclNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chandler Carruthbfb154a2011-07-04 06:13:27 +0000190 llvm::errs() << "Total bytes = " << totalBytes << "\n";
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000191}
192
Alexis Hunted053252010-05-30 07:21:58 +0000193void Decl::add(Kind k) {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000194 switch (k) {
Alexis Hunted053252010-05-30 07:21:58 +0000195#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
196#define ABSTRACT_DECL(DECL)
197#include "clang/AST/DeclNodes.inc"
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000198 }
199}
200
Anders Carlssonaa73b912009-06-13 00:08:58 +0000201bool Decl::isTemplateParameterPack() const {
202 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203 return TTP->isParameterPack();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000204 if (const NonTypeTemplateParmDecl *NTTP
Douglas Gregorf5500772011-01-05 15:48:55 +0000205 = dyn_cast<NonTypeTemplateParmDecl>(this))
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000206 return NTTP->isParameterPack();
Douglas Gregorf5500772011-01-05 15:48:55 +0000207 if (const TemplateTemplateParmDecl *TTP
208 = dyn_cast<TemplateTemplateParmDecl>(this))
209 return TTP->isParameterPack();
Anders Carlssonaa73b912009-06-13 00:08:58 +0000210 return false;
211}
212
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000213bool Decl::isParameterPack() const {
214 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
215 return Parm->isParameterPack();
216
217 return isTemplateParameterPack();
218}
219
Alp Tokera2794f92014-01-22 07:29:52 +0000220FunctionDecl *Decl::getAsFunction() {
221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
222 return FD;
223 if (const FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(this))
224 return FTD->getTemplatedDecl();
Craig Topper36250ad2014-05-12 05:36:57 +0000225 return nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000226}
227
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000228bool Decl::isTemplateDecl() const {
229 return isa<TemplateDecl>(this);
230}
231
Serge Pavlov7dcc97e2016-04-19 06:19:52 +0000232TemplateDecl *Decl::getDescribedTemplate() const {
233 if (auto *FD = dyn_cast<FunctionDecl>(this))
234 return FD->getDescribedFunctionTemplate();
235 else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
236 return RD->getDescribedClassTemplate();
237 else if (auto *VD = dyn_cast<VarDecl>(this))
238 return VD->getDescribedVarTemplate();
239
240 return nullptr;
241}
242
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000243const DeclContext *Decl::getParentFunctionOrMethod() const {
244 for (const DeclContext *DC = getDeclContext();
245 DC && !DC->isTranslationUnit() && !DC->isNamespace();
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000246 DC = DC->getParent())
247 if (DC->isFunctionOrMethod())
Argyrios Kyrtzidis0ce4c9a2011-09-28 02:45:33 +0000248 return DC;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000249
Craig Topper36250ad2014-05-12 05:36:57 +0000250 return nullptr;
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000251}
252
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000253//===----------------------------------------------------------------------===//
Chris Lattnereae6cb62009-03-05 08:00:35 +0000254// PrettyStackTraceDecl Implementation
255//===----------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000257void PrettyStackTraceDecl::print(raw_ostream &OS) const {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000258 SourceLocation TheLoc = Loc;
259 if (TheLoc.isInvalid() && TheDecl)
260 TheLoc = TheDecl->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000261
Chris Lattnereae6cb62009-03-05 08:00:35 +0000262 if (TheLoc.isValid()) {
263 TheLoc.print(OS, SM);
264 OS << ": ";
265 }
266
267 OS << Message;
268
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +0000269 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
270 OS << " '";
271 DN->printQualifiedName(OS);
272 OS << '\'';
273 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000274 OS << '\n';
275}
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattnereae6cb62009-03-05 08:00:35 +0000277//===----------------------------------------------------------------------===//
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000278// Decl Implementation
279//===----------------------------------------------------------------------===//
280
Douglas Gregorb11aad82011-02-19 18:51:44 +0000281// Out-of-line virtual method providing a home for Decl.
Eugene Zelenko0d00c892017-11-08 00:39:18 +0000282Decl::~Decl() = default;
Douglas Gregora43942a2011-02-17 07:02:32 +0000283
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000284void Decl::setDeclContext(DeclContext *DC) {
Chris Lattnerb81eb052009-03-29 06:06:59 +0000285 DeclCtx = DC;
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000286}
287
288void Decl::setLexicalDeclContext(DeclContext *DC) {
289 if (DC == getLexicalDeclContext())
290 return;
291
292 if (isInSemaDC()) {
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000293 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000294 } else {
295 getMultipleDC()->LexicalDC = DC;
296 }
Richard Smithae50c562017-05-23 22:02:49 +0000297
298 // FIXME: We shouldn't be changing the lexical context of declarations
299 // imported from AST files.
300 if (!isFromASTFile()) {
Richard Smith90dc5252017-06-23 01:04:34 +0000301 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
302 if (hasOwningModule())
Richard Smithae50c562017-05-23 22:02:49 +0000303 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
304 }
305
Richard Smithd19389a2017-07-05 07:47:11 +0000306 assert(
307 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
308 getOwningModule()) &&
309 "hidden declaration has no owning module");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000310}
311
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000312void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
313 ASTContext &Ctx) {
314 if (SemaDC == LexicalDC) {
315 DeclCtx = SemaDC;
316 } else {
317 Decl::MultipleDC *MDC = new (Ctx) Decl::MultipleDC();
318 MDC->SemanticDC = SemaDC;
319 MDC->LexicalDC = LexicalDC;
320 DeclCtx = MDC;
321 }
322}
323
Serge Pavlov73c6a242015-08-23 10:22:28 +0000324bool Decl::isLexicallyWithinFunctionOrMethod() const {
325 const DeclContext *LDC = getLexicalDeclContext();
Serge Pavlovb24a7112015-08-23 11:09:40 +0000326 while (true) {
Serge Pavlov73c6a242015-08-23 10:22:28 +0000327 if (LDC->isFunctionOrMethod())
328 return true;
329 if (!isa<TagDecl>(LDC))
330 return false;
Serge Pavlovb24a7112015-08-23 11:09:40 +0000331 LDC = LDC->getLexicalParent();
332 }
Serge Pavlov73c6a242015-08-23 10:22:28 +0000333 return false;
334}
335
John McCall4fa53422009-10-01 00:25:31 +0000336bool Decl::isInAnonymousNamespace() const {
Richard Smithbecb92d2017-10-10 22:33:17 +0000337 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
John McCall4fa53422009-10-01 00:25:31 +0000338 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
339 if (ND->isAnonymousNamespace())
340 return true;
Richard Smithbecb92d2017-10-10 22:33:17 +0000341 }
John McCall4fa53422009-10-01 00:25:31 +0000342
343 return false;
344}
345
Richard Trieuc771d5d2014-05-28 02:16:01 +0000346bool Decl::isInStdNamespace() const {
347 return getDeclContext()->isStdNamespace();
348}
349
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000350TranslationUnitDecl *Decl::getTranslationUnitDecl() {
Argyrios Kyrtzidis4e1a72b2009-06-30 02:34:53 +0000351 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
352 return TUD;
353
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000354 DeclContext *DC = getDeclContext();
355 assert(DC && "This decl is not contained in a translation unit!");
Mike Stump11289f42009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000357 while (!DC->isTranslationUnit()) {
358 DC = DC->getParent();
359 assert(DC && "This decl is not contained in a translation unit!");
360 }
Mike Stump11289f42009-09-09 15:08:12 +0000361
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000362 return cast<TranslationUnitDecl>(DC);
363}
364
365ASTContext &Decl::getASTContext() const {
Mike Stump11289f42009-09-09 15:08:12 +0000366 return getTranslationUnitDecl()->getASTContext();
Argyrios Kyrtzidis743e7db2009-06-29 17:38:40 +0000367}
368
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +0000369ASTMutationListener *Decl::getASTMutationListener() const {
370 return getASTContext().getASTMutationListener();
371}
372
Benjamin Kramerea70eb32012-12-01 15:09:41 +0000373unsigned Decl::getMaxAlignment() const {
374 if (!hasAttrs())
375 return 0;
376
377 unsigned Align = 0;
378 const AttrVec &V = getAttrs();
379 ASTContext &Ctx = getASTContext();
380 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
381 for (; I != E; ++I)
382 Align = std::max(Align, I->getAlignment(Ctx));
383 return Align;
384}
385
Vassil Vassilev928c8252016-04-28 14:13:28 +0000386bool Decl::isUsed(bool CheckUsedAttr) const {
387 const Decl *CanonD = getCanonicalDecl();
388 if (CanonD->Used)
Vassil Vassileva4d7d782016-04-27 10:46:06 +0000389 return true;
390
Vassil Vassilev928c8252016-04-28 14:13:28 +0000391 // Check for used attribute.
392 // Ask the most recent decl, since attributes accumulate in the redecl chain.
393 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
394 return true;
395
396 // The information may have not been deserialized yet. Force deserialization
397 // to complete the needed information.
398 return getMostRecentDecl()->getCanonicalDecl()->Used;
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000399}
400
Eli Friedman276dd182013-09-05 00:02:25 +0000401void Decl::markUsed(ASTContext &C) {
Vassil Vassilev928c8252016-04-28 14:13:28 +0000402 if (isUsed(false))
Eli Friedman276dd182013-09-05 00:02:25 +0000403 return;
404
405 if (C.getASTMutationListener())
406 C.getASTMutationListener()->DeclarationMarkedUsed(this);
407
Vassil Vassilev928c8252016-04-28 14:13:28 +0000408 setIsUsed();
Eli Friedman276dd182013-09-05 00:02:25 +0000409}
410
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000411bool Decl::isReferenced() const {
412 if (Referenced)
413 return true;
414
415 // Check redeclarations.
Aaron Ballman86c93902014-03-06 23:45:36 +0000416 for (auto I : redecls())
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000417 if (I->Referenced)
418 return true;
419
420 return false;
421}
422
Richard Smith3b660562016-09-26 21:27:23 +0000423bool Decl::isExported() const {
424 if (isModulePrivate())
425 return false;
426 // Namespaces are always exported.
427 if (isa<TranslationUnitDecl>(this) || isa<NamespaceDecl>(this))
428 return true;
429 // Otherwise, this is a strictly lexical check.
430 for (auto *DC = getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) {
431 if (cast<Decl>(DC)->isModulePrivate())
432 return false;
433 if (isa<ExportDecl>(DC))
434 return true;
435 }
436 return false;
437}
438
Argyrios Kyrtzidis11d70482017-05-20 04:11:33 +0000439ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
440 const Decl *Definition = nullptr;
441 if (auto ID = dyn_cast<ObjCInterfaceDecl>(this)) {
442 Definition = ID->getDefinition();
443 } else if (auto PD = dyn_cast<ObjCProtocolDecl>(this)) {
444 Definition = PD->getDefinition();
445 } else if (auto TD = dyn_cast<TagDecl>(this)) {
446 Definition = TD->getDefinition();
447 }
448 if (!Definition)
449 Definition = this;
450
451 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
452 return attr;
453 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
454 return dcd->getAttr<ExternalSourceSymbolAttr>();
455 }
456
457 return nullptr;
458}
459
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000460bool Decl::hasDefiningAttr() const {
461 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
462}
463
464const Attr *Decl::getDefiningAttr() const {
465 if (AliasAttr *AA = getAttr<AliasAttr>())
466 return AA;
467 if (IFuncAttr *IFA = getAttr<IFuncAttr>())
468 return IFA;
469 return nullptr;
470}
471
Benjamin Kramer674d5792017-05-26 20:08:24 +0000472static StringRef getRealizedPlatform(const AvailabilityAttr *A,
473 const ASTContext &Context) {
Alex Lorenza8a372d2017-04-27 10:43:48 +0000474 // Check if this is an App Extension "platform", and if so chop off
475 // the suffix for matching with the actual platform.
476 StringRef RealizedPlatform = A->getPlatform()->getName();
477 if (!Context.getLangOpts().AppExt)
478 return RealizedPlatform;
479 size_t suffix = RealizedPlatform.rfind("_app_extension");
480 if (suffix != StringRef::npos)
481 return RealizedPlatform.slice(0, suffix);
482 return RealizedPlatform;
483}
484
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000485/// \brief Determine the availability of the given declaration based on
486/// the target platform.
487///
488/// When it returns an availability result other than \c AR_Available,
489/// if the \p Message parameter is non-NULL, it will be set to a
490/// string describing why the entity is unavailable.
491///
492/// FIXME: Make these strings localizable, since they end up in
493/// diagnostics.
494static AvailabilityResult CheckAvailability(ASTContext &Context,
495 const AvailabilityAttr *A,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000496 std::string *Message,
497 VersionTuple EnclosingVersion) {
498 if (EnclosingVersion.empty())
499 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000500
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000501 if (EnclosingVersion.empty())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000502 return AR_Available;
503
Bob Wilsonb111ec92015-03-02 19:01:14 +0000504 StringRef ActualPlatform = A->getPlatform()->getName();
Bob Wilsonb111ec92015-03-02 19:01:14 +0000505 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
506
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000507 // Match the platform name.
Alex Lorenza8a372d2017-04-27 10:43:48 +0000508 if (getRealizedPlatform(A, Context) != TargetPlatform)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000509 return AR_Available;
Bob Wilsonb111ec92015-03-02 19:01:14 +0000510
511 StringRef PrettyPlatformName
512 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
513
514 if (PrettyPlatformName.empty())
515 PrettyPlatformName = ActualPlatform;
516
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000517 std::string HintMessage;
518 if (!A->getMessage().empty()) {
519 HintMessage = " - ";
520 HintMessage += A->getMessage();
521 }
522
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000523 // Make sure that this declaration has not been marked 'unavailable'.
524 if (A->getUnavailable()) {
525 if (Message) {
526 Message->clear();
527 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian88d510d2011-12-10 00:28:41 +0000528 Out << "not available on " << PrettyPlatformName
529 << HintMessage;
Douglas Gregor7ab142b2011-03-26 03:35:55 +0000530 }
531
532 return AR_Unavailable;
533 }
534
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000535 // Make sure that this declaration has already been introduced.
536 if (!A->getIntroduced().empty() &&
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000537 EnclosingVersion < A->getIntroduced()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000538 if (Message) {
539 Message->clear();
540 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000541 VersionTuple VTI(A->getIntroduced());
542 VTI.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000543 Out << "introduced in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000544 << VTI << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000545 }
546
Duncan P. N. Exon Smith5d6790c2016-03-08 06:12:54 +0000547 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000548 }
549
550 // Make sure that this declaration hasn't been obsoleted.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000551 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000552 if (Message) {
553 Message->clear();
554 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000555 VersionTuple VTO(A->getObsoleted());
556 VTO.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000557 Out << "obsoleted in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000558 << VTO << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000559 }
560
561 return AR_Unavailable;
562 }
563
564 // Make sure that this declaration hasn't been deprecated.
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000565 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000566 if (Message) {
567 Message->clear();
568 llvm::raw_string_ostream Out(*Message);
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000569 VersionTuple VTD(A->getDeprecated());
570 VTD.UseDotAsSeparator();
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000571 Out << "first deprecated in " << PrettyPlatformName << ' '
Fariborz Jahanian2618dba2014-10-06 16:46:02 +0000572 << VTD << HintMessage;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000573 }
574
575 return AR_Deprecated;
576 }
577
578 return AR_Available;
579}
580
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000581AvailabilityResult Decl::getAvailability(std::string *Message,
582 VersionTuple EnclosingVersion) const {
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000583 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000584 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +0000585
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000586 AvailabilityResult Result = AR_Available;
587 std::string ResultMessage;
588
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000589 for (const auto *A : attrs()) {
590 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000591 if (Result >= AR_Deprecated)
592 continue;
593
594 if (Message)
595 ResultMessage = Deprecated->getMessage();
596
597 Result = AR_Deprecated;
598 continue;
599 }
600
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000601 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000602 if (Message)
603 *Message = Unavailable->getMessage();
604 return AR_Unavailable;
605 }
606
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000607 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000608 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000609 Message, EnclosingVersion);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000610
611 if (AR == AR_Unavailable)
612 return AR_Unavailable;
613
614 if (AR > Result) {
615 Result = AR;
616 if (Message)
617 ResultMessage.swap(*Message);
618 }
619 continue;
620 }
621 }
622
623 if (Message)
624 Message->swap(ResultMessage);
625 return Result;
626}
627
Alex Lorenza8a372d2017-04-27 10:43:48 +0000628VersionTuple Decl::getVersionIntroduced() const {
629 const ASTContext &Context = getASTContext();
630 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
631 for (const auto *A : attrs()) {
632 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
633 if (getRealizedPlatform(Availability, Context) != TargetPlatform)
634 continue;
635 if (!Availability->getIntroduced().empty())
636 return Availability->getIntroduced();
637 }
638 }
639 return VersionTuple();
640}
641
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000642bool Decl::canBeWeakImported(bool &IsDefinition) const {
643 IsDefinition = false;
John McCall5fb5df92012-06-20 06:18:46 +0000644
645 // Variables, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000646 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000647 if (Var->isThisDeclarationADefinition()) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000648 IsDefinition = true;
649 return false;
650 }
John McCall5fb5df92012-06-20 06:18:46 +0000651 return true;
652
653 // Functions, if they aren't definitions.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000654 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
655 if (FD->hasBody()) {
656 IsDefinition = true;
657 return false;
658 }
John McCall5fb5df92012-06-20 06:18:46 +0000659 return true;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000660
John McCall5fb5df92012-06-20 06:18:46 +0000661 // Objective-C classes, if this is the non-fragile runtime.
662 } else if (isa<ObjCInterfaceDecl>(this) &&
John McCall18ac1632012-06-20 21:58:02 +0000663 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
John McCall5fb5df92012-06-20 06:18:46 +0000664 return true;
665
666 // Nothing else.
667 } else {
668 return false;
669 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000670}
671
672bool Decl::isWeakImported() const {
673 bool IsDefinition;
674 if (!canBeWeakImported(IsDefinition))
675 return false;
676
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000677 for (const auto *A : attrs()) {
678 if (isa<WeakImportAttr>(A))
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000679 return true;
680
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000681 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
Erik Pilkington48c7cc92016-07-29 17:37:38 +0000682 if (CheckAvailability(getASTContext(), Availability, nullptr,
683 VersionTuple()) == AR_NotYetIntroduced)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000684 return true;
685 }
686 }
687
688 return false;
689}
Tanya Lattner8aefcbe2010-02-17 02:17:21 +0000690
Chris Lattner8e097192009-03-27 20:18:19 +0000691unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
692 switch (DeclKind) {
John McCall3f746822009-11-17 05:59:44 +0000693 case Function:
Richard Smithbc491202017-02-17 20:05:37 +0000694 case CXXDeductionGuide:
John McCall3f746822009-11-17 05:59:44 +0000695 case CXXMethod:
696 case CXXConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +0000697 case ConstructorUsingShadow:
John McCall3f746822009-11-17 05:59:44 +0000698 case CXXDestructor:
699 case CXXConversion:
Chris Lattner8e097192009-03-27 20:18:19 +0000700 case EnumConstant:
701 case Var:
702 case ImplicitParam:
703 case ParmVar:
Chris Lattner8e097192009-03-27 20:18:19 +0000704 case ObjCMethod:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000705 case ObjCProperty:
John McCall5e77d762013-04-16 07:28:30 +0000706 case MSProperty:
Daniel Dunbar45b2d8a2010-04-23 13:07:39 +0000707 return IDNS_Ordinary;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000708 case Label:
709 return IDNS_Label;
Francois Pichet783dd6e2010-11-21 06:08:52 +0000710 case IndirectField:
711 return IDNS_Ordinary | IDNS_Member;
712
Richard Smithb8c41902017-09-07 20:22:00 +0000713 case Binding:
Richard Smith9f951822016-01-06 22:49:11 +0000714 case NonTypeTemplateParm:
Richard Smithb8c41902017-09-07 20:22:00 +0000715 case VarTemplate:
716 // These (C++-only) declarations are found by redeclaration lookup for
717 // tag types, so we include them in the tag namespace.
Richard Smith9f951822016-01-06 22:49:11 +0000718 return IDNS_Ordinary | IDNS_Tag;
719
John McCalle87beb22010-04-23 18:46:30 +0000720 case ObjCCompatibleAlias:
721 case ObjCInterface:
722 return IDNS_Ordinary | IDNS_Type;
723
724 case Typedef:
Richard Smithdda56e42011-04-15 14:24:37 +0000725 case TypeAlias:
John McCalle87beb22010-04-23 18:46:30 +0000726 case TemplateTypeParm:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000727 case ObjCTypeParam:
John McCalle87beb22010-04-23 18:46:30 +0000728 return IDNS_Ordinary | IDNS_Type;
729
Richard Smith151c4562016-12-20 21:35:28 +0000730 case UnresolvedUsingTypename:
731 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
732
John McCall3f746822009-11-17 05:59:44 +0000733 case UsingShadow:
734 return 0; // we'll actually overwrite this later
735
John McCalle61f2ba2009-11-18 02:36:19 +0000736 case UnresolvedUsingValue:
John McCalle61f2ba2009-11-18 02:36:19 +0000737 return IDNS_Ordinary | IDNS_Using;
John McCall3f746822009-11-17 05:59:44 +0000738
739 case Using:
Richard Smith151c4562016-12-20 21:35:28 +0000740 case UsingPack:
John McCall3f746822009-11-17 05:59:44 +0000741 return IDNS_Using;
742
Chris Lattner8e097192009-03-27 20:18:19 +0000743 case ObjCProtocol:
Douglas Gregor79947a22009-04-24 00:11:27 +0000744 return IDNS_ObjCProtocol;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattner8e097192009-03-27 20:18:19 +0000746 case Field:
747 case ObjCAtDefsField:
748 case ObjCIvar:
749 return IDNS_Member;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattner8e097192009-03-27 20:18:19 +0000751 case Record:
752 case CXXRecord:
753 case Enum:
John McCalle87beb22010-04-23 18:46:30 +0000754 return IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner8e097192009-03-27 20:18:19 +0000756 case Namespace:
John McCalle87beb22010-04-23 18:46:30 +0000757 case NamespaceAlias:
758 return IDNS_Namespace;
759
Chris Lattner8e097192009-03-27 20:18:19 +0000760 case FunctionTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000761 return IDNS_Ordinary;
762
Chris Lattner8e097192009-03-27 20:18:19 +0000763 case ClassTemplate:
764 case TemplateTemplateParm:
Richard Smithb8c41902017-09-07 20:22:00 +0000765 case TypeAliasTemplate:
John McCalle87beb22010-04-23 18:46:30 +0000766 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
Mike Stump11289f42009-09-09 15:08:12 +0000767
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000768 case OMPDeclareReduction:
769 return IDNS_OMPReduction;
770
Chris Lattner8e097192009-03-27 20:18:19 +0000771 // Never have names.
John McCallaa74a0c2009-08-28 07:59:38 +0000772 case Friend:
John McCall11083da2009-09-16 22:47:08 +0000773 case FriendTemplate:
Abramo Bagnarad7340582010-06-05 05:09:32 +0000774 case AccessSpec:
Chris Lattner8e097192009-03-27 20:18:19 +0000775 case LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +0000776 case Export:
Chris Lattner8e097192009-03-27 20:18:19 +0000777 case FileScopeAsm:
778 case StaticAssert:
Chris Lattner8e097192009-03-27 20:18:19 +0000779 case ObjCPropertyImpl:
Nico Weber66220292016-03-02 17:28:48 +0000780 case PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +0000781 case PragmaDetectMismatch:
Chris Lattner8e097192009-03-27 20:18:19 +0000782 case Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000783 case Captured:
Chris Lattner8e097192009-03-27 20:18:19 +0000784 case TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +0000785 case ExternCContext:
Richard Smithbdb84f32016-07-22 23:36:59 +0000786 case Decomposition:
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000787
Chris Lattner8e097192009-03-27 20:18:19 +0000788 case UsingDirective:
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000789 case BuiltinTemplate:
Chris Lattner8e097192009-03-27 20:18:19 +0000790 case ClassTemplateSpecialization:
Douglas Gregor2373c592009-05-31 09:31:02 +0000791 case ClassTemplatePartialSpecialization:
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000792 case ClassScopeFunctionSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +0000793 case VarTemplateSpecialization:
794 case VarTemplatePartialSpecialization:
Douglas Gregore93525e2010-04-22 23:19:50 +0000795 case ObjCImplementation:
796 case ObjCCategory:
797 case ObjCCategoryImpl:
Douglas Gregorba345522011-12-02 23:23:56 +0000798 case Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000799 case OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000800 case OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000801 case Empty:
Douglas Gregore93525e2010-04-22 23:19:50 +0000802 // Never looked up by name.
Chris Lattner8e097192009-03-27 20:18:19 +0000803 return 0;
804 }
John McCall3f746822009-11-17 05:59:44 +0000805
David Blaikiee4d798f2012-01-20 21:50:17 +0000806 llvm_unreachable("Invalid DeclKind!");
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000807}
808
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000809void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000810 assert(!HasAttrs && "Decl already contains attrs.");
811
Argyrios Kyrtzidis6f40eb72012-02-09 02:44:08 +0000812 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000813 assert(AttrBlank.empty() && "HasAttrs was wrong?");
Argyrios Kyrtzidis91167172010-06-11 23:09:25 +0000814
815 AttrBlank = attrs;
816 HasAttrs = true;
817}
818
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000819void Decl::dropAttrs() {
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000820 if (!HasAttrs) return;
Mike Stump11289f42009-09-09 15:08:12 +0000821
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000822 HasAttrs = false;
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000823 getASTContext().eraseDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000824}
825
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000826const AttrVec &Decl::getAttrs() const {
827 assert(HasAttrs && "No attrs to get!");
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000828 return getASTContext().getDeclAttrs(this);
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000829}
830
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000831Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000832 Decl::Kind DK = D->getDeclKind();
833 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000834#define DECL(NAME, BASE)
835#define DECL_CONTEXT(NAME) \
836 case Decl::NAME: \
837 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
838#define DECL_CONTEXT_BASE(NAME)
839#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000840 default:
Alexis Hunted053252010-05-30 07:21:58 +0000841#define DECL(NAME, BASE)
842#define DECL_CONTEXT_BASE(NAME) \
843 if (DK >= first##NAME && DK <= last##NAME) \
844 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D));
845#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000846 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000847 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000848}
849
850DeclContext *Decl::castToDeclContext(const Decl *D) {
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000851 Decl::Kind DK = D->getKind();
852 switch(DK) {
Alexis Hunted053252010-05-30 07:21:58 +0000853#define DECL(NAME, BASE)
854#define DECL_CONTEXT(NAME) \
855 case Decl::NAME: \
856 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
857#define DECL_CONTEXT_BASE(NAME)
858#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000859 default:
Alexis Hunted053252010-05-30 07:21:58 +0000860#define DECL(NAME, BASE)
861#define DECL_CONTEXT_BASE(NAME) \
862 if (DK >= first##NAME && DK <= last##NAME) \
863 return static_cast<NAME##Decl*>(const_cast<Decl*>(D));
864#include "clang/AST/DeclNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +0000865 llvm_unreachable("a decl that inherits DeclContext isn't handled");
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000866 }
Argyrios Kyrtzidis3768ad62008-10-12 16:14:48 +0000867}
868
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000869SourceLocation Decl::getBodyRBrace() const {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +0000870 // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
871 // FunctionDecl stores EndRangeLoc for this purpose.
872 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
873 const FunctionDecl *Definition;
874 if (FD->hasBody(Definition))
875 return Definition->getSourceRange().getEnd();
876 return SourceLocation();
877 }
878
Argyrios Kyrtzidis6fbc8fa2010-07-07 11:31:27 +0000879 if (Stmt *Body = getBody())
880 return Body->getSourceRange().getEnd();
881
882 return SourceLocation();
Sebastian Redla7b98a72009-04-26 20:35:05 +0000883}
884
Alp Tokerc1086762013-12-07 13:51:35 +0000885bool Decl::AccessDeclContextSanity() const {
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000886#ifndef NDEBUG
John McCall401982f2010-01-20 21:53:11 +0000887 // Suppress this check if any of the following hold:
888 // 1. this is the translation unit (and thus has no parent)
889 // 2. this is a template parameter (and thus doesn't belong to its context)
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000890 // 3. this is a non-type template parameter
891 // 4. the context is not a record
892 // 5. it's invalid
893 // 6. it's a C++0x static_assert.
Anders Carlssonadf36b22009-08-29 20:47:47 +0000894 if (isa<TranslationUnitDecl>(this) ||
Argyrios Kyrtzidisa45855f2010-07-02 11:55:44 +0000895 isa<TemplateTypeParmDecl>(this) ||
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000896 isa<NonTypeTemplateParmDecl>(this) ||
Douglas Gregor2b76dd92010-02-22 17:53:38 +0000897 !isa<CXXRecordDecl>(getDeclContext()) ||
Argyrios Kyrtzidis260b4a82010-09-08 21:32:35 +0000898 isInvalidDecl() ||
899 isa<StaticAssertDecl>(this) ||
900 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
901 // as DeclContext (?).
Argyrios Kyrtzidise1778632010-09-08 21:58:42 +0000902 isa<ParmVarDecl>(this) ||
903 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
904 // AS_none as access specifier.
Francois Pichet09af8c32011-08-17 01:06:54 +0000905 isa<CXXRecordDecl>(this) ||
906 isa<ClassScopeFunctionSpecializationDecl>(this))
Alp Tokerc1086762013-12-07 13:51:35 +0000907 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000908
909 assert(Access != AS_none &&
Anders Carlssona28908d2009-03-25 23:38:06 +0000910 "Access specifier is AS_none inside a record decl");
Douglas Gregor4b00d3b2010-12-02 00:22:25 +0000911#endif
Alp Tokerc1086762013-12-07 13:51:35 +0000912 return true;
Anders Carlssona28908d2009-03-25 23:38:06 +0000913}
914
John McCalldec348f72013-05-03 07:33:41 +0000915static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
916static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
917
Aaron Ballman12b9f652014-01-16 13:55:42 +0000918const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
919 QualType Ty;
920 if (const ValueDecl *D = dyn_cast<ValueDecl>(this))
921 Ty = D->getType();
922 else if (const TypedefNameDecl *D = dyn_cast<TypedefNameDecl>(this))
923 Ty = D->getUnderlyingType();
924 else
Craig Topper36250ad2014-05-12 05:36:57 +0000925 return nullptr;
Aaron Ballman12b9f652014-01-16 13:55:42 +0000926
927 if (Ty->isFunctionPointerType())
928 Ty = Ty->getAs<PointerType>()->getPointeeType();
929 else if (BlocksToo && Ty->isBlockPointerType())
930 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
931
932 return Ty->getAs<FunctionType>();
933}
934
John McCalldec348f72013-05-03 07:33:41 +0000935/// Starting at a given context (a Decl or DeclContext), look for a
936/// code context that is not a closure (a lambda, block, etc.).
937template <class T> static Decl *getNonClosureContext(T *D) {
938 if (getKind(D) == Decl::CXXMethod) {
939 CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
John McCall55c0cee2013-05-03 17:11:14 +0000940 if (MD->getOverloadedOperator() == OO_Call &&
941 MD->getParent()->isLambda())
John McCalldec348f72013-05-03 07:33:41 +0000942 return getNonClosureContext(MD->getParent()->getParent());
943 return MD;
944 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
945 return FD;
946 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
947 return MD;
948 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
949 return getNonClosureContext(BD->getParent());
950 } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
951 return getNonClosureContext(CD->getParent());
952 } else {
Craig Topper36250ad2014-05-12 05:36:57 +0000953 return nullptr;
John McCalldec348f72013-05-03 07:33:41 +0000954 }
John McCallfe96e0b2011-11-06 09:01:30 +0000955}
956
John McCalldec348f72013-05-03 07:33:41 +0000957Decl *Decl::getNonClosureContext() {
958 return ::getNonClosureContext(this);
959}
John McCallb67608f2011-02-22 22:25:23 +0000960
John McCalldec348f72013-05-03 07:33:41 +0000961Decl *DeclContext::getNonClosureAncestor() {
962 return ::getNonClosureContext(this);
John McCallb67608f2011-02-22 22:25:23 +0000963}
Anders Carlssona28908d2009-03-25 23:38:06 +0000964
Eli Friedman7dbab8a2008-06-07 16:52:53 +0000965//===----------------------------------------------------------------------===//
966// DeclContext Implementation
967//===----------------------------------------------------------------------===//
968
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000969bool DeclContext::classof(const Decl *D) {
970 switch (D->getKind()) {
Alexis Hunted053252010-05-30 07:21:58 +0000971#define DECL(NAME, BASE)
972#define DECL_CONTEXT(NAME) case Decl::NAME:
973#define DECL_CONTEXT_BASE(NAME)
974#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000975 return true;
976 default:
Alexis Hunted053252010-05-30 07:21:58 +0000977#define DECL(NAME, BASE)
978#define DECL_CONTEXT_BASE(NAME) \
979 if (D->getKind() >= Decl::first##NAME && \
980 D->getKind() <= Decl::last##NAME) \
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000981 return true;
Alexis Hunted053252010-05-30 07:21:58 +0000982#include "clang/AST/DeclNodes.inc"
Argyrios Kyrtzidisafe24c82009-02-16 14:29:28 +0000983 return false;
984 }
985}
986
Eugene Zelenko0d00c892017-11-08 00:39:18 +0000987DeclContext::~DeclContext() = default;
Douglas Gregor91f84212008-12-11 16:49:14 +0000988
Douglas Gregor7f737c02009-09-10 16:57:35 +0000989/// \brief Find the parent context of this context that will be
990/// used for unqualified name lookup.
991///
992/// Generally, the parent lookup context is the semantic context. However, for
993/// a friend function the parent lookup context is the lexical context, which
994/// is the class in which the friend is declared.
995DeclContext *DeclContext::getLookupParent() {
996 // FIXME: Find a better way to identify friends
997 if (isa<FunctionDecl>(this))
Sebastian Redl50c68252010-08-31 00:36:30 +0000998 if (getParent()->getRedeclContext()->isFileContext() &&
999 getLexicalParent()->getRedeclContext()->isRecord())
Douglas Gregor7f737c02009-09-10 16:57:35 +00001000 return getLexicalParent();
1001
1002 return getParent();
1003}
1004
Sebastian Redlbd595762010-08-31 20:53:31 +00001005bool DeclContext::isInlineNamespace() const {
1006 return isNamespace() &&
1007 cast<NamespaceDecl>(this)->isInline();
1008}
1009
Richard Trieuc771d5d2014-05-28 02:16:01 +00001010bool DeclContext::isStdNamespace() const {
1011 if (!isNamespace())
1012 return false;
1013
1014 const NamespaceDecl *ND = cast<NamespaceDecl>(this);
1015 if (ND->isInline()) {
1016 return ND->getParent()->isStdNamespace();
1017 }
1018
1019 if (!getParent()->getRedeclContext()->isTranslationUnit())
1020 return false;
1021
1022 const IdentifierInfo *II = ND->getIdentifier();
1023 return II && II->isStr("std");
1024}
1025
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001026bool DeclContext::isDependentContext() const {
1027 if (isFileContext())
1028 return false;
1029
Douglas Gregor2373c592009-05-31 09:31:02 +00001030 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1031 return true;
1032
Douglas Gregor680e9e02012-02-21 19:11:17 +00001033 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001034 if (Record->getDescribedClassTemplate())
1035 return true;
Douglas Gregor680e9e02012-02-21 19:11:17 +00001036
1037 if (Record->isDependentLambda())
1038 return true;
1039 }
1040
John McCallc62bb642010-03-24 05:22:00 +00001041 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001042 if (Function->getDescribedFunctionTemplate())
1043 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001044
John McCallc62bb642010-03-24 05:22:00 +00001045 // Friend function declarations are dependent if their *lexical*
1046 // context is dependent.
1047 if (cast<Decl>(this)->getFriendObjectKind())
1048 return getLexicalParent()->isDependentContext();
1049 }
1050
Richard Smith2b560572015-02-07 03:11:11 +00001051 // FIXME: A variable template is a dependent context, but is not a
1052 // DeclContext. A context within it (such as a lambda-expression)
1053 // should be considered dependent.
1054
Douglas Gregor9e927ab2009-05-28 16:34:51 +00001055 return getParent() && getParent()->isDependentContext();
1056}
1057
Douglas Gregor07665a62009-01-05 19:45:36 +00001058bool DeclContext::isTransparentContext() const {
1059 if (DeclKind == Decl::Enum)
Douglas Gregor0bf31402010-10-08 23:50:27 +00001060 return !cast<EnumDecl>(this)->isScoped();
Richard Smith8df390f2016-09-08 23:14:54 +00001061 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
Douglas Gregor07665a62009-01-05 19:45:36 +00001062 return true;
Douglas Gregor07665a62009-01-05 19:45:36 +00001063
1064 return false;
1065}
1066
Serge Pavlov3cb80222013-11-14 02:13:03 +00001067static bool isLinkageSpecContext(const DeclContext *DC,
1068 LinkageSpecDecl::LanguageIDs ID) {
1069 while (DC->getDeclKind() != Decl::TranslationUnit) {
1070 if (DC->getDeclKind() == Decl::LinkageSpec)
1071 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
Richard Smithac9c9a02014-04-14 20:23:58 +00001072 DC = DC->getLexicalParent();
Serge Pavlov3cb80222013-11-14 02:13:03 +00001073 }
1074 return false;
1075}
1076
1077bool DeclContext::isExternCContext() const {
Eugene Zelenko0d00c892017-11-08 00:39:18 +00001078 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
Serge Pavlov3cb80222013-11-14 02:13:03 +00001079}
1080
Alex Lorenz560ae562016-11-02 15:46:34 +00001081const LinkageSpecDecl *DeclContext::getExternCContext() const {
1082 const DeclContext *DC = this;
1083 while (DC->getDeclKind() != Decl::TranslationUnit) {
1084 if (DC->getDeclKind() == Decl::LinkageSpec &&
Eugene Zelenko0d00c892017-11-08 00:39:18 +00001085 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
Alex Lorenz560ae562016-11-02 15:46:34 +00001086 return cast<LinkageSpecDecl>(DC);
1087 DC = DC->getLexicalParent();
1088 }
1089 return nullptr;
1090}
1091
Serge Pavlov3cb80222013-11-14 02:13:03 +00001092bool DeclContext::isExternCXXContext() const {
Eugene Zelenko0d00c892017-11-08 00:39:18 +00001093 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
Serge Pavlov3cb80222013-11-14 02:13:03 +00001094}
1095
Sebastian Redl50c68252010-08-31 00:36:30 +00001096bool DeclContext::Encloses(const DeclContext *DC) const {
Douglas Gregore985a3b2009-08-27 06:03:53 +00001097 if (getPrimaryContext() != this)
1098 return getPrimaryContext()->Encloses(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001099
Douglas Gregore985a3b2009-08-27 06:03:53 +00001100 for (; DC; DC = DC->getParent())
1101 if (DC->getPrimaryContext() == this)
1102 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001103 return false;
Douglas Gregore985a3b2009-08-27 06:03:53 +00001104}
1105
Steve Naroff35c62ae2009-01-08 17:28:14 +00001106DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor91f84212008-12-11 16:49:14 +00001107 switch (DeclKind) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001108 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +00001109 case Decl::ExternCContext:
Douglas Gregor07665a62009-01-05 19:45:36 +00001110 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +00001111 case Decl::Export:
Mike Stump11289f42009-09-09 15:08:12 +00001112 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001113 case Decl::Captured:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001114 case Decl::OMPDeclareReduction:
Douglas Gregor91f84212008-12-11 16:49:14 +00001115 // There is only one DeclContext for these entities.
1116 return this;
1117
1118 case Decl::Namespace:
1119 // The original namespace is our primary context.
1120 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
1121
Douglas Gregor91f84212008-12-11 16:49:14 +00001122 case Decl::ObjCMethod:
1123 return this;
1124
1125 case Decl::ObjCInterface:
Douglas Gregor66b310c2011-12-15 18:03:09 +00001126 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1127 return Def;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001128 return this;
1129
Steve Naroff35c62ae2009-01-08 17:28:14 +00001130 case Decl::ObjCProtocol:
Douglas Gregora715bff2012-01-01 19:51:50 +00001131 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1132 return Def;
Douglas Gregora715bff2012-01-01 19:51:50 +00001133 return this;
Douglas Gregor66b310c2011-12-15 18:03:09 +00001134
Steve Naroff35c62ae2009-01-08 17:28:14 +00001135 case Decl::ObjCCategory:
Douglas Gregor91f84212008-12-11 16:49:14 +00001136 return this;
1137
Steve Naroff35c62ae2009-01-08 17:28:14 +00001138 case Decl::ObjCImplementation:
1139 case Decl::ObjCCategoryImpl:
1140 return this;
1141
Douglas Gregor91f84212008-12-11 16:49:14 +00001142 default:
Alexis Hunted053252010-05-30 07:21:58 +00001143 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
Douglas Gregor67a65642009-02-17 23:15:12 +00001144 // If this is a tag type that has a definition or is currently
1145 // being defined, that definition is our primary context.
John McCalle78aac42010-03-10 03:28:59 +00001146 TagDecl *Tag = cast<TagDecl>(this);
John McCalle78aac42010-03-10 03:28:59 +00001147
1148 if (TagDecl *Def = Tag->getDefinition())
1149 return Def;
1150
Richard Smith5b21db82014-04-23 18:20:42 +00001151 if (const TagType *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1152 // Note, TagType::getDecl returns the (partial) definition one exists.
1153 TagDecl *PossiblePartialDef = TagTy->getDecl();
1154 if (PossiblePartialDef->isBeingDefined())
1155 return PossiblePartialDef;
1156 } else {
1157 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
John McCalle78aac42010-03-10 03:28:59 +00001158 }
1159
1160 return Tag;
Douglas Gregor67a65642009-02-17 23:15:12 +00001161 }
1162
Alexis Hunted053252010-05-30 07:21:58 +00001163 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
Douglas Gregor91f84212008-12-11 16:49:14 +00001164 "Unknown DeclContext kind");
1165 return this;
1166 }
1167}
1168
Douglas Gregore57e7522012-01-07 09:11:48 +00001169void
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001170DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
Douglas Gregore57e7522012-01-07 09:11:48 +00001171 Contexts.clear();
1172
1173 if (DeclKind != Decl::Namespace) {
1174 Contexts.push_back(this);
1175 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001176 }
Douglas Gregore57e7522012-01-07 09:11:48 +00001177
1178 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001179 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1180 N = N->getPreviousDecl())
Douglas Gregore57e7522012-01-07 09:11:48 +00001181 Contexts.push_back(N);
1182
1183 std::reverse(Contexts.begin(), Contexts.end());
Douglas Gregor91f84212008-12-11 16:49:14 +00001184}
1185
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001186std::pair<Decl *, Decl *>
Bill Wendling8eb771d2012-02-22 09:51:33 +00001187DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001188 bool FieldsAlreadyLoaded) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001189 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
Craig Topper36250ad2014-05-12 05:36:57 +00001190 Decl *FirstNewDecl = nullptr;
1191 Decl *PrevDecl = nullptr;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001192 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001193 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1194 continue;
1195
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001196 Decl *D = Decls[I];
1197 if (PrevDecl)
Douglas Gregor781f7132012-01-06 16:59:53 +00001198 PrevDecl->NextInContextAndBits.setPointer(D);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001199 else
1200 FirstNewDecl = D;
1201
1202 PrevDecl = D;
1203 }
1204
1205 return std::make_pair(FirstNewDecl, PrevDecl);
1206}
1207
Richard Smith645d7552013-02-07 03:37:08 +00001208/// \brief We have just acquired external visible storage, and we already have
1209/// built a lookup map. For every name in the map, pull in the new names from
1210/// the external storage.
Richard Smitha8b74592014-03-25 00:34:21 +00001211void DeclContext::reconcileExternalVisibleStorage() const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001212 assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
Richard Smith645d7552013-02-07 03:37:08 +00001213 NeedToReconcileExternalVisibleStorage = false;
1214
Richard Smith9e2341d2015-03-23 03:25:59 +00001215 for (auto &Lookup : *LookupPtr)
Richard Smitha8b74592014-03-25 00:34:21 +00001216 Lookup.second.setHasExternalDecls();
Richard Smith645d7552013-02-07 03:37:08 +00001217}
1218
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001219/// \brief Load the declarations within this lexical storage from an
1220/// external source.
Richard Smith18b380b2015-03-24 02:44:20 +00001221/// \return \c true if any declarations were added.
1222bool
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001223DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1224 ExternalASTSource *Source = getParentASTContext().getExternalSource();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001225 assert(hasExternalLexicalStorage() && Source && "No external storage?");
1226
Argyrios Kyrtzidis98d045e2010-07-30 10:03:23 +00001227 // Notify that we have a DeclContext that is initializing.
1228 ExternalASTSource::Deserializing ADeclContext(Source);
Richard Smith9e2341d2015-03-23 03:25:59 +00001229
Douglas Gregor3d0adb32011-07-15 21:46:17 +00001230 // Load the external declarations, if any.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001231 SmallVector<Decl*, 64> Decls;
Richard Smith18b380b2015-03-24 02:44:20 +00001232 ExternalLexicalStorage = false;
Richard Smith3cb15722015-08-05 22:41:45 +00001233 Source->FindExternalLexicalDecls(this, Decls);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001234
1235 if (Decls.empty())
Richard Smith18b380b2015-03-24 02:44:20 +00001236 return false;
Richard Smith9e2341d2015-03-23 03:25:59 +00001237
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00001238 // We may have already loaded just the fields of this record, in which case
1239 // we need to ignore them.
1240 bool FieldsAlreadyLoaded = false;
1241 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this))
1242 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage;
1243
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001244 // Splice the newly-read declarations into the beginning of the list
1245 // of declarations.
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001246 Decl *ExternalFirst, *ExternalLast;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001247 std::tie(ExternalFirst, ExternalLast) =
1248 BuildDeclChain(Decls, FieldsAlreadyLoaded);
Douglas Gregor781f7132012-01-06 16:59:53 +00001249 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001250 FirstDecl = ExternalFirst;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001251 if (!LastDecl)
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00001252 LastDecl = ExternalLast;
Richard Smith18b380b2015-03-24 02:44:20 +00001253 return true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001254}
1255
John McCall75b960e2010-06-01 09:23:16 +00001256DeclContext::lookup_result
1257ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1258 DeclarationName Name) {
1259 ASTContext &Context = DC->getParentASTContext();
1260 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001261 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001262 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001263 if (DC->NeedToReconcileExternalVisibleStorage)
1264 DC->reconcileExternalVisibleStorage();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001265
Richard Smith4abe0a82013-09-09 07:34:56 +00001266 (*Map)[Name].removeExternalDecls();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001267
John McCall75b960e2010-06-01 09:23:16 +00001268 return DeclContext::lookup_result();
1269}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001270
John McCall75b960e2010-06-01 09:23:16 +00001271DeclContext::lookup_result
1272ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
John McCall75b960e2010-06-01 09:23:16 +00001273 DeclarationName Name,
Argyrios Kyrtzidis94d3f9d2011-09-09 06:44:14 +00001274 ArrayRef<NamedDecl*> Decls) {
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00001275 ASTContext &Context = DC->getParentASTContext();
John McCall75b960e2010-06-01 09:23:16 +00001276 StoredDeclsMap *Map;
Richard Smith9e2341d2015-03-23 03:25:59 +00001277 if (!(Map = DC->LookupPtr))
John McCall75b960e2010-06-01 09:23:16 +00001278 Map = DC->CreateStoredDeclsMap(Context);
Richard Smitha8b74592014-03-25 00:34:21 +00001279 if (DC->NeedToReconcileExternalVisibleStorage)
1280 DC->reconcileExternalVisibleStorage();
John McCall75b960e2010-06-01 09:23:16 +00001281
1282 StoredDeclsList &List = (*Map)[Name];
Richard Smith51445cd2013-06-24 01:46:41 +00001283
1284 // Clear out any old external visible declarations, to avoid quadratic
1285 // performance in the redeclaration checks below.
1286 List.removeExternalDecls();
1287
1288 if (!List.isNull()) {
1289 // We have both existing declarations and new declarations for this name.
1290 // Some of the declarations may simply replace existing ones. Handle those
1291 // first.
1292 llvm::SmallVector<unsigned, 8> Skip;
1293 for (unsigned I = 0, N = Decls.size(); I != N; ++I)
Richard Smithe8292b12015-02-10 03:28:10 +00001294 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
Richard Smith51445cd2013-06-24 01:46:41 +00001295 Skip.push_back(I);
1296 Skip.push_back(Decls.size());
1297
1298 // Add in any new declarations.
1299 unsigned SkipPos = 0;
1300 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1301 if (I == Skip[SkipPos])
1302 ++SkipPos;
1303 else
1304 List.AddSubsequentDecl(Decls[I]);
1305 }
1306 } else {
1307 // Convert the array to a StoredDeclsList.
1308 for (ArrayRef<NamedDecl*>::iterator
1309 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1310 if (List.isNull())
1311 List.setOnlyValue(*I);
1312 else
1313 List.AddSubsequentDecl(*I);
1314 }
John McCall75b960e2010-06-01 09:23:16 +00001315 }
1316
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001317 return List.getLookupResult();
John McCall75b960e2010-06-01 09:23:16 +00001318}
1319
Aaron Ballmanda634f12014-03-07 22:17:20 +00001320DeclContext::decl_iterator DeclContext::decls_begin() const {
1321 if (hasExternalLexicalStorage())
1322 LoadLexicalDeclsFromExternalStorage();
1323 return decl_iterator(FirstDecl);
1324}
1325
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001326bool DeclContext::decls_empty() const {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001327 if (hasExternalLexicalStorage())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001328 LoadLexicalDeclsFromExternalStorage();
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001329
1330 return !FirstDecl;
1331}
1332
Sean Callanan0325fb82013-05-04 02:04:27 +00001333bool DeclContext::containsDecl(Decl *D) const {
1334 return (D->getLexicalDeclContext() == this &&
1335 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1336}
1337
John McCall84d87672009-12-10 09:41:52 +00001338void DeclContext::removeDecl(Decl *D) {
1339 assert(D->getLexicalDeclContext() == this &&
1340 "decl being removed from non-lexical context");
Douglas Gregor781f7132012-01-06 16:59:53 +00001341 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
John McCall84d87672009-12-10 09:41:52 +00001342 "decl is not in decls list");
1343
1344 // Remove D from the decl chain. This is O(n) but hopefully rare.
1345 if (D == FirstDecl) {
1346 if (D == LastDecl)
Craig Topper36250ad2014-05-12 05:36:57 +00001347 FirstDecl = LastDecl = nullptr;
John McCall84d87672009-12-10 09:41:52 +00001348 else
Douglas Gregor781f7132012-01-06 16:59:53 +00001349 FirstDecl = D->NextInContextAndBits.getPointer();
John McCall84d87672009-12-10 09:41:52 +00001350 } else {
Douglas Gregor781f7132012-01-06 16:59:53 +00001351 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
John McCall84d87672009-12-10 09:41:52 +00001352 assert(I && "decl not found in linked list");
Douglas Gregor781f7132012-01-06 16:59:53 +00001353 if (I->NextInContextAndBits.getPointer() == D) {
1354 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
John McCall84d87672009-12-10 09:41:52 +00001355 if (D == LastDecl) LastDecl = I;
1356 break;
1357 }
1358 }
1359 }
1360
1361 // Mark that D is no longer in the decl chain.
Craig Topper36250ad2014-05-12 05:36:57 +00001362 D->NextInContextAndBits.setPointer(nullptr);
John McCall84d87672009-12-10 09:41:52 +00001363
1364 // Remove D from the lookup table if necessary.
1365 if (isa<NamedDecl>(D)) {
1366 NamedDecl *ND = cast<NamedDecl>(D);
1367
Axel Naumanncb2c52f2011-08-26 14:06:12 +00001368 // Remove only decls that have a name
1369 if (!ND->getDeclName()) return;
1370
Vassil Vassilev2e415982017-06-20 14:59:57 +00001371 auto *DC = D->getDeclContext();
Richard Smith26210db2015-11-13 03:52:13 +00001372 do {
1373 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1374 if (Map) {
1375 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1376 assert(Pos != Map->end() && "no lookup entry for decl");
1377 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1378 Pos->second.remove(ND);
1379 }
1380 } while (DC->isTransparentContext() && (DC = DC->getParent()));
John McCall84d87672009-12-10 09:41:52 +00001381 }
1382}
1383
John McCalld1e9d832009-08-11 06:59:38 +00001384void DeclContext::addHiddenDecl(Decl *D) {
Chris Lattner33f219d2009-02-20 00:56:18 +00001385 assert(D->getLexicalDeclContext() == this &&
1386 "Decl inserted into wrong lexical context");
Mike Stump11289f42009-09-09 15:08:12 +00001387 assert(!D->getNextDeclInContext() && D != LastDecl &&
Douglas Gregor020713e2009-01-09 19:42:16 +00001388 "Decl already inserted into a DeclContext");
1389
1390 if (FirstDecl) {
Douglas Gregor781f7132012-01-06 16:59:53 +00001391 LastDecl->NextInContextAndBits.setPointer(D);
Douglas Gregor020713e2009-01-09 19:42:16 +00001392 LastDecl = D;
1393 } else {
1394 FirstDecl = LastDecl = D;
1395 }
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001396
1397 // Notify a C++ record declaration that we've added a member, so it can
Nick Lewycky4b81fc872015-10-18 20:32:12 +00001398 // update its class-specific state.
Douglas Gregora1ce1f82010-09-27 22:06:20 +00001399 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1400 Record->addedMember(D);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001401
1402 // If this is a newly-created (not de-serialized) import declaration, wire
1403 // it in to the list of local import declarations.
1404 if (!D->isFromASTFile()) {
1405 if (ImportDecl *Import = dyn_cast<ImportDecl>(D))
1406 D->getASTContext().addedLocalImportDecl(Import);
1407 }
John McCalld1e9d832009-08-11 06:59:38 +00001408}
1409
1410void DeclContext::addDecl(Decl *D) {
1411 addHiddenDecl(D);
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001412
1413 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001414 ND->getDeclContext()->getPrimaryContext()->
1415 makeDeclVisibleInContextWithFlags(ND, false, true);
Douglas Gregor91f84212008-12-11 16:49:14 +00001416}
1417
Sean Callanan95e74be2011-10-21 02:57:43 +00001418void DeclContext::addDeclInternal(Decl *D) {
1419 addHiddenDecl(D);
1420
1421 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithf634c902012-03-16 06:12:59 +00001422 ND->getDeclContext()->getPrimaryContext()->
1423 makeDeclVisibleInContextWithFlags(ND, true, true);
1424}
1425
1426/// shouldBeHidden - Determine whether a declaration which was declared
1427/// within its semantic context should be invisible to qualified name lookup.
1428static bool shouldBeHidden(NamedDecl *D) {
1429 // Skip unnamed declarations.
1430 if (!D->getDeclName())
1431 return true;
1432
1433 // Skip entities that can't be found by name lookup into a particular
1434 // context.
1435 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1436 D->isTemplateParameter())
1437 return true;
1438
1439 // Skip template specializations.
1440 // FIXME: This feels like a hack. Should DeclarationName support
1441 // template-ids, or is there a better way to keep specializations
1442 // from being visible?
1443 if (isa<ClassTemplateSpecializationDecl>(D))
1444 return true;
1445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1446 if (FD->isFunctionTemplateSpecialization())
1447 return true;
1448
1449 return false;
1450}
1451
1452/// buildLookup - Build the lookup data structure with all of the
1453/// declarations in this DeclContext (and any other contexts linked
1454/// to it or transparent contexts nested within it) and return it.
Richard Smitha8b74592014-03-25 00:34:21 +00001455///
1456/// Note that the produced map may miss out declarations from an
1457/// external source. If it does, those entries will be marked with
1458/// the 'hasExternalDecls' flag.
Richard Smithf634c902012-03-16 06:12:59 +00001459StoredDeclsMap *DeclContext::buildLookup() {
1460 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1461
Richard Smith9e2341d2015-03-23 03:25:59 +00001462 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1463 return LookupPtr;
1464
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001465 SmallVector<DeclContext *, 2> Contexts;
Richard Smithf634c902012-03-16 06:12:59 +00001466 collectAllContexts(Contexts);
Richard Smith18b380b2015-03-24 02:44:20 +00001467
1468 if (HasLazyExternalLexicalLookups) {
1469 HasLazyExternalLexicalLookups = false;
1470 for (auto *DC : Contexts) {
1471 if (DC->hasExternalLexicalStorage())
1472 HasLazyLocalLexicalLookups |=
1473 DC->LoadLexicalDeclsFromExternalStorage();
1474 }
1475
1476 if (!HasLazyLocalLexicalLookups)
1477 return LookupPtr;
1478 }
1479
1480 for (auto *DC : Contexts)
1481 buildLookupImpl(DC, hasExternalVisibleStorage());
Richard Smithf634c902012-03-16 06:12:59 +00001482
1483 // We no longer have any lazy decls.
Richard Smith9e2341d2015-03-23 03:25:59 +00001484 HasLazyLocalLexicalLookups = false;
1485 return LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001486}
1487
1488/// buildLookupImpl - Build part of the lookup data structure for the
1489/// declarations contained within DCtx, which will either be this
1490/// DeclContext, a DeclContext linked to it, or a transparent context
1491/// nested within it.
Richard Smitha3271c12015-02-07 00:45:52 +00001492void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001493 for (Decl *D : DCtx->noload_decls()) {
Richard Smithf634c902012-03-16 06:12:59 +00001494 // Insert this declaration into the lookup structure, but only if
1495 // it's semantically within its decl context. Any other decls which
1496 // should be found in this context are added eagerly.
Richard Smithcf4ab522013-06-24 07:20:36 +00001497 //
1498 // If it's from an AST file, don't add it now. It'll get handled by
1499 // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1500 // in C++, we do not track external visible decls for the TU, so in
1501 // that case we need to collect them all here.
Richard Smithf634c902012-03-16 06:12:59 +00001502 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Richard Smithcf4ab522013-06-24 07:20:36 +00001503 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1504 (!ND->isFromASTFile() ||
1505 (isTranslationUnit() &&
1506 !getParentASTContext().getLangOpts().CPlusPlus)))
Richard Smitha3271c12015-02-07 00:45:52 +00001507 makeDeclVisibleInContextImpl(ND, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001508
1509 // If this declaration is itself a transparent declaration context
1510 // or inline namespace, add the members of this declaration of that
1511 // context (recursively).
1512 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(D))
1513 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
Richard Smith9e2341d2015-03-23 03:25:59 +00001514 buildLookupImpl(InnerCtx, Internal);
Richard Smithf634c902012-03-16 06:12:59 +00001515 }
Sean Callanan95e74be2011-10-21 02:57:43 +00001516}
1517
Richard Smith40c78062015-02-21 02:31:57 +00001518NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1519
Mike Stump11289f42009-09-09 15:08:12 +00001520DeclContext::lookup_result
Richard Smith40c78062015-02-21 02:31:57 +00001521DeclContext::lookup(DeclarationName Name) const {
Richard Smith8df390f2016-09-08 23:14:54 +00001522 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1523 "should not perform lookups into transparent contexts");
Nick Lewycky2bd636f2012-03-13 04:12:34 +00001524
Manman Ren7d2f5c42016-09-09 19:03:07 +00001525 const DeclContext *PrimaryContext = getPrimaryContext();
1526 if (PrimaryContext != this)
1527 return PrimaryContext->lookup(Name);
1528
Richard Smith8cebe372015-02-25 22:20:13 +00001529 // If we have an external source, ensure that any later redeclarations of this
1530 // context have been loaded, since they may add names to the result of this
1531 // lookup (or add external visible storage).
1532 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1533 if (Source)
1534 (void)cast<Decl>(this)->getMostRecentDecl();
Richard Smithbb853c72014-08-13 01:23:33 +00001535
Richard Smith05afe5e2012-03-13 03:12:56 +00001536 if (hasExternalVisibleStorage()) {
Richard Smith8cebe372015-02-25 22:20:13 +00001537 assert(Source && "external visible storage but no external source?");
1538
Richard Smitha8b74592014-03-25 00:34:21 +00001539 if (NeedToReconcileExternalVisibleStorage)
1540 reconcileExternalVisibleStorage();
1541
Richard Smith9e2341d2015-03-23 03:25:59 +00001542 StoredDeclsMap *Map = LookupPtr;
Richard Smitha8b74592014-03-25 00:34:21 +00001543
Richard Smith9e2341d2015-03-23 03:25:59 +00001544 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001545 // FIXME: Make buildLookup const?
1546 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smith645d7552013-02-07 03:37:08 +00001547
Richard Smith75fc3bf2013-02-08 00:37:45 +00001548 if (!Map)
1549 Map = CreateStoredDeclsMap(getParentASTContext());
1550
Richard Smith4abe0a82013-09-09 07:34:56 +00001551 // If we have a lookup result with no external decls, we are done.
Richard Smith75fc3bf2013-02-08 00:37:45 +00001552 std::pair<StoredDeclsMap::iterator, bool> R =
1553 Map->insert(std::make_pair(Name, StoredDeclsList()));
Richard Smith4abe0a82013-09-09 07:34:56 +00001554 if (!R.second && !R.first->second.hasExternalDecls())
Richard Smith75fc3bf2013-02-08 00:37:45 +00001555 return R.first->second.getLookupResult();
Richard Smithf634c902012-03-16 06:12:59 +00001556
Richard Smith309271b2014-03-04 00:21:14 +00001557 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
Richard Smith9e2341d2015-03-23 03:25:59 +00001558 if (StoredDeclsMap *Map = LookupPtr) {
Richard Smith9ce12e32013-02-07 03:30:24 +00001559 StoredDeclsMap::iterator I = Map->find(Name);
1560 if (I != Map->end())
1561 return I->second.getLookupResult();
1562 }
1563 }
1564
Richard Smith40c78062015-02-21 02:31:57 +00001565 return lookup_result();
John McCall75b960e2010-06-01 09:23:16 +00001566 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001567
Richard Smith9e2341d2015-03-23 03:25:59 +00001568 StoredDeclsMap *Map = LookupPtr;
1569 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
Richard Smith40c78062015-02-21 02:31:57 +00001570 Map = const_cast<DeclContext*>(this)->buildLookup();
Richard Smithf634c902012-03-16 06:12:59 +00001571
1572 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001573 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001574
1575 StoredDeclsMap::iterator I = Map->find(Name);
1576 if (I == Map->end())
Richard Smith40c78062015-02-21 02:31:57 +00001577 return lookup_result();
Richard Smithf634c902012-03-16 06:12:59 +00001578
1579 return I->second.getLookupResult();
Douglas Gregor91f84212008-12-11 16:49:14 +00001580}
1581
Richard Smith95d99302013-07-13 02:00:19 +00001582DeclContext::lookup_result
1583DeclContext::noload_lookup(DeclarationName Name) {
Richard Smith8df390f2016-09-08 23:14:54 +00001584 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1585 "should not perform lookups into transparent contexts");
Richard Smith95d99302013-07-13 02:00:19 +00001586
1587 DeclContext *PrimaryContext = getPrimaryContext();
1588 if (PrimaryContext != this)
1589 return PrimaryContext->noload_lookup(Name);
1590
Sam McCall091b1ef2018-01-16 12:33:46 +00001591 loadLazyLocalLexicalLookups();
Richard Smith9e2341d2015-03-23 03:25:59 +00001592 StoredDeclsMap *Map = LookupPtr;
Richard Smith95d99302013-07-13 02:00:19 +00001593 if (!Map)
Richard Smith40c78062015-02-21 02:31:57 +00001594 return lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001595
1596 StoredDeclsMap::iterator I = Map->find(Name);
Craig Topper36250ad2014-05-12 05:36:57 +00001597 return I != Map->end() ? I->second.getLookupResult()
Richard Smith40c78062015-02-21 02:31:57 +00001598 : lookup_result();
Richard Smith95d99302013-07-13 02:00:19 +00001599}
1600
Sam McCall091b1ef2018-01-16 12:33:46 +00001601// If we have any lazy lexical declarations not in our lookup map, add them
1602// now. Don't import any external declarations, not even if we know we have
1603// some missing from the external visible lookups.
1604void DeclContext::loadLazyLocalLexicalLookups() {
1605 if (HasLazyLocalLexicalLookups) {
1606 SmallVector<DeclContext *, 2> Contexts;
1607 collectAllContexts(Contexts);
1608 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1609 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1610 HasLazyLocalLexicalLookups = false;
1611 }
1612}
1613
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001614void DeclContext::localUncachedLookup(DeclarationName Name,
1615 SmallVectorImpl<NamedDecl *> &Results) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001616 Results.clear();
1617
1618 // If there's no external storage, just perform a normal lookup and copy
1619 // the results.
Douglas Gregordd6006f2012-07-17 21:16:27 +00001620 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001621 lookup_result LookupResults = lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00001622 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001623 return;
1624 }
1625
1626 // If we have a lookup table, check there first. Maybe we'll get lucky.
Richard Smith9e2341d2015-03-23 03:25:59 +00001627 // FIXME: Should we be checking these flags on the primary context?
1628 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1629 if (StoredDeclsMap *Map = LookupPtr) {
Douglas Gregordd6006f2012-07-17 21:16:27 +00001630 StoredDeclsMap::iterator Pos = Map->find(Name);
1631 if (Pos != Map->end()) {
1632 Results.insert(Results.end(),
David Blaikieff7d47a2012-12-19 00:45:41 +00001633 Pos->second.getLookupResult().begin(),
1634 Pos->second.getLookupResult().end());
Douglas Gregordd6006f2012-07-17 21:16:27 +00001635 return;
1636 }
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001637 }
1638 }
Douglas Gregordd6006f2012-07-17 21:16:27 +00001639
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001640 // Slow case: grovel through the declarations in our chain looking for
1641 // matches.
Richard Smith9e2341d2015-03-23 03:25:59 +00001642 // FIXME: If we have lazy external declarations, this will not find them!
1643 // FIXME: Should we CollectAllContexts and walk them all here?
Douglas Gregor9e0a5b32011-10-15 00:10:27 +00001644 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1645 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1646 if (ND->getDeclName() == Name)
1647 Results.push_back(ND);
1648 }
1649}
1650
Sebastian Redl50c68252010-08-31 00:36:30 +00001651DeclContext *DeclContext::getRedeclContext() {
Chris Lattner17a1bfa2009-03-27 19:19:59 +00001652 DeclContext *Ctx = this;
Sebastian Redlbd595762010-08-31 20:53:31 +00001653 // Skip through transparent contexts.
1654 while (Ctx->isTransparentContext())
Douglas Gregor6ad0ef52009-01-06 23:51:29 +00001655 Ctx = Ctx->getParent();
1656 return Ctx;
1657}
1658
Douglas Gregorf47b9112009-02-25 22:02:03 +00001659DeclContext *DeclContext::getEnclosingNamespaceContext() {
1660 DeclContext *Ctx = this;
1661 // Skip through non-namespace, non-translation-unit contexts.
Sebastian Redl4f08c962010-08-31 00:36:23 +00001662 while (!Ctx->isFileContext())
Douglas Gregorf47b9112009-02-25 22:02:03 +00001663 Ctx = Ctx->getParent();
1664 return Ctx->getPrimaryContext();
1665}
1666
Reid Klecknerd60b82f2014-11-17 23:36:45 +00001667RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1668 // Loop until we find a non-record context.
1669 RecordDecl *OutermostRD = nullptr;
1670 DeclContext *DC = this;
1671 while (DC->isRecord()) {
1672 OutermostRD = cast<RecordDecl>(DC);
1673 DC = DC->getLexicalParent();
1674 }
1675 return OutermostRD;
1676}
1677
Sebastian Redl50c68252010-08-31 00:36:30 +00001678bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1679 // For non-file contexts, this is equivalent to Equals.
1680 if (!isFileContext())
1681 return O->Equals(this);
1682
1683 do {
1684 if (O->Equals(this))
1685 return true;
1686
1687 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1688 if (!NS || !NS->isInline())
1689 break;
1690 O = NS->getParent();
1691 } while (O);
1692
1693 return false;
1694}
1695
Richard Smithf634c902012-03-16 06:12:59 +00001696void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1697 DeclContext *PrimaryDC = this->getPrimaryContext();
1698 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1699 // If the decl is being added outside of its semantic decl context, we
1700 // need to ensure that we eagerly build the lookup information for it.
1701 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
Sean Callanan95e74be2011-10-21 02:57:43 +00001702}
1703
Richard Smithf634c902012-03-16 06:12:59 +00001704void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1705 bool Recoverable) {
1706 assert(this == getPrimaryContext() && "expected a primary DC");
Sean Callanan95e74be2011-10-21 02:57:43 +00001707
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001708 if (!isLookupContext()) {
1709 if (isTransparentContext())
1710 getParent()->getPrimaryContext()
1711 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
Richard Smith05afe5e2012-03-13 03:12:56 +00001712 return;
Vassil Vassilev71eafde2016-04-06 20:56:03 +00001713 }
Richard Smith05afe5e2012-03-13 03:12:56 +00001714
Richard Smithf634c902012-03-16 06:12:59 +00001715 // Skip declarations which should be invisible to name lookup.
1716 if (shouldBeHidden(D))
1717 return;
1718
1719 // If we already have a lookup data structure, perform the insertion into
1720 // it. If we might have externally-stored decls with this name, look them
1721 // up and perform the insertion. If this decl was declared outside its
1722 // semantic context, buildLookup won't add it, so add it now.
1723 //
1724 // FIXME: As a performance hack, don't add such decls into the translation
1725 // unit unless we're in C++, since qualified lookup into the TU is never
1726 // performed.
Richard Smith9e2341d2015-03-23 03:25:59 +00001727 if (LookupPtr || hasExternalVisibleStorage() ||
Richard Smithf634c902012-03-16 06:12:59 +00001728 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1729 (getParentASTContext().getLangOpts().CPlusPlus ||
1730 !isTranslationUnit()))) {
1731 // If we have lazily omitted any decls, they might have the same name as
1732 // the decl which we are adding, so build a full lookup table before adding
1733 // this decl.
1734 buildLookup();
1735 makeDeclVisibleInContextImpl(D, Internal);
1736 } else {
Richard Smith9e2341d2015-03-23 03:25:59 +00001737 HasLazyLocalLexicalLookups = true;
Richard Smithf634c902012-03-16 06:12:59 +00001738 }
1739
1740 // If we are a transparent context or inline namespace, insert into our
1741 // parent context, too. This operation is recursive.
1742 if (isTransparentContext() || isInlineNamespace())
1743 getParent()->getPrimaryContext()->
1744 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1745
1746 Decl *DCAsDecl = cast<Decl>(this);
1747 // Notify that a decl was made visible unless we are a Tag being defined.
1748 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1749 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1750 L->AddedVisibleDecl(this, D);
1751}
1752
1753void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1754 // Find or create the stored declaration map.
Richard Smith9e2341d2015-03-23 03:25:59 +00001755 StoredDeclsMap *Map = LookupPtr;
Richard Smithf634c902012-03-16 06:12:59 +00001756 if (!Map) {
1757 ASTContext *C = &getParentASTContext();
1758 Map = CreateStoredDeclsMap(*C);
Argyrios Kyrtzidise51e5542010-07-04 21:44:25 +00001759 }
1760
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001761 // If there is an external AST source, load any declarations it knows about
1762 // with this declaration's name.
1763 // If the lookup table contains an entry about this name it means that we
1764 // have already checked the external source.
Sean Callanan95e74be2011-10-21 02:57:43 +00001765 if (!Internal)
1766 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1767 if (hasExternalVisibleStorage() &&
Richard Smithf634c902012-03-16 06:12:59 +00001768 Map->find(D->getDeclName()) == Map->end())
Sean Callanan95e74be2011-10-21 02:57:43 +00001769 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00001770
Douglas Gregor91f84212008-12-11 16:49:14 +00001771 // Insert this declaration into the map.
Richard Smithf634c902012-03-16 06:12:59 +00001772 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
Richard Smith4abe0a82013-09-09 07:34:56 +00001773
1774 if (Internal) {
1775 // If this is being added as part of loading an external declaration,
1776 // this may not be the only external declaration with this name.
1777 // In this case, we never try to replace an existing declaration; we'll
1778 // handle that when we finalize the list of declarations for this name.
1779 DeclNameEntries.setHasExternalDecls();
1780 DeclNameEntries.AddSubsequentDecl(D);
1781 return;
1782 }
1783
Richard Smitha3271c12015-02-07 00:45:52 +00001784 if (DeclNameEntries.isNull()) {
Chris Lattnercaae7162009-02-20 01:44:05 +00001785 DeclNameEntries.setOnlyValue(D);
Richard Smithf634c902012-03-16 06:12:59 +00001786 return;
Douglas Gregor91f84212008-12-11 16:49:14 +00001787 }
Chris Lattner24e24d52009-02-20 00:55:03 +00001788
Richard Smithe8292b12015-02-10 03:28:10 +00001789 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
Richard Smithf634c902012-03-16 06:12:59 +00001790 // This declaration has replaced an existing one for which
1791 // declarationReplaces returns true.
1792 return;
1793 }
Mike Stump11289f42009-09-09 15:08:12 +00001794
Richard Smithf634c902012-03-16 06:12:59 +00001795 // Put this declaration into the appropriate slot.
1796 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor91f84212008-12-11 16:49:14 +00001797}
Douglas Gregor889ceb72009-02-03 19:21:40 +00001798
Richard Smith40c78062015-02-21 02:31:57 +00001799UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1800 return cast<UsingDirectiveDecl>(*I);
1801}
1802
Douglas Gregor889ceb72009-02-03 19:21:40 +00001803/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1804/// this context.
Aaron Ballman804a7fb2014-03-17 17:14:12 +00001805DeclContext::udir_range DeclContext::using_directives() const {
Richard Smith05afe5e2012-03-13 03:12:56 +00001806 // FIXME: Use something more efficient than normal lookup for using
1807 // directives. In C++, using directives are looked up more than anything else.
Richard Smithcf4bdde2015-02-21 02:45:19 +00001808 lookup_result Result = lookup(UsingDirectiveDecl::getName());
Richard Smith40c78062015-02-21 02:31:57 +00001809 return udir_range(Result.begin(), Result.end());
Douglas Gregor889ceb72009-02-03 19:21:40 +00001810}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001811
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001812//===----------------------------------------------------------------------===//
1813// Creation and Destruction of StoredDeclsMaps. //
1814//===----------------------------------------------------------------------===//
1815
John McCallc62bb642010-03-24 05:22:00 +00001816StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
Richard Smith9e2341d2015-03-23 03:25:59 +00001817 assert(!LookupPtr && "context already has a decls map");
John McCallc62bb642010-03-24 05:22:00 +00001818 assert(getPrimaryContext() == this &&
1819 "creating decls map on non-primary context");
1820
1821 StoredDeclsMap *M;
1822 bool Dependent = isDependentContext();
1823 if (Dependent)
1824 M = new DependentStoredDeclsMap();
1825 else
1826 M = new StoredDeclsMap();
1827 M->Previous = C.LastSDM;
1828 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
Richard Smith9e2341d2015-03-23 03:25:59 +00001829 LookupPtr = M;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001830 return M;
1831}
1832
1833void ASTContext::ReleaseDeclContextMaps() {
John McCallc62bb642010-03-24 05:22:00 +00001834 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1835 // pointer because the subclass doesn't add anything that needs to
1836 // be deleted.
John McCallc62bb642010-03-24 05:22:00 +00001837 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1838}
1839
1840void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1841 while (Map) {
1842 // Advance the iteration before we invalidate memory.
1843 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1844
1845 if (Dependent)
1846 delete static_cast<DependentStoredDeclsMap*>(Map);
1847 else
1848 delete Map;
1849
1850 Map = Next.getPointer();
1851 Dependent = Next.getInt();
1852 }
1853}
1854
John McCallc62bb642010-03-24 05:22:00 +00001855DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1856 DeclContext *Parent,
1857 const PartialDiagnostic &PDiag) {
1858 assert(Parent->isDependentContext()
1859 && "cannot iterate dependent diagnostics of non-dependent context");
1860 Parent = Parent->getPrimaryContext();
Richard Smith9e2341d2015-03-23 03:25:59 +00001861 if (!Parent->LookupPtr)
John McCallc62bb642010-03-24 05:22:00 +00001862 Parent->CreateStoredDeclsMap(C);
1863
Richard Smith9e2341d2015-03-23 03:25:59 +00001864 DependentStoredDeclsMap *Map =
1865 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
John McCallc62bb642010-03-24 05:22:00 +00001866
Douglas Gregora55530e2010-03-29 23:56:53 +00001867 // Allocate the copy of the PartialDiagnostic via the ASTContext's
Douglas Gregor89336232010-03-29 23:34:08 +00001868 // BumpPtrAllocator, rather than the ASTContext itself.
Craig Topper36250ad2014-05-12 05:36:57 +00001869 PartialDiagnostic::Storage *DiagStorage = nullptr;
Douglas Gregora55530e2010-03-29 23:56:53 +00001870 if (PDiag.hasStorage())
1871 DiagStorage = new (C) PartialDiagnostic::Storage;
1872
1873 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
John McCallc62bb642010-03-24 05:22:00 +00001874
1875 // TODO: Maybe we shouldn't reverse the order during insertion.
1876 DD->NextDiagnostic = Map->FirstDiagnostic;
1877 Map->FirstDiagnostic = DD;
1878
1879 return DD;
Ted Kremenekda4e0d32010-02-11 07:12:28 +00001880}