Bug Summary

File:tools/clang/lib/AST/DeclBase.cpp
Warning:line 92, column 7
Potential leak of memory pointed to by 'VT'

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp

1//===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Decl and DeclContext classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/DeclBase.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclContextInternals.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenMP.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DependentDiagnostic.h"
27#include "clang/AST/ExternalASTSource.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/Type.h"
30#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"
36#include "clang/Basic/TargetInfo.h"
37#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"
45#include "llvm/Support/raw_ostream.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <string>
50#include <tuple>
51#include <utility>
52
53using namespace clang;
54
55//===----------------------------------------------------------------------===//
56// Statistics
57//===----------------------------------------------------------------------===//
58
59#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
60#define ABSTRACT_DECL(DECL)
61#include "clang/AST/DeclNodes.inc"
62
63void Decl::updateOutOfDate(IdentifierInfo &II) const {
64 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
65}
66
67#define DECL(DERIVED, BASE) \
68 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
69 "Alignment sufficient after objects prepended to " #DERIVED);
70#define ABSTRACT_DECL(DECL)
71#include "clang/AST/DeclNodes.inc"
72
73void *Decl::operator new(std::size_t Size, const ASTContext &Context,
74 unsigned ID, std::size_t Extra) {
75 // Allocate an extra 8 bytes worth of storage, which ensures that the
76 // resulting pointer will still be 8-byte aligned.
77 static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
78 "Decl won't be misaligned");
79 void *Start = Context.Allocate(Size + Extra + 8);
80 void *Result = (char*)Start + 8;
81
82 unsigned *PrefixPtr = (unsigned *)Result - 2;
83
84 // Zero out the first 4 bytes; this is used to store the owning module ID.
85 PrefixPtr[0] = 0;
86
87 // Store the global declaration ID in the second 4 bytes.
88 PrefixPtr[1] = ID;
89
90 return Result;
91}
92
93void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94 DeclContext *Parent, std::size_t Extra) {
95 assert(!Parent || &Parent->getParentASTContext() == &Ctx)((!Parent || &Parent->getParentASTContext() == &Ctx
) ? static_cast<void> (0) : __assert_fail ("!Parent || &Parent->getParentASTContext() == &Ctx"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 95, __PRETTY_FUNCTION__))
;
96 // With local visibility enabled, we track the owning module even for local
97 // 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) {
100 // Ensure required alignment of the resulting object by adding extra
101 // padding at the start if required.
102 size_t ExtraAlign =
103 llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
104 char *Buffer = reinterpret_cast<char *>(
105 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106 Buffer += ExtraAlign;
107 auto *ParentModule =
108 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
109 return new (Buffer) Module*(ParentModule) + 1;
110 }
111 return ::operator new(Size + Extra, Ctx);
112}
113
114Module *Decl::getOwningModuleSlow() const {
115 assert(isFromASTFile() && "Not from AST file?")((isFromASTFile() && "Not from AST file?") ? static_cast
<void> (0) : __assert_fail ("isFromASTFile() && \"Not from AST file?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 115, __PRETTY_FUNCTION__))
;
116 return getASTContext().getExternalSource()->getModule(getOwningModuleID());
117}
118
119bool Decl::hasLocalOwningModuleStorage() const {
120 return getASTContext().getLangOpts().trackLocalOwningModule();
121}
122
123const char *Decl::getDeclKindName() const {
124 switch (DeclKind) {
125 default: llvm_unreachable("Declaration not in DeclNodes.inc!")::llvm::llvm_unreachable_internal("Declaration not in DeclNodes.inc!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 125)
;
126#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127#define ABSTRACT_DECL(DECL)
128#include "clang/AST/DeclNodes.inc"
129 }
130}
131
132void Decl::setInvalidDecl(bool Invalid) {
133 InvalidDecl = Invalid;
134 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition())((!isa<TagDecl>(this) || !cast<TagDecl>(this)->
isCompleteDefinition()) ? static_cast<void> (0) : __assert_fail
("!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 134, __PRETTY_FUNCTION__))
;
135 if (!Invalid) {
136 return;
137 }
138
139 if (!isa<ParmVarDecl>(this)) {
140 // 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 }
145
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 }
153}
154
155const char *DeclContext::getDeclKindName() const {
156 switch (DeclKind) {
157 default: llvm_unreachable("Declaration context not in DeclNodes.inc!")::llvm::llvm_unreachable_internal("Declaration context not in DeclNodes.inc!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 157)
;
158#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
159#define ABSTRACT_DECL(DECL)
160#include "clang/AST/DeclNodes.inc"
161 }
162}
163
164bool Decl::StatisticsEnabled = false;
165void Decl::EnableStatistics() {
166 StatisticsEnabled = true;
167}
168
169void Decl::PrintStats() {
170 llvm::errs() << "\n*** Decl Stats:\n";
171
172 int totalDecls = 0;
173#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
174#define ABSTRACT_DECL(DECL)
175#include "clang/AST/DeclNodes.inc"
176 llvm::errs() << " " << totalDecls << " decls total.\n";
177
178 int totalBytes = 0;
179#define DECL(DERIVED, BASE) \
180 if (n##DERIVED##s > 0) { \
181 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
182 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
183 << sizeof(DERIVED##Decl) << " each (" \
184 << n##DERIVED##s * sizeof(DERIVED##Decl) \
185 << " bytes)\n"; \
186 }
187#define ABSTRACT_DECL(DECL)
188#include "clang/AST/DeclNodes.inc"
189
190 llvm::errs() << "Total bytes = " << totalBytes << "\n";
191}
192
193void Decl::add(Kind k) {
194 switch (k) {
195#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
196#define ABSTRACT_DECL(DECL)
197#include "clang/AST/DeclNodes.inc"
198 }
199}
200
201bool Decl::isTemplateParameterPack() const {
202 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203 return TTP->isParameterPack();
204 if (const NonTypeTemplateParmDecl *NTTP
205 = dyn_cast<NonTypeTemplateParmDecl>(this))
206 return NTTP->isParameterPack();
207 if (const TemplateTemplateParmDecl *TTP
208 = dyn_cast<TemplateTemplateParmDecl>(this))
209 return TTP->isParameterPack();
210 return false;
211}
212
213bool Decl::isParameterPack() const {
214 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
215 return Parm->isParameterPack();
216
217 return isTemplateParameterPack();
218}
219
220FunctionDecl *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();
225 return nullptr;
226}
227
228bool Decl::isTemplateDecl() const {
229 return isa<TemplateDecl>(this);
230}
231
232TemplateDecl *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
243const DeclContext *Decl::getParentFunctionOrMethod() const {
244 for (const DeclContext *DC = getDeclContext();
245 DC && !DC->isTranslationUnit() && !DC->isNamespace();
246 DC = DC->getParent())
247 if (DC->isFunctionOrMethod())
248 return DC;
249
250 return nullptr;
251}
252
253//===----------------------------------------------------------------------===//
254// PrettyStackTraceDecl Implementation
255//===----------------------------------------------------------------------===//
256
257void PrettyStackTraceDecl::print(raw_ostream &OS) const {
258 SourceLocation TheLoc = Loc;
259 if (TheLoc.isInvalid() && TheDecl)
260 TheLoc = TheDecl->getLocation();
261
262 if (TheLoc.isValid()) {
263 TheLoc.print(OS, SM);
264 OS << ": ";
265 }
266
267 OS << Message;
268
269 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
270 OS << " '";
271 DN->printQualifiedName(OS);
272 OS << '\'';
273 }
274 OS << '\n';
275}
276
277//===----------------------------------------------------------------------===//
278// Decl Implementation
279//===----------------------------------------------------------------------===//
280
281// Out-of-line virtual method providing a home for Decl.
282Decl::~Decl() = default;
283
284void Decl::setDeclContext(DeclContext *DC) {
285 DeclCtx = DC;
286}
287
288void Decl::setLexicalDeclContext(DeclContext *DC) {
289 if (DC == getLexicalDeclContext())
290 return;
291
292 if (isInSemaDC()) {
293 setDeclContextsImpl(getDeclContext(), DC, getASTContext());
294 } else {
295 getMultipleDC()->LexicalDC = DC;
296 }
297
298 // FIXME: We shouldn't be changing the lexical context of declarations
299 // imported from AST files.
300 if (!isFromASTFile()) {
301 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
302 if (hasOwningModule())
303 setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
304 }
305
306 assert((((getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported
|| getOwningModule()) && "hidden declaration has no owning module"
) ? static_cast<void> (0) : __assert_fail ("(getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported || getOwningModule()) && \"hidden declaration has no owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 309, __PRETTY_FUNCTION__))
307 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||(((getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported
|| getOwningModule()) && "hidden declaration has no owning module"
) ? static_cast<void> (0) : __assert_fail ("(getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported || getOwningModule()) && \"hidden declaration has no owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 309, __PRETTY_FUNCTION__))
308 getOwningModule()) &&(((getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported
|| getOwningModule()) && "hidden declaration has no owning module"
) ? static_cast<void> (0) : __assert_fail ("(getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported || getOwningModule()) && \"hidden declaration has no owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 309, __PRETTY_FUNCTION__))
309 "hidden declaration has no owning module")(((getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported
|| getOwningModule()) && "hidden declaration has no owning module"
) ? static_cast<void> (0) : __assert_fail ("(getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported || getOwningModule()) && \"hidden declaration has no owning module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 309, __PRETTY_FUNCTION__))
;
310}
311
312void 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
324bool Decl::isLexicallyWithinFunctionOrMethod() const {
325 const DeclContext *LDC = getLexicalDeclContext();
326 while (true) {
327 if (LDC->isFunctionOrMethod())
328 return true;
329 if (!isa<TagDecl>(LDC))
330 return false;
331 LDC = LDC->getLexicalParent();
332 }
333 return false;
334}
335
336bool Decl::isInAnonymousNamespace() const {
337 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
338 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
339 if (ND->isAnonymousNamespace())
340 return true;
341 }
342
343 return false;
344}
345
346bool Decl::isInStdNamespace() const {
347 return getDeclContext()->isStdNamespace();
348}
349
350TranslationUnitDecl *Decl::getTranslationUnitDecl() {
351 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this))
352 return TUD;
353
354 DeclContext *DC = getDeclContext();
355 assert(DC && "This decl is not contained in a translation unit!")((DC && "This decl is not contained in a translation unit!"
) ? static_cast<void> (0) : __assert_fail ("DC && \"This decl is not contained in a translation unit!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 355, __PRETTY_FUNCTION__))
;
356
357 while (!DC->isTranslationUnit()) {
358 DC = DC->getParent();
359 assert(DC && "This decl is not contained in a translation unit!")((DC && "This decl is not contained in a translation unit!"
) ? static_cast<void> (0) : __assert_fail ("DC && \"This decl is not contained in a translation unit!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 359, __PRETTY_FUNCTION__))
;
360 }
361
362 return cast<TranslationUnitDecl>(DC);
363}
364
365ASTContext &Decl::getASTContext() const {
366 return getTranslationUnitDecl()->getASTContext();
367}
368
369ASTMutationListener *Decl::getASTMutationListener() const {
370 return getASTContext().getASTMutationListener();
371}
372
373unsigned 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
386bool Decl::isUsed(bool CheckUsedAttr) const {
387 const Decl *CanonD = getCanonicalDecl();
388 if (CanonD->Used)
389 return true;
390
391 // 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;
399}
400
401void Decl::markUsed(ASTContext &C) {
402 if (isUsed(false))
403 return;
404
405 if (C.getASTMutationListener())
406 C.getASTMutationListener()->DeclarationMarkedUsed(this);
407
408 setIsUsed();
409}
410
411bool Decl::isReferenced() const {
412 if (Referenced)
413 return true;
414
415 // Check redeclarations.
416 for (auto I : redecls())
417 if (I->Referenced)
418 return true;
419
420 return false;
421}
422
423bool 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
439ExternalSourceSymbolAttr *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
460bool 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
472static StringRef getRealizedPlatform(const AvailabilityAttr *A,
473 const ASTContext &Context) {
474 // 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
485/// \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,
496 std::string *Message,
497 VersionTuple EnclosingVersion) {
498 if (EnclosingVersion.empty())
499 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
500
501 if (EnclosingVersion.empty())
502 return AR_Available;
503
504 StringRef ActualPlatform = A->getPlatform()->getName();
505 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
506
507 // Match the platform name.
508 if (getRealizedPlatform(A, Context) != TargetPlatform)
509 return AR_Available;
510
511 StringRef PrettyPlatformName
512 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
513
514 if (PrettyPlatformName.empty())
515 PrettyPlatformName = ActualPlatform;
516
517 std::string HintMessage;
518 if (!A->getMessage().empty()) {
519 HintMessage = " - ";
520 HintMessage += A->getMessage();
521 }
522
523 // 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);
528 Out << "not available on " << PrettyPlatformName
529 << HintMessage;
530 }
531
532 return AR_Unavailable;
533 }
534
535 // Make sure that this declaration has already been introduced.
536 if (!A->getIntroduced().empty() &&
537 EnclosingVersion < A->getIntroduced()) {
538 if (Message) {
539 Message->clear();
540 llvm::raw_string_ostream Out(*Message);
541 VersionTuple VTI(A->getIntroduced());
542 VTI.UseDotAsSeparator();
543 Out << "introduced in " << PrettyPlatformName << ' '
544 << VTI << HintMessage;
545 }
546
547 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
548 }
549
550 // Make sure that this declaration hasn't been obsoleted.
551 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
552 if (Message) {
553 Message->clear();
554 llvm::raw_string_ostream Out(*Message);
555 VersionTuple VTO(A->getObsoleted());
556 VTO.UseDotAsSeparator();
557 Out << "obsoleted in " << PrettyPlatformName << ' '
558 << VTO << HintMessage;
559 }
560
561 return AR_Unavailable;
562 }
563
564 // Make sure that this declaration hasn't been deprecated.
565 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
566 if (Message) {
567 Message->clear();
568 llvm::raw_string_ostream Out(*Message);
569 VersionTuple VTD(A->getDeprecated());
570 VTD.UseDotAsSeparator();
571 Out << "first deprecated in " << PrettyPlatformName << ' '
572 << VTD << HintMessage;
573 }
574
575 return AR_Deprecated;
576 }
577
578 return AR_Available;
579}
580
581AvailabilityResult Decl::getAvailability(std::string *Message,
582 VersionTuple EnclosingVersion) const {
583 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
584 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
585
586 AvailabilityResult Result = AR_Available;
587 std::string ResultMessage;
588
589 for (const auto *A : attrs()) {
590 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
591 if (Result >= AR_Deprecated)
592 continue;
593
594 if (Message)
595 ResultMessage = Deprecated->getMessage();
596
597 Result = AR_Deprecated;
598 continue;
599 }
600
601 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
602 if (Message)
603 *Message = Unavailable->getMessage();
604 return AR_Unavailable;
605 }
606
607 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
608 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
609 Message, EnclosingVersion);
610
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
628VersionTuple 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
642bool Decl::canBeWeakImported(bool &IsDefinition) const {
643 IsDefinition = false;
644
645 // Variables, if they aren't definitions.
646 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
647 if (Var->isThisDeclarationADefinition()) {
648 IsDefinition = true;
649 return false;
650 }
651 return true;
652
653 // Functions, if they aren't definitions.
654 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) {
655 if (FD->hasBody()) {
656 IsDefinition = true;
657 return false;
658 }
659 return true;
660
661 // Objective-C classes, if this is the non-fragile runtime.
662 } else if (isa<ObjCInterfaceDecl>(this) &&
663 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
664 return true;
665
666 // Nothing else.
667 } else {
668 return false;
669 }
670}
671
672bool Decl::isWeakImported() const {
673 bool IsDefinition;
674 if (!canBeWeakImported(IsDefinition))
675 return false;
676
677 for (const auto *A : attrs()) {
678 if (isa<WeakImportAttr>(A))
679 return true;
680
681 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
682 if (CheckAvailability(getASTContext(), Availability, nullptr,
683 VersionTuple()) == AR_NotYetIntroduced)
684 return true;
685 }
686 }
687
688 return false;
689}
690
691unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
692 switch (DeclKind) {
693 case Function:
694 case CXXDeductionGuide:
695 case CXXMethod:
696 case CXXConstructor:
697 case ConstructorUsingShadow:
698 case CXXDestructor:
699 case CXXConversion:
700 case EnumConstant:
701 case Var:
702 case ImplicitParam:
703 case ParmVar:
704 case ObjCMethod:
705 case ObjCProperty:
706 case MSProperty:
707 return IDNS_Ordinary;
708 case Label:
709 return IDNS_Label;
710 case IndirectField:
711 return IDNS_Ordinary | IDNS_Member;
712
713 case Binding:
714 case NonTypeTemplateParm:
715 case VarTemplate:
716 // These (C++-only) declarations are found by redeclaration lookup for
717 // tag types, so we include them in the tag namespace.
718 return IDNS_Ordinary | IDNS_Tag;
719
720 case ObjCCompatibleAlias:
721 case ObjCInterface:
722 return IDNS_Ordinary | IDNS_Type;
723
724 case Typedef:
725 case TypeAlias:
726 case TemplateTypeParm:
727 case ObjCTypeParam:
728 return IDNS_Ordinary | IDNS_Type;
729
730 case UnresolvedUsingTypename:
731 return IDNS_Ordinary | IDNS_Type | IDNS_Using;
732
733 case UsingShadow:
734 return 0; // we'll actually overwrite this later
735
736 case UnresolvedUsingValue:
737 return IDNS_Ordinary | IDNS_Using;
738
739 case Using:
740 case UsingPack:
741 return IDNS_Using;
742
743 case ObjCProtocol:
744 return IDNS_ObjCProtocol;
745
746 case Field:
747 case ObjCAtDefsField:
748 case ObjCIvar:
749 return IDNS_Member;
750
751 case Record:
752 case CXXRecord:
753 case Enum:
754 return IDNS_Tag | IDNS_Type;
755
756 case Namespace:
757 case NamespaceAlias:
758 return IDNS_Namespace;
759
760 case FunctionTemplate:
761 return IDNS_Ordinary;
762
763 case ClassTemplate:
764 case TemplateTemplateParm:
765 case TypeAliasTemplate:
766 return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
767
768 case OMPDeclareReduction:
769 return IDNS_OMPReduction;
770
771 // Never have names.
772 case Friend:
773 case FriendTemplate:
774 case AccessSpec:
775 case LinkageSpec:
776 case Export:
777 case FileScopeAsm:
778 case StaticAssert:
779 case ObjCPropertyImpl:
780 case PragmaComment:
781 case PragmaDetectMismatch:
782 case Block:
783 case Captured:
784 case TranslationUnit:
785 case ExternCContext:
786 case Decomposition:
787
788 case UsingDirective:
789 case BuiltinTemplate:
790 case ClassTemplateSpecialization:
791 case ClassTemplatePartialSpecialization:
792 case ClassScopeFunctionSpecialization:
793 case VarTemplateSpecialization:
794 case VarTemplatePartialSpecialization:
795 case ObjCImplementation:
796 case ObjCCategory:
797 case ObjCCategoryImpl:
798 case Import:
799 case OMPThreadPrivate:
800 case OMPCapturedExpr:
801 case Empty:
802 // Never looked up by name.
803 return 0;
804 }
805
806 llvm_unreachable("Invalid DeclKind!")::llvm::llvm_unreachable_internal("Invalid DeclKind!", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 806)
;
807}
808
809void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
810 assert(!HasAttrs && "Decl already contains attrs.")((!HasAttrs && "Decl already contains attrs.") ? static_cast
<void> (0) : __assert_fail ("!HasAttrs && \"Decl already contains attrs.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 810, __PRETTY_FUNCTION__))
;
811
812 AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
813 assert(AttrBlank.empty() && "HasAttrs was wrong?")((AttrBlank.empty() && "HasAttrs was wrong?") ? static_cast
<void> (0) : __assert_fail ("AttrBlank.empty() && \"HasAttrs was wrong?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 813, __PRETTY_FUNCTION__))
;
814
815 AttrBlank = attrs;
816 HasAttrs = true;
817}
818
819void Decl::dropAttrs() {
820 if (!HasAttrs) return;
821
822 HasAttrs = false;
823 getASTContext().eraseDeclAttrs(this);
824}
825
826const AttrVec &Decl::getAttrs() const {
827 assert(HasAttrs && "No attrs to get!")((HasAttrs && "No attrs to get!") ? static_cast<void
> (0) : __assert_fail ("HasAttrs && \"No attrs to get!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 827, __PRETTY_FUNCTION__))
;
828 return getASTContext().getDeclAttrs(this);
829}
830
831Decl *Decl::castFromDeclContext (const DeclContext *D) {
832 Decl::Kind DK = D->getDeclKind();
833 switch(DK) {
834#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"
840 default:
841#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"
846 llvm_unreachable("a decl that inherits DeclContext isn't handled")::llvm::llvm_unreachable_internal("a decl that inherits DeclContext isn't handled"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 846)
;
847 }
848}
849
850DeclContext *Decl::castToDeclContext(const Decl *D) {
851 Decl::Kind DK = D->getKind();
852 switch(DK) {
853#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"
859 default:
860#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"
865 llvm_unreachable("a decl that inherits DeclContext isn't handled")::llvm::llvm_unreachable_internal("a decl that inherits DeclContext isn't handled"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 865)
;
866 }
867}
868
869SourceLocation Decl::getBodyRBrace() const {
870 // 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
879 if (Stmt *Body = getBody())
880 return Body->getSourceRange().getEnd();
881
882 return SourceLocation();
883}
884
885bool Decl::AccessDeclContextSanity() const {
886#ifndef NDEBUG
887 // 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)
890 // 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.
894 if (isa<TranslationUnitDecl>(this) ||
895 isa<TemplateTypeParmDecl>(this) ||
896 isa<NonTypeTemplateParmDecl>(this) ||
897 !isa<CXXRecordDecl>(getDeclContext()) ||
898 isInvalidDecl() ||
899 isa<StaticAssertDecl>(this) ||
900 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
901 // as DeclContext (?).
902 isa<ParmVarDecl>(this) ||
903 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
904 // AS_none as access specifier.
905 isa<CXXRecordDecl>(this) ||
906 isa<ClassScopeFunctionSpecializationDecl>(this))
907 return true;
908
909 assert(Access != AS_none &&((Access != AS_none && "Access specifier is AS_none inside a record decl"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Access specifier is AS_none inside a record decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 910, __PRETTY_FUNCTION__))
910 "Access specifier is AS_none inside a record decl")((Access != AS_none && "Access specifier is AS_none inside a record decl"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Access specifier is AS_none inside a record decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 910, __PRETTY_FUNCTION__))
;
911#endif
912 return true;
913}
914
915static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
916static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
917
918const 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
925 return nullptr;
926
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
935/// 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);
940 if (MD->getOverloadedOperator() == OO_Call &&
941 MD->getParent()->isLambda())
942 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 {
953 return nullptr;
954 }
955}
956
957Decl *Decl::getNonClosureContext() {
958 return ::getNonClosureContext(this);
959}
960
961Decl *DeclContext::getNonClosureAncestor() {
962 return ::getNonClosureContext(this);
963}
964
965//===----------------------------------------------------------------------===//
966// DeclContext Implementation
967//===----------------------------------------------------------------------===//
968
969bool DeclContext::classof(const Decl *D) {
970 switch (D->getKind()) {
971#define DECL(NAME, BASE)
972#define DECL_CONTEXT(NAME) case Decl::NAME:
973#define DECL_CONTEXT_BASE(NAME)
974#include "clang/AST/DeclNodes.inc"
975 return true;
976 default:
977#define DECL(NAME, BASE)
978#define DECL_CONTEXT_BASE(NAME) \
979 if (D->getKind() >= Decl::first##NAME && \
980 D->getKind() <= Decl::last##NAME) \
981 return true;
982#include "clang/AST/DeclNodes.inc"
983 return false;
984 }
985}
986
987DeclContext::~DeclContext() = default;
988
989/// \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))
998 if (getParent()->getRedeclContext()->isFileContext() &&
999 getLexicalParent()->getRedeclContext()->isRecord())
1000 return getLexicalParent();
1001
1002 return getParent();
1003}
1004
1005bool DeclContext::isInlineNamespace() const {
1006 return isNamespace() &&
1007 cast<NamespaceDecl>(this)->isInline();
1008}
1009
1010bool 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
1026bool DeclContext::isDependentContext() const {
1027 if (isFileContext())
1028 return false;
1029
1030 if (isa<ClassTemplatePartialSpecializationDecl>(this))
1031 return true;
1032
1033 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) {
1034 if (Record->getDescribedClassTemplate())
1035 return true;
1036
1037 if (Record->isDependentLambda())
1038 return true;
1039 }
1040
1041 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
1042 if (Function->getDescribedFunctionTemplate())
1043 return true;
1044
1045 // Friend function declarations are dependent if their *lexical*
1046 // context is dependent.
1047 if (cast<Decl>(this)->getFriendObjectKind())
1048 return getLexicalParent()->isDependentContext();
1049 }
1050
1051 // 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
1055 return getParent() && getParent()->isDependentContext();
1056}
1057
1058bool DeclContext::isTransparentContext() const {
1059 if (DeclKind == Decl::Enum)
1060 return !cast<EnumDecl>(this)->isScoped();
1061 else if (DeclKind == Decl::LinkageSpec || DeclKind == Decl::Export)
1062 return true;
1063
1064 return false;
1065}
1066
1067static 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;
1072 DC = DC->getLexicalParent();
1073 }
1074 return false;
1075}
1076
1077bool DeclContext::isExternCContext() const {
1078 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1079}
1080
1081const LinkageSpecDecl *DeclContext::getExternCContext() const {
1082 const DeclContext *DC = this;
1083 while (DC->getDeclKind() != Decl::TranslationUnit) {
1084 if (DC->getDeclKind() == Decl::LinkageSpec &&
1085 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1086 return cast<LinkageSpecDecl>(DC);
1087 DC = DC->getLexicalParent();
1088 }
1089 return nullptr;
1090}
1091
1092bool DeclContext::isExternCXXContext() const {
1093 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1094}
1095
1096bool DeclContext::Encloses(const DeclContext *DC) const {
1097 if (getPrimaryContext() != this)
1098 return getPrimaryContext()->Encloses(DC);
1099
1100 for (; DC; DC = DC->getParent())
1101 if (DC->getPrimaryContext() == this)
1102 return true;
1103 return false;
1104}
1105
1106DeclContext *DeclContext::getPrimaryContext() {
1107 switch (DeclKind) {
1108 case Decl::TranslationUnit:
1109 case Decl::ExternCContext:
1110 case Decl::LinkageSpec:
1111 case Decl::Export:
1112 case Decl::Block:
1113 case Decl::Captured:
1114 case Decl::OMPDeclareReduction:
1115 // 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
1122 case Decl::ObjCMethod:
1123 return this;
1124
1125 case Decl::ObjCInterface:
1126 if (ObjCInterfaceDecl *Def = cast<ObjCInterfaceDecl>(this)->getDefinition())
1127 return Def;
1128 return this;
1129
1130 case Decl::ObjCProtocol:
1131 if (ObjCProtocolDecl *Def = cast<ObjCProtocolDecl>(this)->getDefinition())
1132 return Def;
1133 return this;
1134
1135 case Decl::ObjCCategory:
1136 return this;
1137
1138 case Decl::ObjCImplementation:
1139 case Decl::ObjCCategoryImpl:
1140 return this;
1141
1142 default:
1143 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) {
1144 // If this is a tag type that has a definition or is currently
1145 // being defined, that definition is our primary context.
1146 TagDecl *Tag = cast<TagDecl>(this);
1147
1148 if (TagDecl *Def = Tag->getDefinition())
1149 return Def;
1150
1151 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()))((isa<InjectedClassNameType>(Tag->getTypeForDecl()))
? static_cast<void> (0) : __assert_fail ("isa<InjectedClassNameType>(Tag->getTypeForDecl())"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1157, __PRETTY_FUNCTION__))
;
1158 }
1159
1160 return Tag;
1161 }
1162
1163 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&((DeclKind >= Decl::firstFunction && DeclKind <=
Decl::lastFunction && "Unknown DeclContext kind") ? static_cast
<void> (0) : __assert_fail ("DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && \"Unknown DeclContext kind\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1164, __PRETTY_FUNCTION__))
1164 "Unknown DeclContext kind")((DeclKind >= Decl::firstFunction && DeclKind <=
Decl::lastFunction && "Unknown DeclContext kind") ? static_cast
<void> (0) : __assert_fail ("DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && \"Unknown DeclContext kind\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1164, __PRETTY_FUNCTION__))
;
1165 return this;
1166 }
1167}
1168
1169void
1170DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts){
1171 Contexts.clear();
1172
1173 if (DeclKind != Decl::Namespace) {
1174 Contexts.push_back(this);
1175 return;
1176 }
1177
1178 NamespaceDecl *Self = static_cast<NamespaceDecl *>(this);
1179 for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1180 N = N->getPreviousDecl())
1181 Contexts.push_back(N);
1182
1183 std::reverse(Contexts.begin(), Contexts.end());
1184}
1185
1186std::pair<Decl *, Decl *>
1187DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
1188 bool FieldsAlreadyLoaded) {
1189 // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1190 Decl *FirstNewDecl = nullptr;
1191 Decl *PrevDecl = nullptr;
1192 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1193 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I]))
1194 continue;
1195
1196 Decl *D = Decls[I];
1197 if (PrevDecl)
1198 PrevDecl->NextInContextAndBits.setPointer(D);
1199 else
1200 FirstNewDecl = D;
1201
1202 PrevDecl = D;
1203 }
1204
1205 return std::make_pair(FirstNewDecl, PrevDecl);
1206}
1207
1208/// \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.
1211void DeclContext::reconcileExternalVisibleStorage() const {
1212 assert(NeedToReconcileExternalVisibleStorage && LookupPtr)((NeedToReconcileExternalVisibleStorage && LookupPtr)
? static_cast<void> (0) : __assert_fail ("NeedToReconcileExternalVisibleStorage && LookupPtr"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1212, __PRETTY_FUNCTION__))
;
1213 NeedToReconcileExternalVisibleStorage = false;
1214
1215 for (auto &Lookup : *LookupPtr)
1216 Lookup.second.setHasExternalDecls();
6
Calling 'StoredDeclsList::setHasExternalDecls'
1217}
1218
1219/// \brief Load the declarations within this lexical storage from an
1220/// external source.
1221/// \return \c true if any declarations were added.
1222bool
1223DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1224 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1225 assert(hasExternalLexicalStorage() && Source && "No external storage?")((hasExternalLexicalStorage() && Source && "No external storage?"
) ? static_cast<void> (0) : __assert_fail ("hasExternalLexicalStorage() && Source && \"No external storage?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1225, __PRETTY_FUNCTION__))
;
1226
1227 // Notify that we have a DeclContext that is initializing.
1228 ExternalASTSource::Deserializing ADeclContext(Source);
1229
1230 // Load the external declarations, if any.
1231 SmallVector<Decl*, 64> Decls;
1232 ExternalLexicalStorage = false;
1233 Source->FindExternalLexicalDecls(this, Decls);
1234
1235 if (Decls.empty())
1236 return false;
1237
1238 // 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
1244 // Splice the newly-read declarations into the beginning of the list
1245 // of declarations.
1246 Decl *ExternalFirst, *ExternalLast;
1247 std::tie(ExternalFirst, ExternalLast) =
1248 BuildDeclChain(Decls, FieldsAlreadyLoaded);
1249 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1250 FirstDecl = ExternalFirst;
1251 if (!LastDecl)
1252 LastDecl = ExternalLast;
1253 return true;
1254}
1255
1256DeclContext::lookup_result
1257ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1258 DeclarationName Name) {
1259 ASTContext &Context = DC->getParentASTContext();
1260 StoredDeclsMap *Map;
1261 if (!(Map = DC->LookupPtr))
1262 Map = DC->CreateStoredDeclsMap(Context);
1263 if (DC->NeedToReconcileExternalVisibleStorage)
1264 DC->reconcileExternalVisibleStorage();
1265
1266 (*Map)[Name].removeExternalDecls();
1267
1268 return DeclContext::lookup_result();
1269}
1270
1271DeclContext::lookup_result
1272ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1273 DeclarationName Name,
1274 ArrayRef<NamedDecl*> Decls) {
1275 ASTContext &Context = DC->getParentASTContext();
1276 StoredDeclsMap *Map;
1277 if (!(Map = DC->LookupPtr))
1
Assuming 'Map' is not null
2
Taking false branch
1278 Map = DC->CreateStoredDeclsMap(Context);
1279 if (DC->NeedToReconcileExternalVisibleStorage)
3
Assuming the condition is true
4
Taking true branch
1280 DC->reconcileExternalVisibleStorage();
5
Calling 'DeclContext::reconcileExternalVisibleStorage'
1281
1282 StoredDeclsList &List = (*Map)[Name];
1283
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)
1294 if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1295 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 }
1315 }
1316
1317 return List.getLookupResult();
1318}
1319
1320DeclContext::decl_iterator DeclContext::decls_begin() const {
1321 if (hasExternalLexicalStorage())
1322 LoadLexicalDeclsFromExternalStorage();
1323 return decl_iterator(FirstDecl);
1324}
1325
1326bool DeclContext::decls_empty() const {
1327 if (hasExternalLexicalStorage())
1328 LoadLexicalDeclsFromExternalStorage();
1329
1330 return !FirstDecl;
1331}
1332
1333bool DeclContext::containsDecl(Decl *D) const {
1334 return (D->getLexicalDeclContext() == this &&
1335 (D->NextInContextAndBits.getPointer() || D == LastDecl));
1336}
1337
1338void DeclContext::removeDecl(Decl *D) {
1339 assert(D->getLexicalDeclContext() == this &&((D->getLexicalDeclContext() == this && "decl being removed from non-lexical context"
) ? static_cast<void> (0) : __assert_fail ("D->getLexicalDeclContext() == this && \"decl being removed from non-lexical context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1340, __PRETTY_FUNCTION__))
1340 "decl being removed from non-lexical context")((D->getLexicalDeclContext() == this && "decl being removed from non-lexical context"
) ? static_cast<void> (0) : __assert_fail ("D->getLexicalDeclContext() == this && \"decl being removed from non-lexical context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1340, __PRETTY_FUNCTION__))
;
1341 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&(((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
"decl is not in decls list") ? static_cast<void> (0) :
__assert_fail ("(D->NextInContextAndBits.getPointer() || D == LastDecl) && \"decl is not in decls list\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1342, __PRETTY_FUNCTION__))
1342 "decl is not in decls list")(((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
"decl is not in decls list") ? static_cast<void> (0) :
__assert_fail ("(D->NextInContextAndBits.getPointer() || D == LastDecl) && \"decl is not in decls list\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1342, __PRETTY_FUNCTION__))
;
1343
1344 // Remove D from the decl chain. This is O(n) but hopefully rare.
1345 if (D == FirstDecl) {
1346 if (D == LastDecl)
1347 FirstDecl = LastDecl = nullptr;
1348 else
1349 FirstDecl = D->NextInContextAndBits.getPointer();
1350 } else {
1351 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1352 assert(I && "decl not found in linked list")((I && "decl not found in linked list") ? static_cast
<void> (0) : __assert_fail ("I && \"decl not found in linked list\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1352, __PRETTY_FUNCTION__))
;
1353 if (I->NextInContextAndBits.getPointer() == D) {
1354 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1355 if (D == LastDecl) LastDecl = I;
1356 break;
1357 }
1358 }
1359 }
1360
1361 // Mark that D is no longer in the decl chain.
1362 D->NextInContextAndBits.setPointer(nullptr);
1363
1364 // Remove D from the lookup table if necessary.
1365 if (isa<NamedDecl>(D)) {
1366 NamedDecl *ND = cast<NamedDecl>(D);
1367
1368 // Remove only decls that have a name
1369 if (!ND->getDeclName()) return;
1370
1371 auto *DC = D->getDeclContext();
1372 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")((Pos != Map->end() && "no lookup entry for decl")
? static_cast<void> (0) : __assert_fail ("Pos != Map->end() && \"no lookup entry for decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1376, __PRETTY_FUNCTION__))
;
1377 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND)
1378 Pos->second.remove(ND);
1379 }
1380 } while (DC->isTransparentContext() && (DC = DC->getParent()));
1381 }
1382}
1383
1384void DeclContext::addHiddenDecl(Decl *D) {
1385 assert(D->getLexicalDeclContext() == this &&((D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context"
) ? static_cast<void> (0) : __assert_fail ("D->getLexicalDeclContext() == this && \"Decl inserted into wrong lexical context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1386, __PRETTY_FUNCTION__))
1386 "Decl inserted into wrong lexical context")((D->getLexicalDeclContext() == this && "Decl inserted into wrong lexical context"
) ? static_cast<void> (0) : __assert_fail ("D->getLexicalDeclContext() == this && \"Decl inserted into wrong lexical context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1386, __PRETTY_FUNCTION__))
;
1387 assert(!D->getNextDeclInContext() && D != LastDecl &&((!D->getNextDeclInContext() && D != LastDecl &&
"Decl already inserted into a DeclContext") ? static_cast<
void> (0) : __assert_fail ("!D->getNextDeclInContext() && D != LastDecl && \"Decl already inserted into a DeclContext\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1388, __PRETTY_FUNCTION__))
1388 "Decl already inserted into a DeclContext")((!D->getNextDeclInContext() && D != LastDecl &&
"Decl already inserted into a DeclContext") ? static_cast<
void> (0) : __assert_fail ("!D->getNextDeclInContext() && D != LastDecl && \"Decl already inserted into a DeclContext\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1388, __PRETTY_FUNCTION__))
;
1389
1390 if (FirstDecl) {
1391 LastDecl->NextInContextAndBits.setPointer(D);
1392 LastDecl = D;
1393 } else {
1394 FirstDecl = LastDecl = D;
1395 }
1396
1397 // Notify a C++ record declaration that we've added a member, so it can
1398 // update its class-specific state.
1399 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this))
1400 Record->addedMember(D);
1401
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 }
1408}
1409
1410void DeclContext::addDecl(Decl *D) {
1411 addHiddenDecl(D);
1412
1413 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1414 ND->getDeclContext()->getPrimaryContext()->
1415 makeDeclVisibleInContextWithFlags(ND, false, true);
1416}
1417
1418void DeclContext::addDeclInternal(Decl *D) {
1419 addHiddenDecl(D);
1420
1421 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1422 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.
1455///
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.
1459StoredDeclsMap *DeclContext::buildLookup() {
1460 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC")((this == getPrimaryContext() && "buildLookup called on non-primary DC"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"buildLookup called on non-primary DC\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1460, __PRETTY_FUNCTION__))
;
1461
1462 if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1463 return LookupPtr;
1464
1465 SmallVector<DeclContext *, 2> Contexts;
1466 collectAllContexts(Contexts);
1467
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());
1482
1483 // We no longer have any lazy decls.
1484 HasLazyLocalLexicalLookups = false;
1485 return LookupPtr;
1486}
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.
1492void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1493 for (Decl *D : DCtx->noload_decls()) {
1494 // 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.
1497 //
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.
1502 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1503 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1504 (!ND->isFromASTFile() ||
1505 (isTranslationUnit() &&
1506 !getParentASTContext().getLangOpts().CPlusPlus)))
1507 makeDeclVisibleInContextImpl(ND, Internal);
1508
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())
1514 buildLookupImpl(InnerCtx, Internal);
1515 }
1516}
1517
1518NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1519
1520DeclContext::lookup_result
1521DeclContext::lookup(DeclarationName Name) const {
1522 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&((DeclKind != Decl::LinkageSpec && DeclKind != Decl::
Export && "should not perform lookups into transparent contexts"
) ? static_cast<void> (0) : __assert_fail ("DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export && \"should not perform lookups into transparent contexts\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1523, __PRETTY_FUNCTION__))
1523 "should not perform lookups into transparent contexts")((DeclKind != Decl::LinkageSpec && DeclKind != Decl::
Export && "should not perform lookups into transparent contexts"
) ? static_cast<void> (0) : __assert_fail ("DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export && \"should not perform lookups into transparent contexts\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1523, __PRETTY_FUNCTION__))
;
1524
1525 const DeclContext *PrimaryContext = getPrimaryContext();
1526 if (PrimaryContext != this)
1527 return PrimaryContext->lookup(Name);
1528
1529 // 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();
1535
1536 if (hasExternalVisibleStorage()) {
1537 assert(Source && "external visible storage but no external source?")((Source && "external visible storage but no external source?"
) ? static_cast<void> (0) : __assert_fail ("Source && \"external visible storage but no external source?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1537, __PRETTY_FUNCTION__))
;
1538
1539 if (NeedToReconcileExternalVisibleStorage)
1540 reconcileExternalVisibleStorage();
1541
1542 StoredDeclsMap *Map = LookupPtr;
1543
1544 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1545 // FIXME: Make buildLookup const?
1546 Map = const_cast<DeclContext*>(this)->buildLookup();
1547
1548 if (!Map)
1549 Map = CreateStoredDeclsMap(getParentASTContext());
1550
1551 // If we have a lookup result with no external decls, we are done.
1552 std::pair<StoredDeclsMap::iterator, bool> R =
1553 Map->insert(std::make_pair(Name, StoredDeclsList()));
1554 if (!R.second && !R.first->second.hasExternalDecls())
1555 return R.first->second.getLookupResult();
1556
1557 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1558 if (StoredDeclsMap *Map = LookupPtr) {
1559 StoredDeclsMap::iterator I = Map->find(Name);
1560 if (I != Map->end())
1561 return I->second.getLookupResult();
1562 }
1563 }
1564
1565 return lookup_result();
1566 }
1567
1568 StoredDeclsMap *Map = LookupPtr;
1569 if (HasLazyLocalLexicalLookups || HasLazyExternalLexicalLookups)
1570 Map = const_cast<DeclContext*>(this)->buildLookup();
1571
1572 if (!Map)
1573 return lookup_result();
1574
1575 StoredDeclsMap::iterator I = Map->find(Name);
1576 if (I == Map->end())
1577 return lookup_result();
1578
1579 return I->second.getLookupResult();
1580}
1581
1582DeclContext::lookup_result
1583DeclContext::noload_lookup(DeclarationName Name) {
1584 assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&((DeclKind != Decl::LinkageSpec && DeclKind != Decl::
Export && "should not perform lookups into transparent contexts"
) ? static_cast<void> (0) : __assert_fail ("DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export && \"should not perform lookups into transparent contexts\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1585, __PRETTY_FUNCTION__))
1585 "should not perform lookups into transparent contexts")((DeclKind != Decl::LinkageSpec && DeclKind != Decl::
Export && "should not perform lookups into transparent contexts"
) ? static_cast<void> (0) : __assert_fail ("DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export && \"should not perform lookups into transparent contexts\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1585, __PRETTY_FUNCTION__))
;
1586
1587 DeclContext *PrimaryContext = getPrimaryContext();
1588 if (PrimaryContext != this)
1589 return PrimaryContext->noload_lookup(Name);
1590
1591 // If we have any lazy lexical declarations not in our lookup map, add them
1592 // now. Don't import any external declarations, not even if we know we have
1593 // some missing from the external visible lookups.
1594 if (HasLazyLocalLexicalLookups) {
1595 SmallVector<DeclContext *, 2> Contexts;
1596 collectAllContexts(Contexts);
1597 for (unsigned I = 0, N = Contexts.size(); I != N; ++I)
1598 buildLookupImpl(Contexts[I], hasExternalVisibleStorage());
1599 HasLazyLocalLexicalLookups = false;
1600 }
1601
1602 StoredDeclsMap *Map = LookupPtr;
1603 if (!Map)
1604 return lookup_result();
1605
1606 StoredDeclsMap::iterator I = Map->find(Name);
1607 return I != Map->end() ? I->second.getLookupResult()
1608 : lookup_result();
1609}
1610
1611void DeclContext::localUncachedLookup(DeclarationName Name,
1612 SmallVectorImpl<NamedDecl *> &Results) {
1613 Results.clear();
1614
1615 // If there's no external storage, just perform a normal lookup and copy
1616 // the results.
1617 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1618 lookup_result LookupResults = lookup(Name);
1619 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1620 return;
1621 }
1622
1623 // If we have a lookup table, check there first. Maybe we'll get lucky.
1624 // FIXME: Should we be checking these flags on the primary context?
1625 if (Name && !HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups) {
1626 if (StoredDeclsMap *Map = LookupPtr) {
1627 StoredDeclsMap::iterator Pos = Map->find(Name);
1628 if (Pos != Map->end()) {
1629 Results.insert(Results.end(),
1630 Pos->second.getLookupResult().begin(),
1631 Pos->second.getLookupResult().end());
1632 return;
1633 }
1634 }
1635 }
1636
1637 // Slow case: grovel through the declarations in our chain looking for
1638 // matches.
1639 // FIXME: If we have lazy external declarations, this will not find them!
1640 // FIXME: Should we CollectAllContexts and walk them all here?
1641 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1642 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1643 if (ND->getDeclName() == Name)
1644 Results.push_back(ND);
1645 }
1646}
1647
1648DeclContext *DeclContext::getRedeclContext() {
1649 DeclContext *Ctx = this;
1650 // Skip through transparent contexts.
1651 while (Ctx->isTransparentContext())
1652 Ctx = Ctx->getParent();
1653 return Ctx;
1654}
1655
1656DeclContext *DeclContext::getEnclosingNamespaceContext() {
1657 DeclContext *Ctx = this;
1658 // Skip through non-namespace, non-translation-unit contexts.
1659 while (!Ctx->isFileContext())
1660 Ctx = Ctx->getParent();
1661 return Ctx->getPrimaryContext();
1662}
1663
1664RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1665 // Loop until we find a non-record context.
1666 RecordDecl *OutermostRD = nullptr;
1667 DeclContext *DC = this;
1668 while (DC->isRecord()) {
1669 OutermostRD = cast<RecordDecl>(DC);
1670 DC = DC->getLexicalParent();
1671 }
1672 return OutermostRD;
1673}
1674
1675bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1676 // For non-file contexts, this is equivalent to Equals.
1677 if (!isFileContext())
1678 return O->Equals(this);
1679
1680 do {
1681 if (O->Equals(this))
1682 return true;
1683
1684 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O);
1685 if (!NS || !NS->isInline())
1686 break;
1687 O = NS->getParent();
1688 } while (O);
1689
1690 return false;
1691}
1692
1693void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1694 DeclContext *PrimaryDC = this->getPrimaryContext();
1695 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1696 // If the decl is being added outside of its semantic decl context, we
1697 // need to ensure that we eagerly build the lookup information for it.
1698 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1699}
1700
1701void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1702 bool Recoverable) {
1703 assert(this == getPrimaryContext() && "expected a primary DC")((this == getPrimaryContext() && "expected a primary DC"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"expected a primary DC\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1703, __PRETTY_FUNCTION__))
;
1704
1705 if (!isLookupContext()) {
1706 if (isTransparentContext())
1707 getParent()->getPrimaryContext()
1708 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1709 return;
1710 }
1711
1712 // Skip declarations which should be invisible to name lookup.
1713 if (shouldBeHidden(D))
1714 return;
1715
1716 // If we already have a lookup data structure, perform the insertion into
1717 // it. If we might have externally-stored decls with this name, look them
1718 // up and perform the insertion. If this decl was declared outside its
1719 // semantic context, buildLookup won't add it, so add it now.
1720 //
1721 // FIXME: As a performance hack, don't add such decls into the translation
1722 // unit unless we're in C++, since qualified lookup into the TU is never
1723 // performed.
1724 if (LookupPtr || hasExternalVisibleStorage() ||
1725 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1726 (getParentASTContext().getLangOpts().CPlusPlus ||
1727 !isTranslationUnit()))) {
1728 // If we have lazily omitted any decls, they might have the same name as
1729 // the decl which we are adding, so build a full lookup table before adding
1730 // this decl.
1731 buildLookup();
1732 makeDeclVisibleInContextImpl(D, Internal);
1733 } else {
1734 HasLazyLocalLexicalLookups = true;
1735 }
1736
1737 // If we are a transparent context or inline namespace, insert into our
1738 // parent context, too. This operation is recursive.
1739 if (isTransparentContext() || isInlineNamespace())
1740 getParent()->getPrimaryContext()->
1741 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1742
1743 Decl *DCAsDecl = cast<Decl>(this);
1744 // Notify that a decl was made visible unless we are a Tag being defined.
1745 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1746 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1747 L->AddedVisibleDecl(this, D);
1748}
1749
1750void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1751 // Find or create the stored declaration map.
1752 StoredDeclsMap *Map = LookupPtr;
1753 if (!Map) {
1754 ASTContext *C = &getParentASTContext();
1755 Map = CreateStoredDeclsMap(*C);
1756 }
1757
1758 // If there is an external AST source, load any declarations it knows about
1759 // with this declaration's name.
1760 // If the lookup table contains an entry about this name it means that we
1761 // have already checked the external source.
1762 if (!Internal)
1763 if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1764 if (hasExternalVisibleStorage() &&
1765 Map->find(D->getDeclName()) == Map->end())
1766 Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1767
1768 // Insert this declaration into the map.
1769 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1770
1771 if (Internal) {
1772 // If this is being added as part of loading an external declaration,
1773 // this may not be the only external declaration with this name.
1774 // In this case, we never try to replace an existing declaration; we'll
1775 // handle that when we finalize the list of declarations for this name.
1776 DeclNameEntries.setHasExternalDecls();
1777 DeclNameEntries.AddSubsequentDecl(D);
1778 return;
1779 }
1780
1781 if (DeclNameEntries.isNull()) {
1782 DeclNameEntries.setOnlyValue(D);
1783 return;
1784 }
1785
1786 if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1787 // This declaration has replaced an existing one for which
1788 // declarationReplaces returns true.
1789 return;
1790 }
1791
1792 // Put this declaration into the appropriate slot.
1793 DeclNameEntries.AddSubsequentDecl(D);
1794}
1795
1796UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1797 return cast<UsingDirectiveDecl>(*I);
1798}
1799
1800/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1801/// this context.
1802DeclContext::udir_range DeclContext::using_directives() const {
1803 // FIXME: Use something more efficient than normal lookup for using
1804 // directives. In C++, using directives are looked up more than anything else.
1805 lookup_result Result = lookup(UsingDirectiveDecl::getName());
1806 return udir_range(Result.begin(), Result.end());
1807}
1808
1809//===----------------------------------------------------------------------===//
1810// Creation and Destruction of StoredDeclsMaps. //
1811//===----------------------------------------------------------------------===//
1812
1813StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1814 assert(!LookupPtr && "context already has a decls map")((!LookupPtr && "context already has a decls map") ? static_cast
<void> (0) : __assert_fail ("!LookupPtr && \"context already has a decls map\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1814, __PRETTY_FUNCTION__))
;
1815 assert(getPrimaryContext() == this &&((getPrimaryContext() == this && "creating decls map on non-primary context"
) ? static_cast<void> (0) : __assert_fail ("getPrimaryContext() == this && \"creating decls map on non-primary context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1816, __PRETTY_FUNCTION__))
1816 "creating decls map on non-primary context")((getPrimaryContext() == this && "creating decls map on non-primary context"
) ? static_cast<void> (0) : __assert_fail ("getPrimaryContext() == this && \"creating decls map on non-primary context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1816, __PRETTY_FUNCTION__))
;
1817
1818 StoredDeclsMap *M;
1819 bool Dependent = isDependentContext();
1820 if (Dependent)
1821 M = new DependentStoredDeclsMap();
1822 else
1823 M = new StoredDeclsMap();
1824 M->Previous = C.LastSDM;
1825 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1826 LookupPtr = M;
1827 return M;
1828}
1829
1830void ASTContext::ReleaseDeclContextMaps() {
1831 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1832 // pointer because the subclass doesn't add anything that needs to
1833 // be deleted.
1834 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1835}
1836
1837void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1838 while (Map) {
1839 // Advance the iteration before we invalidate memory.
1840 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1841
1842 if (Dependent)
1843 delete static_cast<DependentStoredDeclsMap*>(Map);
1844 else
1845 delete Map;
1846
1847 Map = Next.getPointer();
1848 Dependent = Next.getInt();
1849 }
1850}
1851
1852DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1853 DeclContext *Parent,
1854 const PartialDiagnostic &PDiag) {
1855 assert(Parent->isDependentContext()((Parent->isDependentContext() && "cannot iterate dependent diagnostics of non-dependent context"
) ? static_cast<void> (0) : __assert_fail ("Parent->isDependentContext() && \"cannot iterate dependent diagnostics of non-dependent context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1856, __PRETTY_FUNCTION__))
1856 && "cannot iterate dependent diagnostics of non-dependent context")((Parent->isDependentContext() && "cannot iterate dependent diagnostics of non-dependent context"
) ? static_cast<void> (0) : __assert_fail ("Parent->isDependentContext() && \"cannot iterate dependent diagnostics of non-dependent context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/AST/DeclBase.cpp"
, 1856, __PRETTY_FUNCTION__))
;
1857 Parent = Parent->getPrimaryContext();
1858 if (!Parent->LookupPtr)
1859 Parent->CreateStoredDeclsMap(C);
1860
1861 DependentStoredDeclsMap *Map =
1862 static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1863
1864 // Allocate the copy of the PartialDiagnostic via the ASTContext's
1865 // BumpPtrAllocator, rather than the ASTContext itself.
1866 PartialDiagnostic::Storage *DiagStorage = nullptr;
1867 if (PDiag.hasStorage())
1868 DiagStorage = new (C) PartialDiagnostic::Storage;
1869
1870 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1871
1872 // TODO: Maybe we shouldn't reverse the order during insertion.
1873 DD->NextDiagnostic = Map->FirstDiagnostic;
1874 Map->FirstDiagnostic = DD;
1875
1876 return DD;
1877}

/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h

1//===-- DeclContextInternals.h - DeclContext Representation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the data structures used in the implementation
11// of DeclContext.
12//
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H
15#define LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclarationName.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/PointerIntPair.h"
22#include "llvm/ADT/PointerUnion.h"
23#include "llvm/ADT/SmallVector.h"
24#include <algorithm>
25
26namespace clang {
27
28class DependentDiagnostic;
29
30/// \brief An array of decls optimized for the common case of only containing
31/// one entry.
32struct StoredDeclsList {
33
34 /// \brief When in vector form, this is what the Data pointer points to.
35 typedef SmallVector<NamedDecl *, 4> DeclsTy;
36
37 /// \brief A collection of declarations, with a flag to indicate if we have
38 /// further external declarations.
39 typedef llvm::PointerIntPair<DeclsTy *, 1, bool> DeclsAndHasExternalTy;
40
41 /// \brief The stored data, which will be either a pointer to a NamedDecl,
42 /// or a pointer to a vector with a flag to indicate if there are further
43 /// external declarations.
44 llvm::PointerUnion<NamedDecl*, DeclsAndHasExternalTy> Data;
45
46public:
47 StoredDeclsList() {}
48
49 StoredDeclsList(StoredDeclsList &&RHS) : Data(RHS.Data) {
50 RHS.Data = (NamedDecl *)nullptr;
51 }
52
53 ~StoredDeclsList() {
54 // If this is a vector-form, free the vector.
55 if (DeclsTy *Vector = getAsVector())
56 delete Vector;
57 }
58
59 StoredDeclsList &operator=(StoredDeclsList &&RHS) {
60 if (DeclsTy *Vector = getAsVector())
61 delete Vector;
62 Data = RHS.Data;
63 RHS.Data = (NamedDecl *)nullptr;
64 return *this;
65 }
66
67 bool isNull() const { return Data.isNull(); }
68
69 NamedDecl *getAsDecl() const {
70 return Data.dyn_cast<NamedDecl *>();
71 }
72
73 DeclsAndHasExternalTy getAsVectorAndHasExternal() const {
74 return Data.dyn_cast<DeclsAndHasExternalTy>();
75 }
76
77 DeclsTy *getAsVector() const {
78 return getAsVectorAndHasExternal().getPointer();
79 }
80
81 bool hasExternalDecls() const {
82 return getAsVectorAndHasExternal().getInt();
83 }
84
85 void setHasExternalDecls() {
86 if (DeclsTy *Vec = getAsVector())
7
Taking false branch
87 Data = DeclsAndHasExternalTy(Vec, true);
88 else {
89 DeclsTy *VT = new DeclsTy();
8
Memory is allocated
90 if (NamedDecl *OldD = getAsDecl())
9
Taking false branch
91 VT->push_back(OldD);
92 Data = DeclsAndHasExternalTy(VT, true);
10
Potential leak of memory pointed to by 'VT'
93 }
94 }
95
96 void setOnlyValue(NamedDecl *ND) {
97 assert(!getAsVector() && "Not inline")((!getAsVector() && "Not inline") ? static_cast<void
> (0) : __assert_fail ("!getAsVector() && \"Not inline\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 97, __PRETTY_FUNCTION__))
;
98 Data = ND;
99 // Make sure that Data is a plain NamedDecl* so we can use its address
100 // at getLookupResult.
101 assert(*(NamedDecl **)&Data == ND &&((*(NamedDecl **)&Data == ND && "PointerUnion mangles the NamedDecl pointer!"
) ? static_cast<void> (0) : __assert_fail ("*(NamedDecl **)&Data == ND && \"PointerUnion mangles the NamedDecl pointer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 102, __PRETTY_FUNCTION__))
102 "PointerUnion mangles the NamedDecl pointer!")((*(NamedDecl **)&Data == ND && "PointerUnion mangles the NamedDecl pointer!"
) ? static_cast<void> (0) : __assert_fail ("*(NamedDecl **)&Data == ND && \"PointerUnion mangles the NamedDecl pointer!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 102, __PRETTY_FUNCTION__))
;
103 }
104
105 void remove(NamedDecl *D) {
106 assert(!isNull() && "removing from empty list")((!isNull() && "removing from empty list") ? static_cast
<void> (0) : __assert_fail ("!isNull() && \"removing from empty list\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 106, __PRETTY_FUNCTION__))
;
107 if (NamedDecl *Singleton = getAsDecl()) {
108 assert(Singleton == D && "list is different singleton")((Singleton == D && "list is different singleton") ? static_cast
<void> (0) : __assert_fail ("Singleton == D && \"list is different singleton\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 108, __PRETTY_FUNCTION__))
;
109 (void)Singleton;
110 Data = (NamedDecl *)nullptr;
111 return;
112 }
113
114 DeclsTy &Vec = *getAsVector();
115 DeclsTy::iterator I = std::find(Vec.begin(), Vec.end(), D);
116 assert(I != Vec.end() && "list does not contain decl")((I != Vec.end() && "list does not contain decl") ? static_cast
<void> (0) : __assert_fail ("I != Vec.end() && \"list does not contain decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 116, __PRETTY_FUNCTION__))
;
117 Vec.erase(I);
118
119 assert(std::find(Vec.begin(), Vec.end(), D)((std::find(Vec.begin(), Vec.end(), D) == Vec.end() &&
"list still contains decl") ? static_cast<void> (0) : __assert_fail
("std::find(Vec.begin(), Vec.end(), D) == Vec.end() && \"list still contains decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 120, __PRETTY_FUNCTION__))
120 == Vec.end() && "list still contains decl")((std::find(Vec.begin(), Vec.end(), D) == Vec.end() &&
"list still contains decl") ? static_cast<void> (0) : __assert_fail
("std::find(Vec.begin(), Vec.end(), D) == Vec.end() && \"list still contains decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 120, __PRETTY_FUNCTION__))
;
121 }
122
123 /// \brief Remove any declarations which were imported from an external
124 /// AST source.
125 void removeExternalDecls() {
126 if (isNull()) {
127 // Nothing to do.
128 } else if (NamedDecl *Singleton = getAsDecl()) {
129 if (Singleton->isFromASTFile())
130 *this = StoredDeclsList();
131 } else {
132 DeclsTy &Vec = *getAsVector();
133 Vec.erase(std::remove_if(Vec.begin(), Vec.end(),
134 [](Decl *D) { return D->isFromASTFile(); }),
135 Vec.end());
136 // Don't have any external decls any more.
137 Data = DeclsAndHasExternalTy(&Vec, false);
138 }
139 }
140
141 /// getLookupResult - Return an array of all the decls that this list
142 /// represents.
143 DeclContext::lookup_result getLookupResult() {
144 if (isNull())
145 return DeclContext::lookup_result();
146
147 // If we have a single NamedDecl, return it.
148 if (NamedDecl *ND = getAsDecl()) {
149 assert(!isNull() && "Empty list isn't allowed")((!isNull() && "Empty list isn't allowed") ? static_cast
<void> (0) : __assert_fail ("!isNull() && \"Empty list isn't allowed\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 149, __PRETTY_FUNCTION__))
;
150
151 // Data is a raw pointer to a NamedDecl*, return it.
152 return DeclContext::lookup_result(ND);
153 }
154
155 assert(getAsVector() && "Must have a vector at this point")((getAsVector() && "Must have a vector at this point"
) ? static_cast<void> (0) : __assert_fail ("getAsVector() && \"Must have a vector at this point\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 155, __PRETTY_FUNCTION__))
;
156 DeclsTy &Vector = *getAsVector();
157
158 // Otherwise, we have a range result.
159 return DeclContext::lookup_result(Vector);
160 }
161
162 /// HandleRedeclaration - If this is a redeclaration of an existing decl,
163 /// replace the old one with D and return true. Otherwise return false.
164 bool HandleRedeclaration(NamedDecl *D, bool IsKnownNewer) {
165 // Most decls only have one entry in their list, special case it.
166 if (NamedDecl *OldD = getAsDecl()) {
167 if (!D->declarationReplaces(OldD, IsKnownNewer))
168 return false;
169 setOnlyValue(D);
170 return true;
171 }
172
173 // Determine if this declaration is actually a redeclaration.
174 DeclsTy &Vec = *getAsVector();
175 for (DeclsTy::iterator OD = Vec.begin(), ODEnd = Vec.end();
176 OD != ODEnd; ++OD) {
177 NamedDecl *OldD = *OD;
178 if (D->declarationReplaces(OldD, IsKnownNewer)) {
179 *OD = D;
180 return true;
181 }
182 }
183
184 return false;
185 }
186
187 /// AddSubsequentDecl - This is called on the second and later decl when it is
188 /// not a redeclaration to merge it into the appropriate place in our list.
189 ///
190 void AddSubsequentDecl(NamedDecl *D) {
191 assert(!isNull() && "don't AddSubsequentDecl when we have no decls")((!isNull() && "don't AddSubsequentDecl when we have no decls"
) ? static_cast<void> (0) : __assert_fail ("!isNull() && \"don't AddSubsequentDecl when we have no decls\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/include/clang/AST/DeclContextInternals.h"
, 191, __PRETTY_FUNCTION__))
;
192
193 // If this is the second decl added to the list, convert this to vector
194 // form.
195 if (NamedDecl *OldD = getAsDecl()) {
196 DeclsTy *VT = new DeclsTy();
197 VT->push_back(OldD);
198 Data = DeclsAndHasExternalTy(VT, false);
199 }
200
201 DeclsTy &Vec = *getAsVector();
202
203 // Using directives end up in a special entry which contains only
204 // other using directives, so all this logic is wasted for them.
205 // But avoiding the logic wastes time in the far-more-common case
206 // that we're *not* adding a new using directive.
207
208 // Tag declarations always go at the end of the list so that an
209 // iterator which points at the first tag will start a span of
210 // decls that only contains tags.
211 if (D->hasTagIdentifierNamespace())
212 Vec.push_back(D);
213
214 // Resolved using declarations go at the front of the list so that
215 // they won't show up in other lookup results. Unresolved using
216 // declarations (which are always in IDNS_Using | IDNS_Ordinary)
217 // follow that so that the using declarations will be contiguous.
218 else if (D->getIdentifierNamespace() & Decl::IDNS_Using) {
219 DeclsTy::iterator I = Vec.begin();
220 if (D->getIdentifierNamespace() != Decl::IDNS_Using) {
221 while (I != Vec.end() &&
222 (*I)->getIdentifierNamespace() == Decl::IDNS_Using)
223 ++I;
224 }
225 Vec.insert(I, D);
226
227 // All other declarations go at the end of the list, but before any
228 // tag declarations. But we can be clever about tag declarations
229 // because there can only ever be one in a scope.
230 } else if (!Vec.empty() && Vec.back()->hasTagIdentifierNamespace()) {
231 NamedDecl *TagD = Vec.back();
232 Vec.back() = D;
233 Vec.push_back(TagD);
234 } else
235 Vec.push_back(D);
236 }
237};
238
239class StoredDeclsMap
240 : public llvm::SmallDenseMap<DeclarationName, StoredDeclsList, 4> {
241
242public:
243 static void DestroyAll(StoredDeclsMap *Map, bool Dependent);
244
245private:
246 friend class ASTContext; // walks the chain deleting these
247 friend class DeclContext;
248 llvm::PointerIntPair<StoredDeclsMap*, 1> Previous;
249};
250
251class DependentStoredDeclsMap : public StoredDeclsMap {
252public:
253 DependentStoredDeclsMap() : FirstDiagnostic(nullptr) {}
254
255private:
256 friend class DependentDiagnostic;
257 friend class DeclContext; // iterates over diagnostics
258
259 DependentDiagnostic *FirstDiagnostic;
260};
261
262} // end namespace clang
263
264#endif