clang  9.0.0svn
DeclBase.cpp
Go to the documentation of this file.
1 //===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Decl and DeclContext classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/DeclBase.h"
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/Type.h"
30 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/PointerIntPair.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/VersionTuple.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstddef>
48 #include <string>
49 #include <tuple>
50 #include <utility>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 // Statistics
56 //===----------------------------------------------------------------------===//
57 
58 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
59 #define ABSTRACT_DECL(DECL)
60 #include "clang/AST/DeclNodes.inc"
61 
64 }
65 
66 #define DECL(DERIVED, BASE) \
67  static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
68  "Alignment sufficient after objects prepended to " #DERIVED);
69 #define ABSTRACT_DECL(DECL)
70 #include "clang/AST/DeclNodes.inc"
71 
72 void *Decl::operator new(std::size_t Size, const ASTContext &Context,
73  unsigned ID, std::size_t Extra) {
74  // Allocate an extra 8 bytes worth of storage, which ensures that the
75  // resulting pointer will still be 8-byte aligned.
76  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
77  "Decl won't be misaligned");
78  void *Start = Context.Allocate(Size + Extra + 8);
79  void *Result = (char*)Start + 8;
80 
81  unsigned *PrefixPtr = (unsigned *)Result - 2;
82 
83  // Zero out the first 4 bytes; this is used to store the owning module ID.
84  PrefixPtr[0] = 0;
85 
86  // Store the global declaration ID in the second 4 bytes.
87  PrefixPtr[1] = ID;
88 
89  return Result;
90 }
91 
92 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
93  DeclContext *Parent, std::size_t Extra) {
94  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
95  // With local visibility enabled, we track the owning module even for local
96  // declarations. We create the TU decl early and may not yet know what the
97  // LangOpts are, so conservatively allocate the storage.
98  if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
99  // Ensure required alignment of the resulting object by adding extra
100  // padding at the start if required.
101  size_t ExtraAlign =
102  llvm::OffsetToAlignment(sizeof(Module *), alignof(Decl));
103  auto *Buffer = reinterpret_cast<char *>(
104  ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
105  Buffer += ExtraAlign;
106  auto *ParentModule =
107  Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
108  return new (Buffer) Module*(ParentModule) + 1;
109  }
110  return ::operator new(Size + Extra, Ctx);
111 }
112 
113 Module *Decl::getOwningModuleSlow() const {
114  assert(isFromASTFile() && "Not from AST file?");
116 }
117 
120 }
121 
122 const char *Decl::getDeclKindName() const {
123  switch (DeclKind) {
124  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
125 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
126 #define ABSTRACT_DECL(DECL)
127 #include "clang/AST/DeclNodes.inc"
128  }
129 }
130 
131 void Decl::setInvalidDecl(bool Invalid) {
132  InvalidDecl = Invalid;
133  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
134  if (!Invalid) {
135  return;
136  }
137 
138  if (!isa<ParmVarDecl>(this)) {
139  // Defensive maneuver for ill-formed code: we're likely not to make it to
140  // a point where we set the access specifier, so default it to "public"
141  // to avoid triggering asserts elsewhere in the front end.
143  }
144 
145  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
146  // are invalid too.
147  if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
148  for (auto *Binding : DD->bindings()) {
149  Binding->setInvalidDecl();
150  }
151  }
152 }
153 
154 const char *DeclContext::getDeclKindName() const {
155  switch (getDeclKind()) {
156 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
157 #define ABSTRACT_DECL(DECL)
158 #include "clang/AST/DeclNodes.inc"
159  }
160  llvm_unreachable("Declaration context not in DeclNodes.inc!");
161 }
162 
163 bool Decl::StatisticsEnabled = false;
165  StatisticsEnabled = true;
166 }
167 
169  llvm::errs() << "\n*** Decl Stats:\n";
170 
171  int totalDecls = 0;
172 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
173 #define ABSTRACT_DECL(DECL)
174 #include "clang/AST/DeclNodes.inc"
175  llvm::errs() << " " << totalDecls << " decls total.\n";
176 
177  int totalBytes = 0;
178 #define DECL(DERIVED, BASE) \
179  if (n##DERIVED##s > 0) { \
180  totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
181  llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
182  << sizeof(DERIVED##Decl) << " each (" \
183  << n##DERIVED##s * sizeof(DERIVED##Decl) \
184  << " bytes)\n"; \
185  }
186 #define ABSTRACT_DECL(DECL)
187 #include "clang/AST/DeclNodes.inc"
188 
189  llvm::errs() << "Total bytes = " << totalBytes << "\n";
190 }
191 
192 void Decl::add(Kind k) {
193  switch (k) {
194 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
195 #define ABSTRACT_DECL(DECL)
196 #include "clang/AST/DeclNodes.inc"
197  }
198 }
199 
201  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
202  return TTP->isParameterPack();
203  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
204  return NTTP->isParameterPack();
205  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
206  return TTP->isParameterPack();
207  return false;
208 }
209 
210 bool Decl::isParameterPack() const {
211  if (const auto *Parm = dyn_cast<ParmVarDecl>(this))
212  return Parm->isParameterPack();
213 
214  return isTemplateParameterPack();
215 }
216 
218  if (auto *FD = dyn_cast<FunctionDecl>(this))
219  return FD;
220  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
221  return FTD->getTemplatedDecl();
222  return nullptr;
223 }
224 
225 bool Decl::isTemplateDecl() const {
226  return isa<TemplateDecl>(this);
227 }
228 
230  if (auto *FD = dyn_cast<FunctionDecl>(this))
231  return FD->getDescribedFunctionTemplate();
232  else if (auto *RD = dyn_cast<CXXRecordDecl>(this))
233  return RD->getDescribedClassTemplate();
234  else if (auto *VD = dyn_cast<VarDecl>(this))
235  return VD->getDescribedVarTemplate();
236  else if (auto *AD = dyn_cast<TypeAliasDecl>(this))
237  return AD->getDescribedAliasTemplate();
238 
239  return nullptr;
240 }
241 
242 bool Decl::isTemplated() const {
243  // A declaration is dependent if it is a template or a template pattern, or
244  // is within (lexcially for a friend, semantically otherwise) a dependent
245  // context.
246  // FIXME: Should local extern declarations be treated like friends?
247  if (auto *AsDC = dyn_cast<DeclContext>(this))
248  return AsDC->isDependentContext();
250  return DC->isDependentContext() || isTemplateDecl() || getDescribedTemplate();
251 }
252 
254  for (const DeclContext *DC = getDeclContext();
255  DC && !DC->isTranslationUnit() && !DC->isNamespace();
256  DC = DC->getParent())
257  if (DC->isFunctionOrMethod())
258  return DC;
259 
260  return nullptr;
261 }
262 
263 //===----------------------------------------------------------------------===//
264 // PrettyStackTraceDecl Implementation
265 //===----------------------------------------------------------------------===//
266 
267 void PrettyStackTraceDecl::print(raw_ostream &OS) const {
268  SourceLocation TheLoc = Loc;
269  if (TheLoc.isInvalid() && TheDecl)
270  TheLoc = TheDecl->getLocation();
271 
272  if (TheLoc.isValid()) {
273  TheLoc.print(OS, SM);
274  OS << ": ";
275  }
276 
277  OS << Message;
278 
279  if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
280  OS << " '";
281  DN->printQualifiedName(OS);
282  OS << '\'';
283  }
284  OS << '\n';
285 }
286 
287 //===----------------------------------------------------------------------===//
288 // Decl Implementation
289 //===----------------------------------------------------------------------===//
290 
291 // Out-of-line virtual method providing a home for Decl.
292 Decl::~Decl() = default;
293 
295  DeclCtx = DC;
296 }
297 
299  if (DC == getLexicalDeclContext())
300  return;
301 
302  if (isInSemaDC()) {
303  setDeclContextsImpl(getDeclContext(), DC, getASTContext());
304  } else {
305  getMultipleDC()->LexicalDC = DC;
306  }
307 
308  // FIXME: We shouldn't be changing the lexical context of declarations
309  // imported from AST files.
310  if (!isFromASTFile()) {
311  setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
312  if (hasOwningModule())
313  setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
314  }
315 
316  assert(
318  getOwningModule()) &&
319  "hidden declaration has no owning module");
320 }
321 
322 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
323  ASTContext &Ctx) {
324  if (SemaDC == LexicalDC) {
325  DeclCtx = SemaDC;
326  } else {
327  auto *MDC = new (Ctx) Decl::MultipleDC();
328  MDC->SemanticDC = SemaDC;
329  MDC->LexicalDC = LexicalDC;
330  DeclCtx = MDC;
331  }
332 }
333 
335  const DeclContext *LDC = getLexicalDeclContext();
336  while (true) {
337  if (LDC->isFunctionOrMethod())
338  return true;
339  if (!isa<TagDecl>(LDC))
340  return false;
341  LDC = LDC->getLexicalParent();
342  }
343  return false;
344 }
345 
347  for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
348  if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
349  if (ND->isAnonymousNamespace())
350  return true;
351  }
352 
353  return false;
354 }
355 
357  return getDeclContext()->isStdNamespace();
358 }
359 
361  if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
362  return TUD;
363 
364  DeclContext *DC = getDeclContext();
365  assert(DC && "This decl is not contained in a translation unit!");
366 
367  while (!DC->isTranslationUnit()) {
368  DC = DC->getParent();
369  assert(DC && "This decl is not contained in a translation unit!");
370  }
371 
372  return cast<TranslationUnitDecl>(DC);
373 }
374 
377 }
378 
381 }
382 
383 unsigned Decl::getMaxAlignment() const {
384  if (!hasAttrs())
385  return 0;
386 
387  unsigned Align = 0;
388  const AttrVec &V = getAttrs();
389  ASTContext &Ctx = getASTContext();
390  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
391  for (; I != E; ++I)
392  Align = std::max(Align, I->getAlignment(Ctx));
393  return Align;
394 }
395 
396 bool Decl::isUsed(bool CheckUsedAttr) const {
397  const Decl *CanonD = getCanonicalDecl();
398  if (CanonD->Used)
399  return true;
400 
401  // Check for used attribute.
402  // Ask the most recent decl, since attributes accumulate in the redecl chain.
403  if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
404  return true;
405 
406  // The information may have not been deserialized yet. Force deserialization
407  // to complete the needed information.
408  return getMostRecentDecl()->getCanonicalDecl()->Used;
409 }
410 
412  if (isUsed(false))
413  return;
414 
415  if (C.getASTMutationListener())
417 
418  setIsUsed();
419 }
420 
421 bool Decl::isReferenced() const {
422  if (Referenced)
423  return true;
424 
425  // Check redeclarations.
426  for (const auto *I : redecls())
427  if (I->Referenced)
428  return true;
429 
430  return false;
431 }
432 
433 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
434  const Decl *Definition = nullptr;
435  if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
436  Definition = ID->getDefinition();
437  } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
438  Definition = PD->getDefinition();
439  } else if (auto *TD = dyn_cast<TagDecl>(this)) {
440  Definition = TD->getDefinition();
441  }
442  if (!Definition)
443  Definition = this;
444 
445  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
446  return attr;
447  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
448  return dcd->getAttr<ExternalSourceSymbolAttr>();
449  }
450 
451  return nullptr;
452 }
453 
454 bool Decl::hasDefiningAttr() const {
455  return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
456 }
457 
458 const Attr *Decl::getDefiningAttr() const {
459  if (auto *AA = getAttr<AliasAttr>())
460  return AA;
461  if (auto *IFA = getAttr<IFuncAttr>())
462  return IFA;
463  return nullptr;
464 }
465 
466 static StringRef getRealizedPlatform(const AvailabilityAttr *A,
467  const ASTContext &Context) {
468  // Check if this is an App Extension "platform", and if so chop off
469  // the suffix for matching with the actual platform.
470  StringRef RealizedPlatform = A->getPlatform()->getName();
471  if (!Context.getLangOpts().AppExt)
472  return RealizedPlatform;
473  size_t suffix = RealizedPlatform.rfind("_app_extension");
474  if (suffix != StringRef::npos)
475  return RealizedPlatform.slice(0, suffix);
476  return RealizedPlatform;
477 }
478 
479 /// Determine the availability of the given declaration based on
480 /// the target platform.
481 ///
482 /// When it returns an availability result other than \c AR_Available,
483 /// if the \p Message parameter is non-NULL, it will be set to a
484 /// string describing why the entity is unavailable.
485 ///
486 /// FIXME: Make these strings localizable, since they end up in
487 /// diagnostics.
489  const AvailabilityAttr *A,
490  std::string *Message,
491  VersionTuple EnclosingVersion) {
492  if (EnclosingVersion.empty())
493  EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
494 
495  if (EnclosingVersion.empty())
496  return AR_Available;
497 
498  StringRef ActualPlatform = A->getPlatform()->getName();
499  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
500 
501  // Match the platform name.
502  if (getRealizedPlatform(A, Context) != TargetPlatform)
503  return AR_Available;
504 
505  StringRef PrettyPlatformName
506  = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
507 
508  if (PrettyPlatformName.empty())
509  PrettyPlatformName = ActualPlatform;
510 
511  std::string HintMessage;
512  if (!A->getMessage().empty()) {
513  HintMessage = " - ";
514  HintMessage += A->getMessage();
515  }
516 
517  // Make sure that this declaration has not been marked 'unavailable'.
518  if (A->getUnavailable()) {
519  if (Message) {
520  Message->clear();
521  llvm::raw_string_ostream Out(*Message);
522  Out << "not available on " << PrettyPlatformName
523  << HintMessage;
524  }
525 
526  return AR_Unavailable;
527  }
528 
529  // Make sure that this declaration has already been introduced.
530  if (!A->getIntroduced().empty() &&
531  EnclosingVersion < A->getIntroduced()) {
532  if (Message) {
533  Message->clear();
534  llvm::raw_string_ostream Out(*Message);
535  VersionTuple VTI(A->getIntroduced());
536  Out << "introduced in " << PrettyPlatformName << ' '
537  << VTI << HintMessage;
538  }
539 
540  return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
541  }
542 
543  // Make sure that this declaration hasn't been obsoleted.
544  if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
545  if (Message) {
546  Message->clear();
547  llvm::raw_string_ostream Out(*Message);
548  VersionTuple VTO(A->getObsoleted());
549  Out << "obsoleted in " << PrettyPlatformName << ' '
550  << VTO << HintMessage;
551  }
552 
553  return AR_Unavailable;
554  }
555 
556  // Make sure that this declaration hasn't been deprecated.
557  if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
558  if (Message) {
559  Message->clear();
560  llvm::raw_string_ostream Out(*Message);
561  VersionTuple VTD(A->getDeprecated());
562  Out << "first deprecated in " << PrettyPlatformName << ' '
563  << VTD << HintMessage;
564  }
565 
566  return AR_Deprecated;
567  }
568 
569  return AR_Available;
570 }
571 
573  VersionTuple EnclosingVersion,
574  StringRef *RealizedPlatform) const {
575  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
576  return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
577  RealizedPlatform);
578 
580  std::string ResultMessage;
581 
582  for (const auto *A : attrs()) {
583  if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
584  if (Result >= AR_Deprecated)
585  continue;
586 
587  if (Message)
588  ResultMessage = Deprecated->getMessage();
589 
590  Result = AR_Deprecated;
591  continue;
592  }
593 
594  if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
595  if (Message)
596  *Message = Unavailable->getMessage();
597  return AR_Unavailable;
598  }
599 
600  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
602  Message, EnclosingVersion);
603 
604  if (AR == AR_Unavailable) {
605  if (RealizedPlatform)
606  *RealizedPlatform = Availability->getPlatform()->getName();
607  return AR_Unavailable;
608  }
609 
610  if (AR > Result) {
611  Result = AR;
612  if (Message)
613  ResultMessage.swap(*Message);
614  }
615  continue;
616  }
617  }
618 
619  if (Message)
620  Message->swap(ResultMessage);
621  return Result;
622 }
623 
624 VersionTuple Decl::getVersionIntroduced() const {
625  const ASTContext &Context = getASTContext();
626  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
627  for (const auto *A : attrs()) {
628  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
629  if (getRealizedPlatform(Availability, Context) != TargetPlatform)
630  continue;
631  if (!Availability->getIntroduced().empty())
632  return Availability->getIntroduced();
633  }
634  }
635  return {};
636 }
637 
638 bool Decl::canBeWeakImported(bool &IsDefinition) const {
639  IsDefinition = false;
640 
641  // Variables, if they aren't definitions.
642  if (const auto *Var = dyn_cast<VarDecl>(this)) {
643  if (Var->isThisDeclarationADefinition()) {
644  IsDefinition = true;
645  return false;
646  }
647  return true;
648 
649  // Functions, if they aren't definitions.
650  } else if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
651  if (FD->hasBody()) {
652  IsDefinition = true;
653  return false;
654  }
655  return true;
656 
657  // Objective-C classes, if this is the non-fragile runtime.
658  } else if (isa<ObjCInterfaceDecl>(this) &&
660  return true;
661 
662  // Nothing else.
663  } else {
664  return false;
665  }
666 }
667 
668 bool Decl::isWeakImported() const {
669  bool IsDefinition;
670  if (!canBeWeakImported(IsDefinition))
671  return false;
672 
673  for (const auto *A : attrs()) {
674  if (isa<WeakImportAttr>(A))
675  return true;
676 
677  if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
678  if (CheckAvailability(getASTContext(), Availability, nullptr,
679  VersionTuple()) == AR_NotYetIntroduced)
680  return true;
681  }
682  }
683 
684  return false;
685 }
686 
688  switch (DeclKind) {
689  case Function:
690  case CXXDeductionGuide:
691  case CXXMethod:
692  case CXXConstructor:
693  case ConstructorUsingShadow:
694  case CXXDestructor:
695  case CXXConversion:
696  case EnumConstant:
697  case Var:
698  case ImplicitParam:
699  case ParmVar:
700  case ObjCMethod:
701  case ObjCProperty:
702  case MSProperty:
703  return IDNS_Ordinary;
704  case Label:
705  return IDNS_Label;
706  case IndirectField:
707  return IDNS_Ordinary | IDNS_Member;
708 
709  case Binding:
710  case NonTypeTemplateParm:
711  case VarTemplate:
712  // These (C++-only) declarations are found by redeclaration lookup for
713  // tag types, so we include them in the tag namespace.
714  return IDNS_Ordinary | IDNS_Tag;
715 
716  case ObjCCompatibleAlias:
717  case ObjCInterface:
718  return IDNS_Ordinary | IDNS_Type;
719 
720  case Typedef:
721  case TypeAlias:
722  case TemplateTypeParm:
723  case ObjCTypeParam:
724  return IDNS_Ordinary | IDNS_Type;
725 
726  case UnresolvedUsingTypename:
728 
729  case UsingShadow:
730  return 0; // we'll actually overwrite this later
731 
732  case UnresolvedUsingValue:
733  return IDNS_Ordinary | IDNS_Using;
734 
735  case Using:
736  case UsingPack:
737  return IDNS_Using;
738 
739  case ObjCProtocol:
740  return IDNS_ObjCProtocol;
741 
742  case Field:
743  case ObjCAtDefsField:
744  case ObjCIvar:
745  return IDNS_Member;
746 
747  case Record:
748  case CXXRecord:
749  case Enum:
750  return IDNS_Tag | IDNS_Type;
751 
752  case Namespace:
753  case NamespaceAlias:
754  return IDNS_Namespace;
755 
756  case FunctionTemplate:
757  return IDNS_Ordinary;
758 
759  case ClassTemplate:
760  case TemplateTemplateParm:
761  case TypeAliasTemplate:
762  return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
763 
764  case OMPDeclareReduction:
765  return IDNS_OMPReduction;
766 
767  case OMPDeclareMapper:
768  return IDNS_OMPMapper;
769 
770  // Never have names.
771  case Friend:
772  case FriendTemplate:
773  case AccessSpec:
774  case LinkageSpec:
775  case Export:
776  case FileScopeAsm:
777  case StaticAssert:
778  case ObjCPropertyImpl:
779  case PragmaComment:
780  case PragmaDetectMismatch:
781  case Block:
782  case Captured:
783  case TranslationUnit:
784  case ExternCContext:
785  case Decomposition:
786 
787  case UsingDirective:
788  case BuiltinTemplate:
789  case ClassTemplateSpecialization:
790  case ClassTemplatePartialSpecialization:
791  case ClassScopeFunctionSpecialization:
792  case VarTemplateSpecialization:
793  case VarTemplatePartialSpecialization:
794  case ObjCImplementation:
795  case ObjCCategory:
796  case ObjCCategoryImpl:
797  case Import:
798  case OMPThreadPrivate:
799  case OMPAllocate:
800  case OMPRequires:
801  case OMPCapturedExpr:
802  case Empty:
803  // Never looked up by name.
804  return 0;
805  }
806 
807  llvm_unreachable("Invalid DeclKind!");
808 }
809 
810 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
811  assert(!HasAttrs && "Decl already contains attrs.");
812 
813  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
814  assert(AttrBlank.empty() && "HasAttrs was wrong?");
815 
816  AttrBlank = attrs;
817  HasAttrs = true;
818 }
819 
821  if (!HasAttrs) return;
822 
823  HasAttrs = false;
825 }
826 
827 void Decl::addAttr(Attr *A) {
828  if (!hasAttrs()) {
829  setAttrs(AttrVec(1, A));
830  return;
831  }
832 
833  AttrVec &Attrs = getAttrs();
834  if (!A->isInherited()) {
835  Attrs.push_back(A);
836  return;
837  }
838 
839  // Attribute inheritance is processed after attribute parsing. To keep the
840  // order as in the source code, add inherited attributes before non-inherited
841  // ones.
842  auto I = Attrs.begin(), E = Attrs.end();
843  for (; I != E; ++I) {
844  if (!(*I)->isInherited())
845  break;
846  }
847  Attrs.insert(I, A);
848 }
849 
850 const AttrVec &Decl::getAttrs() const {
851  assert(HasAttrs && "No attrs to get!");
852  return getASTContext().getDeclAttrs(this);
853 }
854 
856  Decl::Kind DK = D->getDeclKind();
857  switch(DK) {
858 #define DECL(NAME, BASE)
859 #define DECL_CONTEXT(NAME) \
860  case Decl::NAME: \
861  return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
862 #define DECL_CONTEXT_BASE(NAME)
863 #include "clang/AST/DeclNodes.inc"
864  default:
865 #define DECL(NAME, BASE)
866 #define DECL_CONTEXT_BASE(NAME) \
867  if (DK >= first##NAME && DK <= last##NAME) \
868  return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
869 #include "clang/AST/DeclNodes.inc"
870  llvm_unreachable("a decl that inherits DeclContext isn't handled");
871  }
872 }
873 
875  Decl::Kind DK = D->getKind();
876  switch(DK) {
877 #define DECL(NAME, BASE)
878 #define DECL_CONTEXT(NAME) \
879  case Decl::NAME: \
880  return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
881 #define DECL_CONTEXT_BASE(NAME)
882 #include "clang/AST/DeclNodes.inc"
883  default:
884 #define DECL(NAME, BASE)
885 #define DECL_CONTEXT_BASE(NAME) \
886  if (DK >= first##NAME && DK <= last##NAME) \
887  return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
888 #include "clang/AST/DeclNodes.inc"
889  llvm_unreachable("a decl that inherits DeclContext isn't handled");
890  }
891 }
892 
894  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
895  // FunctionDecl stores EndRangeLoc for this purpose.
896  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
897  const FunctionDecl *Definition;
898  if (FD->hasBody(Definition))
899  return Definition->getSourceRange().getEnd();
900  return {};
901  }
902 
903  if (Stmt *Body = getBody())
904  return Body->getSourceRange().getEnd();
905 
906  return {};
907 }
908 
909 bool Decl::AccessDeclContextSanity() const {
910 #ifndef NDEBUG
911  // Suppress this check if any of the following hold:
912  // 1. this is the translation unit (and thus has no parent)
913  // 2. this is a template parameter (and thus doesn't belong to its context)
914  // 3. this is a non-type template parameter
915  // 4. the context is not a record
916  // 5. it's invalid
917  // 6. it's a C++0x static_assert.
918  // 7. it's a block literal declaration
919  if (isa<TranslationUnitDecl>(this) ||
920  isa<TemplateTypeParmDecl>(this) ||
921  isa<NonTypeTemplateParmDecl>(this) ||
922  !isa<CXXRecordDecl>(getDeclContext()) ||
923  isInvalidDecl() ||
924  isa<StaticAssertDecl>(this) ||
925  isa<BlockDecl>(this) ||
926  // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
927  // as DeclContext (?).
928  isa<ParmVarDecl>(this) ||
929  // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
930  // AS_none as access specifier.
931  isa<CXXRecordDecl>(this) ||
932  isa<ClassScopeFunctionSpecializationDecl>(this))
933  return true;
934 
935  assert(Access != AS_none &&
936  "Access specifier is AS_none inside a record decl");
937 #endif
938  return true;
939 }
940 
941 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
942 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
943 
944 int64_t Decl::getID() const {
945  return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
946 }
947 
948 const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
949  QualType Ty;
950  if (const auto *D = dyn_cast<ValueDecl>(this))
951  Ty = D->getType();
952  else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
953  Ty = D->getUnderlyingType();
954  else
955  return nullptr;
956 
957  if (Ty->isFunctionPointerType())
958  Ty = Ty->getAs<PointerType>()->getPointeeType();
959  else if (BlocksToo && Ty->isBlockPointerType())
960  Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
961 
962  return Ty->getAs<FunctionType>();
963 }
964 
965 /// Starting at a given context (a Decl or DeclContext), look for a
966 /// code context that is not a closure (a lambda, block, etc.).
967 template <class T> static Decl *getNonClosureContext(T *D) {
968  if (getKind(D) == Decl::CXXMethod) {
969  auto *MD = cast<CXXMethodDecl>(D);
970  if (MD->getOverloadedOperator() == OO_Call &&
971  MD->getParent()->isLambda())
972  return getNonClosureContext(MD->getParent()->getParent());
973  return MD;
974  } else if (auto *FD = dyn_cast<FunctionDecl>(D))
975  return FD;
976  else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
977  return MD;
978  else if (auto *BD = dyn_cast<BlockDecl>(D))
979  return getNonClosureContext(BD->getParent());
980  else if (auto *CD = dyn_cast<CapturedDecl>(D))
981  return getNonClosureContext(CD->getParent());
982  else
983  return nullptr;
984 }
985 
988 }
989 
992 }
993 
994 //===----------------------------------------------------------------------===//
995 // DeclContext Implementation
996 //===----------------------------------------------------------------------===//
997 
999  DeclContextBits.DeclKind = K;
1000  setHasExternalLexicalStorage(false);
1001  setHasExternalVisibleStorage(false);
1002  setNeedToReconcileExternalVisibleStorage(false);
1003  setHasLazyLocalLexicalLookups(false);
1004  setHasLazyExternalLexicalLookups(false);
1005  setUseQualifiedLookup(false);
1006 }
1007 
1008 bool DeclContext::classof(const Decl *D) {
1009  switch (D->getKind()) {
1010 #define DECL(NAME, BASE)
1011 #define DECL_CONTEXT(NAME) case Decl::NAME:
1012 #define DECL_CONTEXT_BASE(NAME)
1013 #include "clang/AST/DeclNodes.inc"
1014  return true;
1015  default:
1016 #define DECL(NAME, BASE)
1017 #define DECL_CONTEXT_BASE(NAME) \
1018  if (D->getKind() >= Decl::first##NAME && \
1019  D->getKind() <= Decl::last##NAME) \
1020  return true;
1021 #include "clang/AST/DeclNodes.inc"
1022  return false;
1023  }
1024 }
1025 
1026 DeclContext::~DeclContext() = default;
1027 
1028 /// Find the parent context of this context that will be
1029 /// used for unqualified name lookup.
1030 ///
1031 /// Generally, the parent lookup context is the semantic context. However, for
1032 /// a friend function the parent lookup context is the lexical context, which
1033 /// is the class in which the friend is declared.
1035  // FIXME: Find a better way to identify friends.
1036  if (isa<FunctionDecl>(this))
1037  if (getParent()->getRedeclContext()->isFileContext() &&
1038  getLexicalParent()->getRedeclContext()->isRecord())
1039  return getLexicalParent();
1040 
1041  return getParent();
1042 }
1043 
1045  const DeclContext *Ctx = this;
1046 
1047  do {
1048  if (Ctx->isClosure())
1049  return cast<BlockDecl>(Ctx);
1050  Ctx = Ctx->getParent();
1051  } while (Ctx);
1052 
1053  return nullptr;
1054 }
1055 
1057  return isNamespace() &&
1058  cast<NamespaceDecl>(this)->isInline();
1059 }
1060 
1062  if (!isNamespace())
1063  return false;
1064 
1065  const auto *ND = cast<NamespaceDecl>(this);
1066  if (ND->isInline()) {
1067  return ND->getParent()->isStdNamespace();
1068  }
1069 
1070  if (!getParent()->getRedeclContext()->isTranslationUnit())
1071  return false;
1072 
1073  const IdentifierInfo *II = ND->getIdentifier();
1074  return II && II->isStr("std");
1075 }
1076 
1078  if (isFileContext())
1079  return false;
1080 
1081  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1082  return true;
1083 
1084  if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1085  if (Record->getDescribedClassTemplate())
1086  return true;
1087 
1088  if (Record->isDependentLambda())
1089  return true;
1090  }
1091 
1092  if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1093  if (Function->getDescribedFunctionTemplate())
1094  return true;
1095 
1096  // Friend function declarations are dependent if their *lexical*
1097  // context is dependent.
1098  if (cast<Decl>(this)->getFriendObjectKind())
1099  return getLexicalParent()->isDependentContext();
1100  }
1101 
1102  // FIXME: A variable template is a dependent context, but is not a
1103  // DeclContext. A context within it (such as a lambda-expression)
1104  // should be considered dependent.
1105 
1106  return getParent() && getParent()->isDependentContext();
1107 }
1108 
1110  if (getDeclKind() == Decl::Enum)
1111  return !cast<EnumDecl>(this)->isScoped();
1112  else if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
1113  return true;
1114 
1115  return false;
1116 }
1117 
1118 static bool isLinkageSpecContext(const DeclContext *DC,
1120  while (DC->getDeclKind() != Decl::TranslationUnit) {
1121  if (DC->getDeclKind() == Decl::LinkageSpec)
1122  return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1123  DC = DC->getLexicalParent();
1124  }
1125  return false;
1126 }
1127 
1130 }
1131 
1133  const DeclContext *DC = this;
1134  while (DC->getDeclKind() != Decl::TranslationUnit) {
1135  if (DC->getDeclKind() == Decl::LinkageSpec &&
1136  cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
1137  return cast<LinkageSpecDecl>(DC);
1138  DC = DC->getLexicalParent();
1139  }
1140  return nullptr;
1141 }
1142 
1145 }
1146 
1147 bool DeclContext::Encloses(const DeclContext *DC) const {
1148  if (getPrimaryContext() != this)
1149  return getPrimaryContext()->Encloses(DC);
1150 
1151  for (; DC; DC = DC->getParent())
1152  if (DC->getPrimaryContext() == this)
1153  return true;
1154  return false;
1155 }
1156 
1158  switch (getDeclKind()) {
1159  case Decl::TranslationUnit:
1160  case Decl::ExternCContext:
1161  case Decl::LinkageSpec:
1162  case Decl::Export:
1163  case Decl::Block:
1164  case Decl::Captured:
1165  case Decl::OMPDeclareReduction:
1166  case Decl::OMPDeclareMapper:
1167  // There is only one DeclContext for these entities.
1168  return this;
1169 
1170  case Decl::Namespace:
1171  // The original namespace is our primary context.
1172  return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1173 
1174  case Decl::ObjCMethod:
1175  return this;
1176 
1177  case Decl::ObjCInterface:
1178  if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1179  if (auto *Def = OID->getDefinition())
1180  return Def;
1181  return this;
1182 
1183  case Decl::ObjCProtocol:
1184  if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1185  if (auto *Def = OPD->getDefinition())
1186  return Def;
1187  return this;
1188 
1189  case Decl::ObjCCategory:
1190  return this;
1191 
1192  case Decl::ObjCImplementation:
1193  case Decl::ObjCCategoryImpl:
1194  return this;
1195 
1196  default:
1197  if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1198  // If this is a tag type that has a definition or is currently
1199  // being defined, that definition is our primary context.
1200  auto *Tag = cast<TagDecl>(this);
1201 
1202  if (TagDecl *Def = Tag->getDefinition())
1203  return Def;
1204 
1205  if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1206  // Note, TagType::getDecl returns the (partial) definition one exists.
1207  TagDecl *PossiblePartialDef = TagTy->getDecl();
1208  if (PossiblePartialDef->isBeingDefined())
1209  return PossiblePartialDef;
1210  } else {
1211  assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1212  }
1213 
1214  return Tag;
1215  }
1216 
1217  assert(getDeclKind() >= Decl::firstFunction &&
1218  getDeclKind() <= Decl::lastFunction &&
1219  "Unknown DeclContext kind");
1220  return this;
1221  }
1222 }
1223 
1224 void
1226  Contexts.clear();
1227 
1228  if (getDeclKind() != Decl::Namespace) {
1229  Contexts.push_back(this);
1230  return;
1231  }
1232 
1233  auto *Self = static_cast<NamespaceDecl *>(this);
1234  for (NamespaceDecl *N = Self->getMostRecentDecl(); N;
1235  N = N->getPreviousDecl())
1236  Contexts.push_back(N);
1237 
1238  std::reverse(Contexts.begin(), Contexts.end());
1239 }
1240 
1241 std::pair<Decl *, Decl *>
1243  bool FieldsAlreadyLoaded) {
1244  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1245  Decl *FirstNewDecl = nullptr;
1246  Decl *PrevDecl = nullptr;
1247  for (auto *D : Decls) {
1248  if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
1249  continue;
1250 
1251  if (PrevDecl)
1252  PrevDecl->NextInContextAndBits.setPointer(D);
1253  else
1254  FirstNewDecl = D;
1255 
1256  PrevDecl = D;
1257  }
1258 
1259  return std::make_pair(FirstNewDecl, PrevDecl);
1260 }
1261 
1262 /// We have just acquired external visible storage, and we already have
1263 /// built a lookup map. For every name in the map, pull in the new names from
1264 /// the external storage.
1265 void DeclContext::reconcileExternalVisibleStorage() const {
1266  assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1267  setNeedToReconcileExternalVisibleStorage(false);
1268 
1269  for (auto &Lookup : *LookupPtr)
1270  Lookup.second.setHasExternalDecls();
1271 }
1272 
1273 /// Load the declarations within this lexical storage from an
1274 /// external source.
1275 /// \return \c true if any declarations were added.
1276 bool
1277 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1278  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1279  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1280 
1281  // Notify that we have a DeclContext that is initializing.
1282  ExternalASTSource::Deserializing ADeclContext(Source);
1283 
1284  // Load the external declarations, if any.
1285  SmallVector<Decl*, 64> Decls;
1286  setHasExternalLexicalStorage(false);
1287  Source->FindExternalLexicalDecls(this, Decls);
1288 
1289  if (Decls.empty())
1290  return false;
1291 
1292  // We may have already loaded just the fields of this record, in which case
1293  // we need to ignore them.
1294  bool FieldsAlreadyLoaded = false;
1295  if (const auto *RD = dyn_cast<RecordDecl>(this))
1296  FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1297 
1298  // Splice the newly-read declarations into the beginning of the list
1299  // of declarations.
1300  Decl *ExternalFirst, *ExternalLast;
1301  std::tie(ExternalFirst, ExternalLast) =
1302  BuildDeclChain(Decls, FieldsAlreadyLoaded);
1303  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1304  FirstDecl = ExternalFirst;
1305  if (!LastDecl)
1306  LastDecl = ExternalLast;
1307  return true;
1308 }
1309 
1312  DeclarationName Name) {
1313  ASTContext &Context = DC->getParentASTContext();
1314  StoredDeclsMap *Map;
1315  if (!(Map = DC->LookupPtr))
1316  Map = DC->CreateStoredDeclsMap(Context);
1317  if (DC->hasNeedToReconcileExternalVisibleStorage())
1318  DC->reconcileExternalVisibleStorage();
1319 
1320  (*Map)[Name].removeExternalDecls();
1321 
1322  return DeclContext::lookup_result();
1323 }
1324 
1327  DeclarationName Name,
1328  ArrayRef<NamedDecl*> Decls) {
1329  ASTContext &Context = DC->getParentASTContext();
1330  StoredDeclsMap *Map;
1331  if (!(Map = DC->LookupPtr))
1332  Map = DC->CreateStoredDeclsMap(Context);
1333  if (DC->hasNeedToReconcileExternalVisibleStorage())
1334  DC->reconcileExternalVisibleStorage();
1335 
1336  StoredDeclsList &List = (*Map)[Name];
1337 
1338  // Clear out any old external visible declarations, to avoid quadratic
1339  // performance in the redeclaration checks below.
1340  List.removeExternalDecls();
1341 
1342  if (!List.isNull()) {
1343  // We have both existing declarations and new declarations for this name.
1344  // Some of the declarations may simply replace existing ones. Handle those
1345  // first.
1347  for (unsigned I = 0, N = Decls.size(); I != N; ++I)
1348  if (List.HandleRedeclaration(Decls[I], /*IsKnownNewer*/false))
1349  Skip.push_back(I);
1350  Skip.push_back(Decls.size());
1351 
1352  // Add in any new declarations.
1353  unsigned SkipPos = 0;
1354  for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1355  if (I == Skip[SkipPos])
1356  ++SkipPos;
1357  else
1358  List.AddSubsequentDecl(Decls[I]);
1359  }
1360  } else {
1361  // Convert the array to a StoredDeclsList.
1362  for (auto *D : Decls) {
1363  if (List.isNull())
1364  List.setOnlyValue(D);
1365  else
1366  List.AddSubsequentDecl(D);
1367  }
1368  }
1369 
1370  return List.getLookupResult();
1371 }
1372 
1374  if (hasExternalLexicalStorage())
1375  LoadLexicalDeclsFromExternalStorage();
1376  return decl_iterator(FirstDecl);
1377 }
1378 
1380  if (hasExternalLexicalStorage())
1381  LoadLexicalDeclsFromExternalStorage();
1382 
1383  return !FirstDecl;
1384 }
1385 
1387  return (D->getLexicalDeclContext() == this &&
1388  (D->NextInContextAndBits.getPointer() || D == LastDecl));
1389 }
1390 
1392  if (hasExternalLexicalStorage())
1393  LoadLexicalDeclsFromExternalStorage();
1394  return containsDecl(D);
1395 }
1396 
1397 /// shouldBeHidden - Determine whether a declaration which was declared
1398 /// within its semantic context should be invisible to qualified name lookup.
1399 static bool shouldBeHidden(NamedDecl *D) {
1400  // Skip unnamed declarations.
1401  if (!D->getDeclName())
1402  return true;
1403 
1404  // Skip entities that can't be found by name lookup into a particular
1405  // context.
1406  if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
1407  D->isTemplateParameter())
1408  return true;
1409 
1410  // Skip friends and local extern declarations unless they're the first
1411  // declaration of the entity.
1412  if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
1413  D != D->getCanonicalDecl())
1414  return true;
1415 
1416  // Skip template specializations.
1417  // FIXME: This feels like a hack. Should DeclarationName support
1418  // template-ids, or is there a better way to keep specializations
1419  // from being visible?
1420  if (isa<ClassTemplateSpecializationDecl>(D))
1421  return true;
1422  if (auto *FD = dyn_cast<FunctionDecl>(D))
1423  if (FD->isFunctionTemplateSpecialization())
1424  return true;
1425 
1426  return false;
1427 }
1428 
1430  assert(D->getLexicalDeclContext() == this &&
1431  "decl being removed from non-lexical context");
1432  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1433  "decl is not in decls list");
1434 
1435  // Remove D from the decl chain. This is O(n) but hopefully rare.
1436  if (D == FirstDecl) {
1437  if (D == LastDecl)
1438  FirstDecl = LastDecl = nullptr;
1439  else
1440  FirstDecl = D->NextInContextAndBits.getPointer();
1441  } else {
1442  for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
1443  assert(I && "decl not found in linked list");
1444  if (I->NextInContextAndBits.getPointer() == D) {
1445  I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1446  if (D == LastDecl) LastDecl = I;
1447  break;
1448  }
1449  }
1450  }
1451 
1452  // Mark that D is no longer in the decl chain.
1453  D->NextInContextAndBits.setPointer(nullptr);
1454 
1455  // Remove D from the lookup table if necessary.
1456  if (isa<NamedDecl>(D)) {
1457  auto *ND = cast<NamedDecl>(D);
1458 
1459  // Do not try to remove the declaration if that is invisible to qualified
1460  // lookup. E.g. template specializations are skipped.
1461  if (shouldBeHidden(ND))
1462  return;
1463 
1464  // Remove only decls that have a name
1465  if (!ND->getDeclName())
1466  return;
1467 
1468  auto *DC = D->getDeclContext();
1469  do {
1470  StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1471  if (Map) {
1472  StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1473  assert(Pos != Map->end() && "no lookup entry for decl");
1474  // Remove the decl only if it is contained.
1475  StoredDeclsList::DeclsTy *Vec = Pos->second.getAsVector();
1476  if ((Vec && is_contained(*Vec, ND)) || Pos->second.getAsDecl() == ND)
1477  Pos->second.remove(ND);
1478  }
1479  } while (DC->isTransparentContext() && (DC = DC->getParent()));
1480  }
1481 }
1482 
1484  assert(D->getLexicalDeclContext() == this &&
1485  "Decl inserted into wrong lexical context");
1486  assert(!D->getNextDeclInContext() && D != LastDecl &&
1487  "Decl already inserted into a DeclContext");
1488 
1489  if (FirstDecl) {
1490  LastDecl->NextInContextAndBits.setPointer(D);
1491  LastDecl = D;
1492  } else {
1493  FirstDecl = LastDecl = D;
1494  }
1495 
1496  // Notify a C++ record declaration that we've added a member, so it can
1497  // update its class-specific state.
1498  if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1499  Record->addedMember(D);
1500 
1501  // If this is a newly-created (not de-serialized) import declaration, wire
1502  // it in to the list of local import declarations.
1503  if (!D->isFromASTFile()) {
1504  if (auto *Import = dyn_cast<ImportDecl>(D))
1505  D->getASTContext().addedLocalImportDecl(Import);
1506  }
1507 }
1508 
1510  addHiddenDecl(D);
1511 
1512  if (auto *ND = dyn_cast<NamedDecl>(D))
1513  ND->getDeclContext()->getPrimaryContext()->
1514  makeDeclVisibleInContextWithFlags(ND, false, true);
1515 }
1516 
1518  addHiddenDecl(D);
1519 
1520  if (auto *ND = dyn_cast<NamedDecl>(D))
1521  ND->getDeclContext()->getPrimaryContext()->
1522  makeDeclVisibleInContextWithFlags(ND, true, true);
1523 }
1524 
1525 /// buildLookup - Build the lookup data structure with all of the
1526 /// declarations in this DeclContext (and any other contexts linked
1527 /// to it or transparent contexts nested within it) and return it.
1528 ///
1529 /// Note that the produced map may miss out declarations from an
1530 /// external source. If it does, those entries will be marked with
1531 /// the 'hasExternalDecls' flag.
1533  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1534 
1535  if (!hasLazyLocalLexicalLookups() &&
1536  !hasLazyExternalLexicalLookups())
1537  return LookupPtr;
1538 
1540  collectAllContexts(Contexts);
1541 
1542  if (hasLazyExternalLexicalLookups()) {
1543  setHasLazyExternalLexicalLookups(false);
1544  for (auto *DC : Contexts) {
1545  if (DC->hasExternalLexicalStorage()) {
1546  bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1547  setHasLazyLocalLexicalLookups(
1548  hasLazyLocalLexicalLookups() | LoadedDecls );
1549  }
1550  }
1551 
1552  if (!hasLazyLocalLexicalLookups())
1553  return LookupPtr;
1554  }
1555 
1556  for (auto *DC : Contexts)
1557  buildLookupImpl(DC, hasExternalVisibleStorage());
1558 
1559  // We no longer have any lazy decls.
1560  setHasLazyLocalLexicalLookups(false);
1561  return LookupPtr;
1562 }
1563 
1564 /// buildLookupImpl - Build part of the lookup data structure for the
1565 /// declarations contained within DCtx, which will either be this
1566 /// DeclContext, a DeclContext linked to it, or a transparent context
1567 /// nested within it.
1568 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1569  for (auto *D : DCtx->noload_decls()) {
1570  // Insert this declaration into the lookup structure, but only if
1571  // it's semantically within its decl context. Any other decls which
1572  // should be found in this context are added eagerly.
1573  //
1574  // If it's from an AST file, don't add it now. It'll get handled by
1575  // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1576  // in C++, we do not track external visible decls for the TU, so in
1577  // that case we need to collect them all here.
1578  if (auto *ND = dyn_cast<NamedDecl>(D))
1579  if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
1580  (!ND->isFromASTFile() ||
1581  (isTranslationUnit() &&
1582  !getParentASTContext().getLangOpts().CPlusPlus)))
1583  makeDeclVisibleInContextImpl(ND, Internal);
1584 
1585  // If this declaration is itself a transparent declaration context
1586  // or inline namespace, add the members of this declaration of that
1587  // context (recursively).
1588  if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1589  if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
1590  buildLookupImpl(InnerCtx, Internal);
1591  }
1592 }
1593 
1594 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1595 
1598  assert(getDeclKind() != Decl::LinkageSpec &&
1599  getDeclKind() != Decl::Export &&
1600  "should not perform lookups into transparent contexts");
1601 
1602  const DeclContext *PrimaryContext = getPrimaryContext();
1603  if (PrimaryContext != this)
1604  return PrimaryContext->lookup(Name);
1605 
1606  // If we have an external source, ensure that any later redeclarations of this
1607  // context have been loaded, since they may add names to the result of this
1608  // lookup (or add external visible storage).
1609  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1610  if (Source)
1611  (void)cast<Decl>(this)->getMostRecentDecl();
1612 
1613  if (hasExternalVisibleStorage()) {
1614  assert(Source && "external visible storage but no external source?");
1615 
1616  if (hasNeedToReconcileExternalVisibleStorage())
1617  reconcileExternalVisibleStorage();
1618 
1619  StoredDeclsMap *Map = LookupPtr;
1620 
1621  if (hasLazyLocalLexicalLookups() ||
1622  hasLazyExternalLexicalLookups())
1623  // FIXME: Make buildLookup const?
1624  Map = const_cast<DeclContext*>(this)->buildLookup();
1625 
1626  if (!Map)
1627  Map = CreateStoredDeclsMap(getParentASTContext());
1628 
1629  // If we have a lookup result with no external decls, we are done.
1630  std::pair<StoredDeclsMap::iterator, bool> R =
1631  Map->insert(std::make_pair(Name, StoredDeclsList()));
1632  if (!R.second && !R.first->second.hasExternalDecls())
1633  return R.first->second.getLookupResult();
1634 
1635  if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
1636  if (StoredDeclsMap *Map = LookupPtr) {
1637  StoredDeclsMap::iterator I = Map->find(Name);
1638  if (I != Map->end())
1639  return I->second.getLookupResult();
1640  }
1641  }
1642 
1643  return {};
1644  }
1645 
1646  StoredDeclsMap *Map = LookupPtr;
1647  if (hasLazyLocalLexicalLookups() ||
1648  hasLazyExternalLexicalLookups())
1649  Map = const_cast<DeclContext*>(this)->buildLookup();
1650 
1651  if (!Map)
1652  return {};
1653 
1654  StoredDeclsMap::iterator I = Map->find(Name);
1655  if (I == Map->end())
1656  return {};
1657 
1658  return I->second.getLookupResult();
1659 }
1660 
1663  assert(getDeclKind() != Decl::LinkageSpec &&
1664  getDeclKind() != Decl::Export &&
1665  "should not perform lookups into transparent contexts");
1666 
1667  DeclContext *PrimaryContext = getPrimaryContext();
1668  if (PrimaryContext != this)
1669  return PrimaryContext->noload_lookup(Name);
1670 
1671  loadLazyLocalLexicalLookups();
1672  StoredDeclsMap *Map = LookupPtr;
1673  if (!Map)
1674  return {};
1675 
1676  StoredDeclsMap::iterator I = Map->find(Name);
1677  return I != Map->end() ? I->second.getLookupResult()
1678  : lookup_result();
1679 }
1680 
1681 // If we have any lazy lexical declarations not in our lookup map, add them
1682 // now. Don't import any external declarations, not even if we know we have
1683 // some missing from the external visible lookups.
1684 void DeclContext::loadLazyLocalLexicalLookups() {
1685  if (hasLazyLocalLexicalLookups()) {
1687  collectAllContexts(Contexts);
1688  for (auto *Context : Contexts)
1689  buildLookupImpl(Context, hasExternalVisibleStorage());
1690  setHasLazyLocalLexicalLookups(false);
1691  }
1692 }
1693 
1695  SmallVectorImpl<NamedDecl *> &Results) {
1696  Results.clear();
1697 
1698  // If there's no external storage, just perform a normal lookup and copy
1699  // the results.
1700  if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
1701  lookup_result LookupResults = lookup(Name);
1702  Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1703  return;
1704  }
1705 
1706  // If we have a lookup table, check there first. Maybe we'll get lucky.
1707  // FIXME: Should we be checking these flags on the primary context?
1708  if (Name && !hasLazyLocalLexicalLookups() &&
1709  !hasLazyExternalLexicalLookups()) {
1710  if (StoredDeclsMap *Map = LookupPtr) {
1711  StoredDeclsMap::iterator Pos = Map->find(Name);
1712  if (Pos != Map->end()) {
1713  Results.insert(Results.end(),
1714  Pos->second.getLookupResult().begin(),
1715  Pos->second.getLookupResult().end());
1716  return;
1717  }
1718  }
1719  }
1720 
1721  // Slow case: grovel through the declarations in our chain looking for
1722  // matches.
1723  // FIXME: If we have lazy external declarations, this will not find them!
1724  // FIXME: Should we CollectAllContexts and walk them all here?
1725  for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
1726  if (auto *ND = dyn_cast<NamedDecl>(D))
1727  if (ND->getDeclName() == Name)
1728  Results.push_back(ND);
1729  }
1730 }
1731 
1733  DeclContext *Ctx = this;
1734 
1735  // In C, a record type is the redeclaration context for its fields only. If
1736  // we arrive at a record context after skipping anything else, we should skip
1737  // the record as well. Currently, this means skipping enumerations because
1738  // they're the only transparent context that can exist within a struct or
1739  // union.
1740  bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1741  !getParentASTContext().getLangOpts().CPlusPlus;
1742 
1743  // Skip through contexts to get to the redeclaration context. Transparent
1744  // contexts are always skipped.
1745  while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
1746  Ctx = Ctx->getParent();
1747  return Ctx;
1748 }
1749 
1751  DeclContext *Ctx = this;
1752  // Skip through non-namespace, non-translation-unit contexts.
1753  while (!Ctx->isFileContext())
1754  Ctx = Ctx->getParent();
1755  return Ctx->getPrimaryContext();
1756 }
1757 
1759  // Loop until we find a non-record context.
1760  RecordDecl *OutermostRD = nullptr;
1761  DeclContext *DC = this;
1762  while (DC->isRecord()) {
1763  OutermostRD = cast<RecordDecl>(DC);
1764  DC = DC->getLexicalParent();
1765  }
1766  return OutermostRD;
1767 }
1768 
1770  // For non-file contexts, this is equivalent to Equals.
1771  if (!isFileContext())
1772  return O->Equals(this);
1773 
1774  do {
1775  if (O->Equals(this))
1776  return true;
1777 
1778  const auto *NS = dyn_cast<NamespaceDecl>(O);
1779  if (!NS || !NS->isInline())
1780  break;
1781  O = NS->getParent();
1782  } while (O);
1783 
1784  return false;
1785 }
1786 
1788  DeclContext *PrimaryDC = this->getPrimaryContext();
1789  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1790  // If the decl is being added outside of its semantic decl context, we
1791  // need to ensure that we eagerly build the lookup information for it.
1792  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1793 }
1794 
1795 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1796  bool Recoverable) {
1797  assert(this == getPrimaryContext() && "expected a primary DC");
1798 
1799  if (!isLookupContext()) {
1800  if (isTransparentContext())
1801  getParent()->getPrimaryContext()
1802  ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1803  return;
1804  }
1805 
1806  // Skip declarations which should be invisible to name lookup.
1807  if (shouldBeHidden(D))
1808  return;
1809 
1810  // If we already have a lookup data structure, perform the insertion into
1811  // it. If we might have externally-stored decls with this name, look them
1812  // up and perform the insertion. If this decl was declared outside its
1813  // semantic context, buildLookup won't add it, so add it now.
1814  //
1815  // FIXME: As a performance hack, don't add such decls into the translation
1816  // unit unless we're in C++, since qualified lookup into the TU is never
1817  // performed.
1818  if (LookupPtr || hasExternalVisibleStorage() ||
1819  ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
1820  (getParentASTContext().getLangOpts().CPlusPlus ||
1821  !isTranslationUnit()))) {
1822  // If we have lazily omitted any decls, they might have the same name as
1823  // the decl which we are adding, so build a full lookup table before adding
1824  // this decl.
1825  buildLookup();
1826  makeDeclVisibleInContextImpl(D, Internal);
1827  } else {
1828  setHasLazyLocalLexicalLookups(true);
1829  }
1830 
1831  // If we are a transparent context or inline namespace, insert into our
1832  // parent context, too. This operation is recursive.
1833  if (isTransparentContext() || isInlineNamespace())
1834  getParent()->getPrimaryContext()->
1835  makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1836 
1837  auto *DCAsDecl = cast<Decl>(this);
1838  // Notify that a decl was made visible unless we are a Tag being defined.
1839  if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
1840  if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1841  L->AddedVisibleDecl(this, D);
1842 }
1843 
1844 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1845  // Find or create the stored declaration map.
1846  StoredDeclsMap *Map = LookupPtr;
1847  if (!Map) {
1848  ASTContext *C = &getParentASTContext();
1849  Map = CreateStoredDeclsMap(*C);
1850  }
1851 
1852  // If there is an external AST source, load any declarations it knows about
1853  // with this declaration's name.
1854  // If the lookup table contains an entry about this name it means that we
1855  // have already checked the external source.
1856  if (!Internal)
1857  if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1858  if (hasExternalVisibleStorage() &&
1859  Map->find(D->getDeclName()) == Map->end())
1860  Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1861 
1862  // Insert this declaration into the map.
1863  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1864 
1865  if (Internal) {
1866  // If this is being added as part of loading an external declaration,
1867  // this may not be the only external declaration with this name.
1868  // In this case, we never try to replace an existing declaration; we'll
1869  // handle that when we finalize the list of declarations for this name.
1870  DeclNameEntries.setHasExternalDecls();
1871  DeclNameEntries.AddSubsequentDecl(D);
1872  return;
1873  }
1874 
1875  if (DeclNameEntries.isNull()) {
1876  DeclNameEntries.setOnlyValue(D);
1877  return;
1878  }
1879 
1880  if (DeclNameEntries.HandleRedeclaration(D, /*IsKnownNewer*/!Internal)) {
1881  // This declaration has replaced an existing one for which
1882  // declarationReplaces returns true.
1883  return;
1884  }
1885 
1886  // Put this declaration into the appropriate slot.
1887  DeclNameEntries.AddSubsequentDecl(D);
1888 }
1889 
1891  return cast<UsingDirectiveDecl>(*I);
1892 }
1893 
1894 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1895 /// this context.
1897  // FIXME: Use something more efficient than normal lookup for using
1898  // directives. In C++, using directives are looked up more than anything else.
1899  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1900  return udir_range(Result.begin(), Result.end());
1901 }
1902 
1903 //===----------------------------------------------------------------------===//
1904 // Creation and Destruction of StoredDeclsMaps. //
1905 //===----------------------------------------------------------------------===//
1906 
1907 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1908  assert(!LookupPtr && "context already has a decls map");
1909  assert(getPrimaryContext() == this &&
1910  "creating decls map on non-primary context");
1911 
1912  StoredDeclsMap *M;
1913  bool Dependent = isDependentContext();
1914  if (Dependent)
1915  M = new DependentStoredDeclsMap();
1916  else
1917  M = new StoredDeclsMap();
1918  M->Previous = C.LastSDM;
1919  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1920  LookupPtr = M;
1921  return M;
1922 }
1923 
1924 void ASTContext::ReleaseDeclContextMaps() {
1925  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1926  // pointer because the subclass doesn't add anything that needs to
1927  // be deleted.
1928  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1929 }
1930 
1931 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1932  while (Map) {
1933  // Advance the iteration before we invalidate memory.
1934  llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1935 
1936  if (Dependent)
1937  delete static_cast<DependentStoredDeclsMap*>(Map);
1938  else
1939  delete Map;
1940 
1941  Map = Next.getPointer();
1942  Dependent = Next.getInt();
1943  }
1944 }
1945 
1948  const PartialDiagnostic &PDiag) {
1949  assert(Parent->isDependentContext()
1950  && "cannot iterate dependent diagnostics of non-dependent context");
1951  Parent = Parent->getPrimaryContext();
1952  if (!Parent->LookupPtr)
1953  Parent->CreateStoredDeclsMap(C);
1954 
1955  auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
1956 
1957  // Allocate the copy of the PartialDiagnostic via the ASTContext's
1958  // BumpPtrAllocator, rather than the ASTContext itself.
1959  PartialDiagnostic::Storage *DiagStorage = nullptr;
1960  if (PDiag.hasStorage())
1961  DiagStorage = new (C) PartialDiagnostic::Storage;
1962 
1963  auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
1964 
1965  // TODO: Maybe we shouldn't reverse the order during insertion.
1966  DD->NextDiagnostic = Map->FirstDiagnostic;
1967  Map->FirstDiagnostic = DD;
1968 
1969  return DD;
1970 }
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition: DeclBase.cpp:466
Defines the clang::ASTContext interface.
Represents a function declaration or definition.
Definition: Decl.h:1737
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
void localUncachedLookup(DeclarationName Name, SmallVectorImpl< NamedDecl *> &Results)
A simplistic name lookup mechanism that performs name lookup into this declaration context without co...
Definition: DeclBase.cpp:1694
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled...
Definition: TargetInfo.h:1228
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:874
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:751
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2549
QualType getPointeeType() const
Definition: Type.h:2562
static bool shouldBeHidden(NamedDecl *D)
shouldBeHidden - Determine whether a declaration which was declared within its semantic context shoul...
Definition: DeclBase.cpp:1399
A (possibly-)qualified type.
Definition: Type.h:639
bool isBlockPointerType() const
Definition: Type.h:6316
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:3923
const char * getDeclKindName() const
Definition: DeclBase.cpp:122
llvm::PointerIntPair< Decl *, 2, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:243
void AddSubsequentDecl(NamedDecl *D)
AddSubsequentDecl - This is called on the second and later decl when it is not a redeclaration to mer...
virtual void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl *> &Result)
Finds all declarations lexically contained within the given DeclContext, after applying an optional f...
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c.h:67
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:855
bool isClosure() const
Definition: DeclBase.h:1790
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:978
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:478
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecDecl::LanguageIDs ID)
Definition: DeclBase.cpp:1118
Stmt - This represents one statement.
Definition: Stmt.h:65
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3367
C Language Family Type Representation.
const char * getDeclKindName() const
Definition: DeclBase.cpp:154
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:34
static void add(Kind k)
Definition: DeclBase.cpp:192
Defines the C++ template declaration subclasses.
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:952
Defines types useful for describing an Objective-C runtime.
Represent a C++ namespace.
Definition: Decl.h:514
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:689
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:791
static Decl * getNonClosureContext(T *D)
Starting at a given context (a Decl or DeclContext), look for a code context that is not a closure (a...
Definition: DeclBase.cpp:967
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:253
unsigned Access
Access - Used by C++ decls for the access specifier.
Definition: DeclBase.h:324
bool HandleRedeclaration(NamedDecl *D, bool IsKnownNewer)
HandleRedeclaration - If this is a redeclaration of an existing decl, replace the old one with D and ...
bool hasOwningModule() const
Is this declaration owned by some module?
Definition: DeclBase.h:746
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:379
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6768
bool hasLocalOwningModuleStorage() const
Definition: DeclBase.cpp:118
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1128
bool isInvalidDecl() const
Definition: DeclBase.h:545
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition: DeclBase.cpp:433
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:210
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1429
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
Definition: ObjCRuntime.h:361
Types, declared with &#39;struct foo&#39;, typedefs, etc.
Definition: DeclBase.h:131
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:334
Represents a struct/union/class.
Definition: Decl.h:3592
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1147
One of these records is kept for each identifier that is lexed.
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:346
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static DeclContextLookupResult SetExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name, ArrayRef< NamedDecl *> Decls)
Definition: DeclBase.cpp:1326
QualType getPointeeType() const
Definition: Type.h:2666
void print(raw_ostream &OS, const SourceManager &SM) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1186
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1881
Describes a module or submodule.
Definition: Module.h:64
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)
Update an out-of-date identifier.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1750
virtual bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name)
Find all declarations with the given name in the given context, and add them to the context by callin...
Namespaces, declared with &#39;namespace foo {}&#39;.
Definition: DeclBase.h:141
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:421
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:778
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1532
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
Definition: DeclBase.cpp:1311
ASTContext & getASTContext() const
Definition: Decl.h:119
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:820
Labels, declared with &#39;x:&#39; and referenced with &#39;goto x&#39;.
Definition: DeclBase.h:118
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:738
Represents a linkage specification.
Definition: DeclCXX.h:2833
Ordinary names.
Definition: DeclBase.h:145
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:869
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1517
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1597
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:73
NodeId Parent
Definition: ASTDiff.cpp:191
Decl * getNextDeclInContext()
Definition: DeclBase.h:427
bool canBeWeakImported(bool &IsDefinition) const
Determines whether this symbol can be weak-imported, e.g., whether it would be well-formed to add the...
Definition: DeclBase.cpp:638
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:1896
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:572
Objective C @protocol.
Definition: DeclBase.h:148
llvm::iterator_range< udir_iterator > udir_range
Definition: DeclBase.h:2287
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition: DeclBase.h:2014
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl&#39;s underlying type to extract a FunctionType when possible. ...
Definition: DeclBase.cpp:948
void removeExternalDecls()
Remove any declarations which were imported from an external AST source.
int64_t getID() const
Definition: DeclBase.cpp:944
bool isInlineNamespace() const
Definition: DeclBase.cpp:1056
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1773
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3857
const Attr * getDefiningAttr() const
Return this declaration&#39;s defining attribute if it has one.
Definition: DeclBase.cpp:458
Defines the clang::LangOptions interface.
std::string Label
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition: DeclBase.cpp:687
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1386
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:131
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:179
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1769
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:967
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1052
bool isFileContext() const
Definition: DeclBase.h:1827
DeclContext * getDeclContext()
Definition: DeclBase.h:430
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don&#39;t attempt to retr...
Definition: DeclBase.cpp:1662
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:990
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2431
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:200
bool containsDeclAndLoad(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1391
This declaration is an OpenMP user defined mapper.
Definition: DeclBase.h:182
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
bool isFunctionOrMethod() const
Definition: DeclBase.h:1809
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:206
This declaration has an owning module, and is visible when that module is imported.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:383
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1757
void collectAllContexts(SmallVectorImpl< DeclContext *> &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context...
Definition: DeclBase.cpp:1225
SourceLocation getEnd() const
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1077
The result type of a method or function.
const SourceManager & SM
Definition: Format.cpp:1568
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:294
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:29
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:1103
virtual void DeclarationMarkedUsed(const Decl *D)
A declaration is marked used which was not previously marked used.
bool decls_empty() const
Definition: DeclBase.cpp:1379
AttrVec & getAttrs()
Definition: DeclBase.h:482
bool hasAttrs() const
Definition: DeclBase.h:476
Abstract interface for external sources of AST nodes.
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:225
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1750
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1787
DeclContext::lookup_result getLookupResult()
getLookupResult - Return an array of all the decls that this list represents.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:217
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1224
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:624
Encodes a location in the source.
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:137
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:783
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1373
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3063
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:375
bool isStdNamespace() const
Definition: DeclBase.cpp:1061
This file defines OpenMP nodes for declarative directives.
void print(raw_ostream &OS) const override
Definition: DeclBase.cpp:267
DeclContext(Decl::Kind K)
Definition: DeclBase.cpp:998
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:694
UsingDirectiveDecl * operator*() const
Definition: DeclBase.cpp:1890
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:396
An array of decls optimized for the common case of only containing one entry.
void dropAttrs()
Definition: DeclBase.cpp:820
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:668
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:668
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1963
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:940
Dataflow Directional Tag Classes.
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:62
bool isValid() const
Return true if this is a valid SourceLocation object.
virtual Module * getModule(unsigned ID)
Retrieve the module that corresponds to the given module ID.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:398
bool isRecord() const
Definition: DeclBase.h:1836
attr_range attrs() const
Definition: DeclBase.h:493
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1758
The name of a declaration.
Kind getKind() const
Definition: DeclBase.h:424
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:986
Tags, declared with &#39;struct foo;&#39; and referenced with &#39;struct foo&#39;.
Definition: DeclBase.h:126
llvm::BumpPtrAllocator & getAllocator() const
Definition: ASTContext.h:664
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1082
A dependently-generated diagnostic.
Pointer to a block type.
Definition: Type.h:2651
static DependentDiagnostic * Create(ASTContext &Context, DeclContext *Parent, AccessNonce _, SourceLocation Loc, bool IsMemberAccess, AccessSpecifier AS, NamedDecl *TargetDecl, CXXRecordDecl *NamingClass, QualType BaseObjectType, const PartialDiagnostic &PDiag)
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:565
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2844
T * getAttr() const
Definition: DeclBase.h:530
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:706
virtual ~Decl()
void setOnlyValue(NamedDecl *ND)
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1732
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1132
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1509
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:411
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1097
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Defines the clang::SourceLocation class and associated facilities.
DeclContextLookupResult lookup_result
Definition: DeclBase.h:2210
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1483
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl *> Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1242
bool isInherited() const
Definition: Attr.h:97
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1034
void addAttr(Attr *A)
Definition: DeclBase.cpp:827
static bool classof(const Decl *D)
Definition: DeclBase.cpp:1008
Defines the clang::TargetInfo interface.
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1786
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3654
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:90
__DEVICE__ int max(int __a, int __b)
The top declaration context.
Definition: Decl.h:107
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
Definition: DeclBase.cpp:1931
static void PrintStats()
Definition: DeclBase.cpp:168
NamedDecl * getMostRecentDecl()
Definition: Decl.h:445
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1157
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Definition: LangOptions.h:267
static void EnableStatistics()
Definition: DeclBase.cpp:164
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:298
This represents a decl that may have a name.
Definition: Decl.h:248
bool isTranslationUnit() const
Definition: DeclBase.h:1832
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:460
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration...
Definition: DeclBase.cpp:229
Represents C++ using-directive.
Definition: DeclCXX.h:2923
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity, such as &#39;alias&#39; or &#39;ifunc&#39;.
Definition: DeclBase.cpp:454
bool isFunctionPointerType() const
Definition: Type.h:6332
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
bool isInStdNamespace() const
Definition: DeclBase.cpp:356
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:360
const LangOptions & getLangOpts() const
Definition: ASTContext.h:706
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1044
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1143
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:242
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:893
Attr - This represents one attribute.
Definition: Attr.h:43
static AvailabilityResult CheckAvailability(ASTContext &Context, const AvailabilityAttr *A, std::string *Message, VersionTuple EnclosingVersion)
Determine the availability of the given declaration based on the target platform. ...
Definition: DeclBase.cpp:488
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3188
This declaration is a using declaration.
Definition: DeclBase.h:164
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:1109