clang  6.0.0svn
DeclBase.cpp
Go to the documentation of this file.
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"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.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"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/Type.h"
31 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/TargetInfo.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 
53 using 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 
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 
73 void *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 
93 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94  DeclContext *Parent, std::size_t Extra) {
95  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
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 
114 Module *Decl::getOwningModuleSlow() const {
115  assert(isFromASTFile() && "Not from AST file?");
117 }
118 
121 }
122 
123 const char *Decl::getDeclKindName() const {
124  switch (DeclKind) {
125  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
126 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127 #define ABSTRACT_DECL(DECL)
128 #include "clang/AST/DeclNodes.inc"
129  }
130 }
131 
132 void Decl::setInvalidDecl(bool Invalid) {
133  InvalidDecl = Invalid;
134  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
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.
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 
155 const char *DeclContext::getDeclKindName() const {
156  switch (DeclKind) {
157  default: llvm_unreachable("Declaration context not in DeclNodes.inc!");
158 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
159 #define ABSTRACT_DECL(DECL)
160 #include "clang/AST/DeclNodes.inc"
161  }
162 }
163 
164 bool Decl::StatisticsEnabled = false;
166  StatisticsEnabled = true;
167 }
168 
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 
193 void 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 
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 
213 bool Decl::isParameterPack() const {
214  if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this))
215  return Parm->isParameterPack();
216 
217  return isTemplateParameterPack();
218 }
219 
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 
228 bool Decl::isTemplateDecl() const {
229  return isa<TemplateDecl>(this);
230 }
231 
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 
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 
257 void 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.
282 Decl::~Decl() = default;
283 
285  DeclCtx = DC;
286 }
287 
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(
308  getOwningModule()) &&
309  "hidden declaration has no owning module");
310 }
311 
312 void 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 
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 
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 
347  return getDeclContext()->isStdNamespace();
348 }
349 
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!");
356 
357  while (!DC->isTranslationUnit()) {
358  DC = DC->getParent();
359  assert(DC && "This decl is not contained in a translation unit!");
360  }
361 
362  return cast<TranslationUnitDecl>(DC);
363 }
364 
367 }
368 
371 }
372 
373 unsigned 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 
386 bool 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 
402  if (isUsed(false))
403  return;
404 
405  if (C.getASTMutationListener())
407 
408  setIsUsed();
409 }
410 
411 bool 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 
423 bool 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 
439 ExternalSourceSymbolAttr *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 
460 bool Decl::hasDefiningAttr() const {
461  return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>();
462 }
463 
464 const 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 
472 static 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.
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 
582  VersionTuple EnclosingVersion) const {
583  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
584  return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion);
585 
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)) {
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 
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 
642 bool 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) &&
664  return true;
665 
666  // Nothing else.
667  } else {
668  return false;
669  }
670 }
671 
672 bool 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,
684  return true;
685  }
686  }
687 
688  return false;
689 }
690 
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:
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!");
807 }
808 
809 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
810  assert(!HasAttrs && "Decl already contains attrs.");
811 
812  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
813  assert(AttrBlank.empty() && "HasAttrs was wrong?");
814 
815  AttrBlank = attrs;
816  HasAttrs = true;
817 }
818 
820  if (!HasAttrs) return;
821 
822  HasAttrs = false;
824 }
825 
826 const AttrVec &Decl::getAttrs() const {
827  assert(HasAttrs && "No attrs to get!");
828  return getASTContext().getDeclAttrs(this);
829 }
830 
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");
847  }
848 }
849 
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");
866  }
867 }
868 
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 
885 bool 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 &&
910  "Access specifier is AS_none inside a record decl");
911 #endif
912  return true;
913 }
914 
915 static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
916 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
917 
918 const 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.).
937 template <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 
959 }
960 
963 }
964 
965 //===----------------------------------------------------------------------===//
966 // DeclContext Implementation
967 //===----------------------------------------------------------------------===//
968 
969 bool 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 
987 DeclContext::~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.
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 
1006  return isNamespace() &&
1007  cast<NamespaceDecl>(this)->isInline();
1008 }
1009 
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 
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 
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 
1067 static bool isLinkageSpecContext(const DeclContext *DC,
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 
1079 }
1080 
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 
1094 }
1095 
1096 bool 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 
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()));
1158  }
1159 
1160  return Tag;
1161  }
1162 
1163  assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction &&
1164  "Unknown DeclContext kind");
1165  return this;
1166  }
1167 }
1168 
1169 void
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 
1186 std::pair<Decl *, Decl *>
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.
1211 void DeclContext::reconcileExternalVisibleStorage() const {
1212  assert(NeedToReconcileExternalVisibleStorage && LookupPtr);
1213  NeedToReconcileExternalVisibleStorage = false;
1214 
1215  for (auto &Lookup : *LookupPtr)
1216  Lookup.second.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.
1222 bool
1223 DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1224  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1225  assert(hasExternalLexicalStorage() && Source && "No external storage?");
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 
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 
1273  DeclarationName Name,
1274  ArrayRef<NamedDecl*> Decls) {
1275  ASTContext &Context = DC->getParentASTContext();
1276  StoredDeclsMap *Map;
1277  if (!(Map = DC->LookupPtr))
1278  Map = DC->CreateStoredDeclsMap(Context);
1279  if (DC->NeedToReconcileExternalVisibleStorage)
1280  DC->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.
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.
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 
1321  if (hasExternalLexicalStorage())
1322  LoadLexicalDeclsFromExternalStorage();
1323  return decl_iterator(FirstDecl);
1324 }
1325 
1327  if (hasExternalLexicalStorage())
1328  LoadLexicalDeclsFromExternalStorage();
1329 
1330  return !FirstDecl;
1331 }
1332 
1334  return (D->getLexicalDeclContext() == this &&
1335  (D->NextInContextAndBits.getPointer() || D == LastDecl));
1336 }
1337 
1339  assert(D->getLexicalDeclContext() == this &&
1340  "decl being removed from non-lexical context");
1341  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1342  "decl is not in decls list");
1343 
1344  // Remove D from the decl chain. This is O(n) but hopefully rare.
1345  if (D == FirstDecl) {
1346  if (D == LastDecl)
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");
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");
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 
1385  assert(D->getLexicalDeclContext() == this &&
1386  "Decl inserted into wrong lexical context");
1387  assert(!D->getNextDeclInContext() && D != LastDecl &&
1388  "Decl already inserted into a DeclContext");
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 
1411  addHiddenDecl(D);
1412 
1413  if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
1414  ND->getDeclContext()->getPrimaryContext()->
1415  makeDeclVisibleInContextWithFlags(ND, false, true);
1416 }
1417 
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.
1428 static 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.
1460  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1461 
1462  if (!HasLazyLocalLexicalLookups && !HasLazyExternalLexicalLookups)
1463  return LookupPtr;
1464 
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.
1492 void 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 
1518 NamedDecl *const DeclContextLookupResult::SingleElementDummyList = nullptr;
1519 
1522  assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1523  "should not perform lookups into transparent contexts");
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?");
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 
1584  assert(DeclKind != Decl::LinkageSpec && DeclKind != Decl::Export &&
1585  "should not perform lookups into transparent contexts");
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) {
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 
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 
1649  DeclContext *Ctx = this;
1650  // Skip through transparent contexts.
1651  while (Ctx->isTransparentContext())
1652  Ctx = Ctx->getParent();
1653  return Ctx;
1654 }
1655 
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 
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 
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 
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 
1701 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1702  bool Recoverable) {
1703  assert(this == getPrimaryContext() && "expected a primary DC");
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 
1750 void 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 
1797  return cast<UsingDirectiveDecl>(*I);
1798 }
1799 
1800 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1801 /// this context.
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 
1813 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1814  assert(!LookupPtr && "context already has a decls map");
1815  assert(getPrimaryContext() == this &&
1816  "creating decls map on non-primary context");
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 
1830 void 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 
1837 void 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 
1854  const PartialDiagnostic &PDiag) {
1855  assert(Parent->isDependentContext()
1856  && "cannot iterate dependent diagnostics of non-dependent context");
1857  Parent = Parent->getPrimaryContext();
1858  if (!Parent->LookupPtr)
1859  Parent->CreateStoredDeclsMap(C);
1860 
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 }
static StringRef getRealizedPlatform(const AvailabilityAttr *A, const ASTContext &Context)
Definition: DeclBase.cpp:472
Defines the clang::ASTContext interface.
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
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:1611
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled...
Definition: TargetInfo.h:999
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:850
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:2285
QualType getPointeeType() const
Definition: Type.h:2298
static bool shouldBeHidden(NamedDecl *D)
shouldBeHidden - Determine whether a declaration which was declared within its semantic context shoul...
Definition: DeclBase.cpp:1428
A (possibly-)qualified type.
Definition: Type.h:653
bool isBlockPointerType() const
Definition: Type.h:5952
TagDecl * getDefinition() const
getDefinition - Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:3725
const char * getDeclKindName() const
Definition: DeclBase.cpp:123
llvm::PointerIntPair< Decl *, 2, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:239
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
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:60
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:831
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:974
static bool isLinkageSpecContext(const DeclContext *DC, LinkageSpecDecl::LanguageIDs ID)
Definition: DeclBase.cpp:1067
Stmt - This represents one statement.
Definition: Stmt.h:66
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3058
C Language Family Type Representation.
const char * getDeclKindName() const
Definition: DeclBase.cpp:155
const Type * getTypeForDecl() const
Definition: Decl.h:2778
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:54
static void add(Kind k)
Definition: DeclBase.cpp:193
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:948
Defines types useful for describing an Objective-C runtime.
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:506
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
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:937
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:243
unsigned Access
Access - Used by C++ decls for the access specifier.
Definition: DeclBase.h:319
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
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:807
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:369
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6307
bool hasLocalOwningModuleStorage() const
Definition: DeclBase.cpp:119
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1077
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
bool isInvalidDecl() const
Definition: DeclBase.h:546
ExternalSourceSymbolAttr * getExternalSourceSymbolAttr() const
Looks on this and related declarations for an applicable external source symbol attribute.
Definition: DeclBase.cpp:439
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:213
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1514
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1338
bool hasWeakClassImport() const
Does this runtime support weakly importing classes?
Definition: ObjCRuntime.h:271
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
Types, declared with &#39;struct foo&#39;, typedefs, etc.
Definition: DeclBase.h:130
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:324
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3482
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1096
One of these records is kept for each identifier that is lexed.
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:336
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:1272
QualType getPointeeType() const
Definition: Type.h:2402
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:149
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:567
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1178
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1451
Describes a module or submodule.
Definition: Module.h:65
virtual void updateOutOfDateIdentifier(IdentifierInfo &II)
Update an out-of-date identifier.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1656
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:140
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:411
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:1459
static DeclContextLookupResult SetNoExternalVisibleDeclsForName(const DeclContext *DC, DeclarationName Name)
Definition: DeclBase.cpp:1257
ASTContext & getASTContext() const
Definition: Decl.h:119
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1152
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2229
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
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:117
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:738
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3860
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
Represents a linkage specification.
Definition: DeclCXX.h:2743
A binding in a decomposition declaration.
Definition: DeclCXX.h:3718
bool isExported() const
Whether this declaration is exported (by virtue of being lexically within an ExportDecl or by being a...
Definition: DeclBase.cpp:423
Ordinary names.
Definition: DeclBase.h:144
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:865
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1418
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1521
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:72
NodeId Parent
Definition: ASTDiff.cpp:192
Decl * getNextDeclInContext()
Definition: DeclBase.h:422
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:642
udir_range using_directives() const
Returns iterator range [First, Last) of UsingDirectiveDecls stored within this context.
Definition: DeclBase.cpp:1802
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3168
Objective C @protocol.
Definition: DeclBase.h:147
llvm::iterator_range< udir_iterator > udir_range
Definition: DeclBase.h:1851
decl_range noload_decls() const
noload_decls_begin/end - Iterate over the declarations stored in this context that are currently load...
Definition: DeclBase.h:1584
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl&#39;s underlying type to extract a FunctionType when possible. ...
Definition: DeclBase.cpp:918
void removeExternalDecls()
Remove any declarations which were imported from an external AST source.
bool isInlineNamespace() const
Definition: DeclBase.cpp:1005
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1347
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3689
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:628
const Attr * getDefiningAttr() const
Return this declaration&#39;s defining attribute if it has one.
Definition: DeclBase.cpp:464
Defines the clang::LangOptions interface.
std::string Label
static unsigned getIdentifierNamespaceForKind(Kind DK)
Definition: DeclBase.cpp:691
const FunctionProtoType * T
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1333
Declaration of a template type parameter.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:178
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:1675
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:963
bool isFileContext() const
Definition: DeclBase.h:1397
DeclContext * getDeclContext()
Definition: DeclBase.h:425
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:1583
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:961
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1952
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:201
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
bool isFunctionOrMethod() const
Definition: DeclBase.h:1380
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:117
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:373
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1331
void collectAllContexts(SmallVectorImpl< DeclContext *> &Contexts)
Collects all of the declaration contexts that are semantically connected to this declaration context...
Definition: DeclBase.cpp:1170
SourceLocation getEnd() const
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1026
The result type of a method or function.
const SourceManager & SM
Definition: Format.cpp:1337
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:284
virtual void DeclarationMarkedUsed(const Decl *D)
A declaration is marked used which was not previously marked used.
bool decls_empty() const
Definition: DeclBase.cpp:1326
AttrVec & getAttrs()
Definition: DeclBase.h:477
bool hasAttrs() const
Definition: DeclBase.h:471
Abstract interface for external sources of AST nodes.
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:228
bool empty() const
Determine whether this version information is empty (e.g., all version components are zero)...
Definition: VersionTuple.h:69
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1324
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1693
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:220
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:995
VersionTuple getVersionIntroduced() const
Retrieve the version of the target platform in which this declaration was introduced.
Definition: DeclBase.cpp:628
Encodes a location in the source.
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:136
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:1320
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2938
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:365
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
bool isStdNamespace() const
Definition: DeclBase.cpp:1010
This file defines OpenMP nodes for declarative directives.
void print(raw_ostream &OS) const override
Definition: DeclBase.cpp:257
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:1796
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:386
An array of decls optimized for the common case of only containing one entry.
void dropAttrs()
Definition: DeclBase.cpp:819
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:672
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:3965
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:650
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1533
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2796
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:936
Dataflow Directional Tag Classes.
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:63
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:1252
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
bool isRecord() const
Definition: DeclBase.h:1405
attr_range attrs() const
Definition: DeclBase.h:494
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1568
A decomposition declaration.
Definition: DeclCXX.h:3766
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1664
DeclarationName - The name of a declaration.
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2085
Kind getKind() const
Definition: DeclBase.h:419
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:957
Tags, declared with &#39;struct foo;&#39; and referenced with &#39;struct foo&#39;.
Definition: DeclBase.h:125
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1048
A dependently-generated diagnostic.
Pointer to a block type.
Definition: Type.h:2387
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:566
LanguageIDs
Represents the language in a linkage specification.
Definition: DeclCXX.h:2753
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple()) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:581
T * getAttr() const
Definition: DeclBase.h:531
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:1648
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1081
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1410
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:401
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1063
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.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
DeclContextLookupResult lookup_result
Definition: DeclBase.h:1776
void addHiddenDecl(Decl *D)
Add the declaration D to this context without modifying any lookup tables.
Definition: DeclBase.cpp:1384
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl *> Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1187
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:995
static bool classof(const Decl *D)
Definition: DeclBase.cpp:969
Defines the clang::TargetInfo interface.
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1360
Defines the clang::VersionTuple class, which represents a version in the form major[.minor[.subminor]].
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3505
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:107
static void DestroyAll(StoredDeclsMap *Map, bool Dependent)
Definition: DeclBase.cpp:1837
static void PrintStats()
Definition: DeclBase.cpp:169
NamedDecl * getMostRecentDecl()
Definition: Decl.h:437
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1106
bool trackLocalOwningModule() const
Do we need to track the owning module for a local declaration?
Definition: LangOptions.h:172
static void EnableStatistics()
Definition: DeclBase.cpp:165
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:600
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:288
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
bool isTranslationUnit() const
Definition: DeclBase.h:1401
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:455
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration...
Definition: DeclBase.cpp:232
Represents C++ using-directive.
Definition: DeclCXX.h:2843
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:460
bool isFunctionPointerType() const
Definition: Type.h:5968
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:346
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:350
const LangOptions & getLangOpts() const
Definition: ASTContext.h:688
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1092
SourceLocation getBodyRBrace() const
getBodyRBrace - Gets the right brace of the body, if a body exists.
Definition: DeclBase.cpp:869
Declaration of a template function.
Definition: DeclTemplate.h:967
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:494
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:3102
This declaration is a using declaration.
Definition: DeclBase.h:163
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:1058