clang  6.0.0
SemaDecl.cpp
Go to the documentation of this file.
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
55  if (OwnedType) {
56  Decl *Group[2] = { OwnedType, Ptr };
57  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58  }
59 
60  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68  bool AllowTemplates = false,
69  bool AllowNonTemplates = true)
70  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71  AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72  WantExpressionKeywords = false;
73  WantCXXNamedCasts = false;
74  WantRemainingKeywords = false;
75  }
76 
77  bool ValidateCandidate(const TypoCorrection &candidate) override {
78  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79  if (!AllowInvalidDecl && ND->isInvalidDecl())
80  return false;
81 
82  if (getAsTypeTemplateDecl(ND))
83  return AllowTemplates;
84 
85  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86  if (!IsType)
87  return false;
88 
89  if (AllowNonTemplates)
90  return true;
91 
92  // An injected-class-name of a class template (specialization) is valid
93  // as a template or as a non-template.
94  if (AllowTemplates) {
95  auto *RD = dyn_cast<CXXRecordDecl>(ND);
96  if (!RD || !RD->isInjectedClassName())
97  return false;
98  RD = cast<CXXRecordDecl>(RD->getDeclContext());
99  return RD->getDescribedClassTemplate() ||
100  isa<ClassTemplateSpecializationDecl>(RD);
101  }
102 
103  return false;
104  }
105 
106  return !WantClassName && candidate.isKeyword();
107  }
108 
109  private:
110  bool AllowInvalidDecl;
111  bool WantClassName;
112  bool AllowTemplates;
113  bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
120  switch (Kind) {
121  // FIXME: Take into account the current language when deciding whether a
122  // token kind is a valid type specifier
123  case tok::kw_short:
124  case tok::kw_long:
125  case tok::kw___int64:
126  case tok::kw___int128:
127  case tok::kw_signed:
128  case tok::kw_unsigned:
129  case tok::kw_void:
130  case tok::kw_char:
131  case tok::kw_int:
132  case tok::kw_half:
133  case tok::kw_float:
134  case tok::kw_double:
135  case tok::kw__Float16:
136  case tok::kw___float128:
137  case tok::kw_wchar_t:
138  case tok::kw_bool:
139  case tok::kw___underlying_type:
140  case tok::kw___auto_type:
141  return true;
142 
143  case tok::annot_typename:
144  case tok::kw_char16_t:
145  case tok::kw_char32_t:
146  case tok::kw_typeof:
147  case tok::annot_decltype:
148  case tok::kw_decltype:
149  return getLangOpts().CPlusPlus;
150 
151  default:
152  break;
153  }
154 
155  return false;
156 }
157 
158 namespace {
160  NotFound,
161  FoundNonType,
162  FoundType
163 };
164 } // end anonymous namespace
165 
166 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// dependent class.
168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169 /// type decl, \a FoundType if only type decls are found.
172  SourceLocation NameLoc,
173  const CXXRecordDecl *RD) {
174  if (!RD->hasDefinition())
175  return UnqualifiedTypeNameLookupResult::NotFound;
176  // Look for type decls in base classes.
177  UnqualifiedTypeNameLookupResult FoundTypeDecl =
178  UnqualifiedTypeNameLookupResult::NotFound;
179  for (const auto &Base : RD->bases()) {
180  const CXXRecordDecl *BaseRD = nullptr;
181  if (auto *BaseTT = Base.getType()->getAs<TagType>())
182  BaseRD = BaseTT->getAsCXXRecordDecl();
183  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184  // Look for type decls in dependent base classes that have known primary
185  // templates.
186  if (!TST || !TST->isDependentType())
187  continue;
188  auto *TD = TST->getTemplateName().getAsTemplateDecl();
189  if (!TD)
190  continue;
191  if (auto *BasePrimaryTemplate =
192  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193  if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194  BaseRD = BasePrimaryTemplate;
195  else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
197  CTD->findPartialSpecialization(Base.getType()))
198  if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199  BaseRD = PS;
200  }
201  }
202  }
203  if (BaseRD) {
204  for (NamedDecl *ND : BaseRD->lookup(&II)) {
205  if (!isa<TypeDecl>(ND))
206  return UnqualifiedTypeNameLookupResult::FoundNonType;
207  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208  }
209  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211  case UnqualifiedTypeNameLookupResult::FoundNonType:
212  return UnqualifiedTypeNameLookupResult::FoundNonType;
213  case UnqualifiedTypeNameLookupResult::FoundType:
214  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215  break;
216  case UnqualifiedTypeNameLookupResult::NotFound:
217  break;
218  }
219  }
220  }
221  }
222 
223  return FoundTypeDecl;
224 }
225 
227  const IdentifierInfo &II,
228  SourceLocation NameLoc) {
229  // Lookup in the parent class template context, if any.
230  const CXXRecordDecl *RD = nullptr;
231  UnqualifiedTypeNameLookupResult FoundTypeDecl =
232  UnqualifiedTypeNameLookupResult::NotFound;
233  for (DeclContext *DC = S.CurContext;
234  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235  DC = DC->getParent()) {
236  // Look for type decls in dependent base classes that have known primary
237  // templates.
238  RD = dyn_cast<CXXRecordDecl>(DC);
239  if (RD && RD->getDescribedClassTemplate())
240  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241  }
242  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243  return nullptr;
244 
245  // We found some types in dependent base classes. Recover as if the user
246  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
247  // lookup during template instantiation.
248  S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 
250  ASTContext &Context = S.Context;
251  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252  cast<Type>(Context.getRecordType(RD)));
253  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254 
255  CXXScopeSpec SS;
256  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 
258  TypeLocBuilder Builder;
260  DepTL.setNameLoc(NameLoc);
262  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264 }
265 
266 /// \brief If the identifier refers to a type name within this scope,
267 /// return the declaration of that type.
268 ///
269 /// This routine performs ordinary name lookup of the identifier II
270 /// within the given scope, with optional C++ scope specifier SS, to
271 /// determine whether the name refers to a type. If so, returns an
272 /// opaque pointer (actually a QualType) corresponding to that
273 /// type. Otherwise, returns NULL.
275  Scope *S, CXXScopeSpec *SS,
276  bool isClassName, bool HasTrailingDot,
277  ParsedType ObjectTypePtr,
278  bool IsCtorOrDtorName,
279  bool WantNontrivialTypeSourceInfo,
280  bool IsClassTemplateDeductionContext,
281  IdentifierInfo **CorrectedII) {
282  // FIXME: Consider allowing this outside C++1z mode as an extension.
283  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284  getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
285  !isClassName && !HasTrailingDot;
286 
287  // Determine where we will perform name lookup.
288  DeclContext *LookupCtx = nullptr;
289  if (ObjectTypePtr) {
290  QualType ObjectType = ObjectTypePtr.get();
291  if (ObjectType->isRecordType())
292  LookupCtx = computeDeclContext(ObjectType);
293  } else if (SS && SS->isNotEmpty()) {
294  LookupCtx = computeDeclContext(*SS, false);
295 
296  if (!LookupCtx) {
297  if (isDependentScopeSpecifier(*SS)) {
298  // C++ [temp.res]p3:
299  // A qualified-id that refers to a type and in which the
300  // nested-name-specifier depends on a template-parameter (14.6.2)
301  // shall be prefixed by the keyword typename to indicate that the
302  // qualified-id denotes a type, forming an
303  // elaborated-type-specifier (7.1.5.3).
304  //
305  // We therefore do not perform any name lookup if the result would
306  // refer to a member of an unknown specialization.
307  if (!isClassName && !IsCtorOrDtorName)
308  return nullptr;
309 
310  // We know from the grammar that this name refers to a type,
311  // so build a dependent node to describe the type.
312  if (WantNontrivialTypeSourceInfo)
313  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 
315  NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316  QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317  II, NameLoc);
318  return ParsedType::make(T);
319  }
320 
321  return nullptr;
322  }
323 
324  if (!LookupCtx->isDependentContext() &&
325  RequireCompleteDeclContext(*SS, LookupCtx))
326  return nullptr;
327  }
328 
329  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330  // lookup for class-names.
331  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332  LookupOrdinaryName;
333  LookupResult Result(*this, &II, NameLoc, Kind);
334  if (LookupCtx) {
335  // Perform "qualified" name lookup into the declaration context we
336  // computed, which is either the type of the base of a member access
337  // expression or the declaration context associated with a prior
338  // nested-name-specifier.
339  LookupQualifiedName(Result, LookupCtx);
340 
341  if (ObjectTypePtr && Result.empty()) {
342  // C++ [basic.lookup.classref]p3:
343  // If the unqualified-id is ~type-name, the type-name is looked up
344  // in the context of the entire postfix-expression. If the type T of
345  // the object expression is of a class type C, the type-name is also
346  // looked up in the scope of class C. At least one of the lookups shall
347  // find a name that refers to (possibly cv-qualified) T.
348  LookupName(Result, S);
349  }
350  } else {
351  // Perform unqualified name lookup.
352  LookupName(Result, S);
353 
354  // For unqualified lookup in a class template in MSVC mode, look into
355  // dependent base classes where the primary class template is known.
356  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357  if (ParsedType TypeInBase =
358  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359  return TypeInBase;
360  }
361  }
362 
363  NamedDecl *IIDecl = nullptr;
364  switch (Result.getResultKind()) {
367  if (CorrectedII) {
368  TypoCorrection Correction =
369  CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370  llvm::make_unique<TypeNameValidatorCCC>(
371  true, isClassName, AllowDeducedTemplate),
372  CTK_ErrorRecovery);
373  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374  TemplateTy Template;
375  bool MemberOfUnknownSpecialization;
377  TemplateName.setIdentifier(NewII, NameLoc);
378  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379  CXXScopeSpec NewSS, *NewSSPtr = SS;
380  if (SS && NNS) {
381  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382  NewSSPtr = &NewSS;
383  }
384  if (Correction && (NNS || NewII != &II) &&
385  // Ignore a correction to a template type as the to-be-corrected
386  // identifier is not a template (typo correction for template names
387  // is handled elsewhere).
388  !(getLangOpts().CPlusPlus && NewSSPtr &&
389  isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390  Template, MemberOfUnknownSpecialization))) {
391  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392  isClassName, HasTrailingDot, ObjectTypePtr,
393  IsCtorOrDtorName,
394  WantNontrivialTypeSourceInfo,
395  IsClassTemplateDeductionContext);
396  if (Ty) {
397  diagnoseTypo(Correction,
398  PDiag(diag::err_unknown_type_or_class_name_suggest)
399  << Result.getLookupName() << isClassName);
400  if (SS && NNS)
401  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402  *CorrectedII = NewII;
403  return Ty;
404  }
405  }
406  }
407  // If typo correction failed or was not performed, fall through
408  LLVM_FALLTHROUGH;
411  Result.suppressDiagnostics();
412  return nullptr;
413 
415  // Recover from type-hiding ambiguities by hiding the type. We'll
416  // do the lookup again when looking for an object, and we can
417  // diagnose the error then. If we don't do this, then the error
418  // about hiding the type will be immediately followed by an error
419  // that only makes sense if the identifier was treated like a type.
421  Result.suppressDiagnostics();
422  return nullptr;
423  }
424 
425  // Look to see if we have a type anywhere in the list of results.
426  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427  Res != ResEnd; ++Res) {
428  if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429  (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430  if (!IIDecl ||
431  (*Res)->getLocation().getRawEncoding() <
432  IIDecl->getLocation().getRawEncoding())
433  IIDecl = *Res;
434  }
435  }
436 
437  if (!IIDecl) {
438  // None of the entities we found is a type, so there is no way
439  // to even assume that the result is a type. In this case, don't
440  // complain about the ambiguity. The parser will either try to
441  // perform this lookup again (e.g., as an object name), which
442  // will produce the ambiguity, or will complain that it expected
443  // a type name.
444  Result.suppressDiagnostics();
445  return nullptr;
446  }
447 
448  // We found a type within the ambiguous lookup; diagnose the
449  // ambiguity and then return that type. This might be the right
450  // answer, or it might not be, but it suppresses any attempt to
451  // perform the name lookup again.
452  break;
453 
454  case LookupResult::Found:
455  IIDecl = Result.getFoundDecl();
456  break;
457  }
458 
459  assert(IIDecl && "Didn't find decl");
460 
461  QualType T;
462  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463  // C++ [class.qual]p2: A lookup that would find the injected-class-name
464  // instead names the constructors of the class, except when naming a class.
465  // This is ill-formed when we're not actually forming a ctor or dtor name.
466  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467  auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468  if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469  FoundRD->isInjectedClassName() &&
470  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471  Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472  << &II << /*Type*/1;
473 
474  DiagnoseUseOfDecl(IIDecl, NameLoc);
475 
476  T = Context.getTypeDeclType(TD);
477  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480  if (!HasTrailingDot)
481  T = Context.getObjCInterfaceType(IDecl);
482  } else if (AllowDeducedTemplate) {
483  if (auto *TD = getAsTypeTemplateDecl(IIDecl))
485  QualType(), false);
486  }
487 
488  if (T.isNull()) {
489  // If it's not plausibly a type, suppress diagnostics.
490  Result.suppressDiagnostics();
491  return nullptr;
492  }
493 
494  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495  // constructor or destructor name (in such a case, the scope specifier
496  // will be attached to the enclosing Expr or Decl node).
497  if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498  !isa<ObjCInterfaceDecl>(IIDecl)) {
499  if (WantNontrivialTypeSourceInfo) {
500  // Construct a type with type-source information.
501  TypeLocBuilder Builder;
502  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 
504  T = getElaboratedType(ETK_None, *SS, T);
505  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
507  ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509  } else {
510  T = getElaboratedType(ETK_None, *SS, T);
511  }
512  }
513 
514  return ParsedType::make(T);
515 }
516 
517 // Builds a fake NNS for the given decl context.
518 static NestedNameSpecifier *
520  for (;; DC = DC->getLookupParent()) {
521  DC = DC->getPrimaryContext();
522  auto *ND = dyn_cast<NamespaceDecl>(DC);
523  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524  return NestedNameSpecifier::Create(Context, nullptr, ND);
525  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527  RD->getTypeForDecl());
528  else if (isa<TranslationUnitDecl>(DC))
529  return NestedNameSpecifier::GlobalSpecifier(Context);
530  }
531  llvm_unreachable("something isn't in TU scope?");
532 }
533 
534 /// Find the parent class with dependent bases of the innermost enclosing method
535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536 /// up allowing unqualified dependent type names at class-level, which MSVC
537 /// correctly rejects.
538 static const CXXRecordDecl *
540  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541  DC = DC->getPrimaryContext();
542  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543  if (MD->getParent()->hasAnyDependentBases())
544  return MD->getParent();
545  }
546  return nullptr;
547 }
548 
550  SourceLocation NameLoc,
551  bool IsTemplateTypeArg) {
552  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 
554  NestedNameSpecifier *NNS = nullptr;
555  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556  // If we weren't able to parse a default template argument, delay lookup
557  // until instantiation time by making a non-dependent DependentTypeName. We
558  // pretend we saw a NestedNameSpecifier referring to the current scope, and
559  // lookup is retried.
560  // FIXME: This hurts our diagnostic quality, since we get errors like "no
561  // type named 'Foo' in 'current_namespace'" when the user didn't write any
562  // name specifiers.
563  NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565  } else if (const CXXRecordDecl *RD =
567  // Build a DependentNameType that will perform lookup into RD at
568  // instantiation time.
569  NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570  RD->getTypeForDecl());
571 
572  // Diagnose that this identifier was undeclared, and retry the lookup during
573  // template instantiation.
574  Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575  << RD;
576  } else {
577  // This is not a situation that we should recover from.
578  return ParsedType();
579  }
580 
581  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 
583  // Build type location information. We synthesized the qualifier, so we have
584  // to build a fake NestedNameSpecifierLoc.
585  NestedNameSpecifierLocBuilder NNSLocBuilder;
586  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 
589  TypeLocBuilder Builder;
591  DepTL.setNameLoc(NameLoc);
593  DepTL.setQualifierLoc(QualifierLoc);
594  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 }
596 
597 /// isTagName() - This method is called *for error recovery purposes only*
598 /// to determine if the specified name is a valid tag name ("struct foo"). If
599 /// so, this returns the TST for the tag corresponding to it (TST_enum,
600 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
601 /// cases in C where the user forgot to specify the tag.
603  // Do a tag name lookup in this scope.
604  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605  LookupName(R, S, false);
608  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609  switch (TD->getTagKind()) {
610  case TTK_Struct: return DeclSpec::TST_struct;
612  case TTK_Union: return DeclSpec::TST_union;
613  case TTK_Class: return DeclSpec::TST_class;
614  case TTK_Enum: return DeclSpec::TST_enum;
615  }
616  }
617 
619 }
620 
621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
623 /// then downgrade the missing typename error to a warning.
624 /// This is needed for MSVC compatibility; Example:
625 /// @code
626 /// template<class T> class A {
627 /// public:
628 /// typedef int TYPE;
629 /// };
630 /// template<class T> class B : public A<T> {
631 /// public:
632 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
633 /// };
634 /// @endcode
636  if (CurContext->isRecord()) {
638  return true;
639 
640  const Type *Ty = SS->getScopeRep()->getAsType();
641 
642  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643  for (const auto &Base : RD->bases())
644  if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645  return true;
646  return S->isFunctionPrototypeScope();
647  }
648  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 }
650 
652  SourceLocation IILoc,
653  Scope *S,
654  CXXScopeSpec *SS,
655  ParsedType &SuggestedType,
656  bool IsTemplateName) {
657  // Don't report typename errors for editor placeholders.
658  if (II->isEditorPlaceholder())
659  return;
660  // We don't have anything to suggest (yet).
661  SuggestedType = nullptr;
662 
663  // There may have been a typo in the name of the type. Look up typo
664  // results, in case we have something that we can suggest.
665  if (TypoCorrection Corrected =
666  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667  llvm::make_unique<TypeNameValidatorCCC>(
668  false, false, IsTemplateName, !IsTemplateName),
669  CTK_ErrorRecovery)) {
670  // FIXME: Support error recovery for the template-name case.
671  bool CanRecover = !IsTemplateName;
672  if (Corrected.isKeyword()) {
673  // We corrected to a keyword.
674  diagnoseTypo(Corrected,
675  PDiag(IsTemplateName ? diag::err_no_template_suggest
676  : diag::err_unknown_typename_suggest)
677  << II);
678  II = Corrected.getCorrectionAsIdentifierInfo();
679  } else {
680  // We found a similarly-named type or interface; suggest that.
681  if (!SS || !SS->isSet()) {
682  diagnoseTypo(Corrected,
683  PDiag(IsTemplateName ? diag::err_no_template_suggest
684  : diag::err_unknown_typename_suggest)
685  << II, CanRecover);
686  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689  II->getName().equals(CorrectedStr);
690  diagnoseTypo(Corrected,
691  PDiag(IsTemplateName
692  ? diag::err_no_member_template_suggest
693  : diag::err_unknown_nested_typename_suggest)
694  << II << DC << DroppedSpecifier << SS->getRange(),
695  CanRecover);
696  } else {
697  llvm_unreachable("could not have corrected a typo here");
698  }
699 
700  if (!CanRecover)
701  return;
702 
703  CXXScopeSpec tmpSS;
704  if (Corrected.getCorrectionSpecifier())
705  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706  SourceRange(IILoc));
707  // FIXME: Support class template argument deduction here.
708  SuggestedType =
709  getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710  tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711  /*IsCtorOrDtorName=*/false,
712  /*NonTrivialTypeSourceInfo=*/true);
713  }
714  return;
715  }
716 
717  if (getLangOpts().CPlusPlus && !IsTemplateName) {
718  // See if II is a class template that the user forgot to pass arguments to.
719  UnqualifiedId Name;
720  Name.setIdentifier(II, IILoc);
721  CXXScopeSpec EmptySS;
722  TemplateTy TemplateResult;
723  bool MemberOfUnknownSpecialization;
724  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725  Name, nullptr, true, TemplateResult,
726  MemberOfUnknownSpecialization) == TNK_Type_template) {
727  TemplateName TplName = TemplateResult.get();
728  Diag(IILoc, diag::err_template_missing_args)
729  << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730  if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731  Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732  << TplDecl->getTemplateParameters()->getSourceRange();
733  }
734  return;
735  }
736  }
737 
738  // FIXME: Should we move the logic that tries to recover from a missing tag
739  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741  if (!SS || (!SS->isSet() && !SS->isInvalid()))
742  Diag(IILoc, IsTemplateName ? diag::err_no_template
743  : diag::err_unknown_typename)
744  << II;
745  else if (DeclContext *DC = computeDeclContext(*SS, false))
746  Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747  : diag::err_typename_nested_not_found)
748  << II << DC << SS->getRange();
749  else if (isDependentScopeSpecifier(*SS)) {
750  unsigned DiagID = diag::err_typename_missing;
751  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752  DiagID = diag::ext_typename_missing;
753 
754  Diag(SS->getRange().getBegin(), DiagID)
755  << SS->getScopeRep() << II->getName()
756  << SourceRange(SS->getRange().getBegin(), IILoc)
757  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758  SuggestedType = ActOnTypenameType(S, SourceLocation(),
759  *SS, *II, IILoc).get();
760  } else {
761  assert(SS && SS->isInvalid() &&
762  "Invalid scope specifier has already been diagnosed");
763  }
764 }
765 
766 /// \brief Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770  NextToken.is(tok::less);
771 
772  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774  return true;
775 
776  if (CheckTemplate && isa<TemplateDecl>(*I))
777  return true;
778  }
779 
780  return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784  Scope *S, CXXScopeSpec &SS,
785  IdentifierInfo *&Name,
786  SourceLocation NameLoc) {
787  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788  SemaRef.LookupParsedName(R, S, &SS);
789  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790  StringRef FixItTagName;
791  switch (Tag->getTagKind()) {
792  case TTK_Class:
793  FixItTagName = "class ";
794  break;
795 
796  case TTK_Enum:
797  FixItTagName = "enum ";
798  break;
799 
800  case TTK_Struct:
801  FixItTagName = "struct ";
802  break;
803 
804  case TTK_Interface:
805  FixItTagName = "__interface ";
806  break;
807 
808  case TTK_Union:
809  FixItTagName = "union ";
810  break;
811  }
812 
813  StringRef TagName = FixItTagName.drop_back();
814  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819  I != IEnd; ++I)
820  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821  << Name << TagName;
822 
823  // Replace lookup results with just the tag decl.
824  Result.clear(Sema::LookupTagName);
825  SemaRef.LookupParsedName(Result, S, &SS);
826  return true;
827  }
828 
829  return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834  QualType T, SourceLocation NameLoc) {
835  ASTContext &Context = S.Context;
836 
837  TypeLocBuilder Builder;
838  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840  T = S.getElaboratedType(ETK_None, SS, T);
841  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
849  SourceLocation NameLoc, const Token &NextToken,
850  bool IsAddressOfOperand,
851  std::unique_ptr<CorrectionCandidateCallback> CCC) {
852  DeclarationNameInfo NameInfo(Name, NameLoc);
853  ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855  if (NextToken.is(tok::coloncolon)) {
856  NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857  BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858  } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859  isCurrentClassName(*Name, S, &SS)) {
860  // Per [class.qual]p2, this names the constructors of SS, not the
861  // injected-class-name. We don't have a classification for that.
862  // There's not much point caching this result, since the parser
863  // will reject it later.
865  }
866 
867  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868  LookupParsedName(Result, S, &SS, !CurMethod);
869 
870  // For unqualified lookup in a class template in MSVC mode, look into
871  // dependent base classes where the primary class template is known.
872  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873  if (ParsedType TypeInBase =
874  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875  return TypeInBase;
876  }
877 
878  // Perform lookup for Objective-C instance variables (including automatically
879  // synthesized instance variables), if we're in an Objective-C method.
880  // FIXME: This lookup really, really needs to be folded in to the normal
881  // unqualified lookup mechanism.
882  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883  ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884  if (E.get() || E.isInvalid())
885  return E;
886  }
887 
888  bool SecondTry = false;
889  bool IsFilteredTemplateName = false;
890 
891 Corrected:
892  switch (Result.getResultKind()) {
894  // If an unqualified-id is followed by a '(', then we have a function
895  // call.
896  if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897  // In C++, this is an ADL-only call.
898  // FIXME: Reference?
899  if (getLangOpts().CPlusPlus)
900  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902  // C90 6.3.2.2:
903  // If the expression that precedes the parenthesized argument list in a
904  // function call consists solely of an identifier, and if no
905  // declaration is visible for this identifier, the identifier is
906  // implicitly declared exactly as if, in the innermost block containing
907  // the function call, the declaration
908  //
909  // extern int identifier ();
910  //
911  // appeared.
912  //
913  // We also allow this in C99 as an extension.
914  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915  Result.addDecl(D);
916  Result.resolveKind();
917  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918  }
919  }
920 
921  // In C, we first see whether there is a tag type by the same name, in
922  // which case it's likely that the user just forgot to write "enum",
923  // "struct", or "union".
924  if (!getLangOpts().CPlusPlus && !SecondTry &&
925  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926  break;
927  }
928 
929  // Perform typo correction to determine if there is another name that is
930  // close to this name.
931  if (!SecondTry && CCC) {
932  SecondTry = true;
933  if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934  Result.getLookupKind(), S,
935  &SS, std::move(CCC),
936  CTK_ErrorRecovery)) {
937  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938  unsigned QualifiedDiag = diag::err_no_member_suggest;
939 
940  NamedDecl *FirstDecl = Corrected.getFoundDecl();
941  NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944  UnqualifiedDiag = diag::err_no_template_suggest;
945  QualifiedDiag = diag::err_no_member_template_suggest;
946  } else if (UnderlyingFirstDecl &&
947  (isa<TypeDecl>(UnderlyingFirstDecl) ||
948  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950  UnqualifiedDiag = diag::err_unknown_typename_suggest;
951  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952  }
953 
954  if (SS.isEmpty()) {
955  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956  } else {// FIXME: is this even reachable? Test it.
957  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959  Name->getName().equals(CorrectedStr);
960  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961  << Name << computeDeclContext(SS, false)
962  << DroppedSpecifier << SS.getRange());
963  }
964 
965  // Update the name, so that the caller has the new name.
966  Name = Corrected.getCorrectionAsIdentifierInfo();
967 
968  // Typo correction corrected to a keyword.
969  if (Corrected.isKeyword())
970  return Name;
971 
972  // Also update the LookupResult...
973  // FIXME: This should probably go away at some point
974  Result.clear();
975  Result.setLookupName(Corrected.getCorrection());
976  if (FirstDecl)
977  Result.addDecl(FirstDecl);
978 
979  // If we found an Objective-C instance variable, let
980  // LookupInObjCMethod build the appropriate expression to
981  // reference the ivar.
982  // FIXME: This is a gross hack.
983  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984  Result.clear();
985  ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986  return E;
987  }
988 
989  goto Corrected;
990  }
991  }
992 
993  // We failed to correct; just fall through and let the parser deal with it.
994  Result.suppressDiagnostics();
996 
998  // We performed name lookup into the current instantiation, and there were
999  // dependent bases, so we treat this result the same way as any other
1000  // dependent nested-name-specifier.
1001 
1002  // C++ [temp.res]p2:
1003  // A name used in a template declaration or definition and that is
1004  // dependent on a template-parameter is assumed not to name a type
1005  // unless the applicable name lookup finds a type name or the name is
1006  // qualified by the keyword typename.
1007  //
1008  // FIXME: If the next token is '<', we might want to ask the parser to
1009  // perform some heroics to see if we actually have a
1010  // template-argument-list, which would indicate a missing 'template'
1011  // keyword here.
1012  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013  NameInfo, IsAddressOfOperand,
1014  /*TemplateArgs=*/nullptr);
1015  }
1016 
1017  case LookupResult::Found:
1020  break;
1021 
1023  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024  hasAnyAcceptableTemplateNames(Result)) {
1025  // C++ [temp.local]p3:
1026  // A lookup that finds an injected-class-name (10.2) can result in an
1027  // ambiguity in certain cases (for example, if it is found in more than
1028  // one base class). If all of the injected-class-names that are found
1029  // refer to specializations of the same class template, and if the name
1030  // is followed by a template-argument-list, the reference refers to the
1031  // class template itself and not a specialization thereof, and is not
1032  // ambiguous.
1033  //
1034  // This filtering can make an ambiguous result into an unambiguous one,
1035  // so try again after filtering out template names.
1036  FilterAcceptableTemplateNames(Result);
1037  if (!Result.isAmbiguous()) {
1038  IsFilteredTemplateName = true;
1039  break;
1040  }
1041  }
1042 
1043  // Diagnose the ambiguity and return an error.
1044  return NameClassification::Error();
1045  }
1046 
1047  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048  (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049  // C++ [temp.names]p3:
1050  // After name lookup (3.4) finds that a name is a template-name or that
1051  // an operator-function-id or a literal- operator-id refers to a set of
1052  // overloaded functions any member of which is a function template if
1053  // this is followed by a <, the < is always taken as the delimiter of a
1054  // template-argument-list and never as the less-than operator.
1055  if (!IsFilteredTemplateName)
1056  FilterAcceptableTemplateNames(Result);
1057 
1058  if (!Result.empty()) {
1059  bool IsFunctionTemplate;
1060  bool IsVarTemplate;
1061  TemplateName Template;
1062  if (Result.end() - Result.begin() > 1) {
1063  IsFunctionTemplate = true;
1064  Template = Context.getOverloadedTemplateName(Result.begin(),
1065  Result.end());
1066  } else {
1067  TemplateDecl *TD
1068  = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070  IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072  if (SS.isSet() && !SS.isInvalid())
1073  Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074  /*TemplateKeyword=*/false,
1075  TD);
1076  else
1077  Template = TemplateName(TD);
1078  }
1079 
1080  if (IsFunctionTemplate) {
1081  // Function templates always go through overload resolution, at which
1082  // point we'll perform the various checks (e.g., accessibility) we need
1083  // to based on which function we selected.
1084  Result.suppressDiagnostics();
1085 
1086  return NameClassification::FunctionTemplate(Template);
1087  }
1088 
1089  return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090  : NameClassification::TypeTemplate(Template);
1091  }
1092  }
1093 
1094  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096  DiagnoseUseOfDecl(Type, NameLoc);
1097  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098  QualType T = Context.getTypeDeclType(Type);
1099  if (SS.isNotEmpty())
1100  return buildNestedType(*this, SS, T, NameLoc);
1101  return ParsedType::make(T);
1102  }
1103 
1104  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105  if (!Class) {
1106  // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107  if (ObjCCompatibleAliasDecl *Alias =
1108  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109  Class = Alias->getClassInterface();
1110  }
1111 
1112  if (Class) {
1113  DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115  if (NextToken.is(tok::period)) {
1116  // Interface. <something> is parsed as a property reference expression.
1117  // Just return "unknown" as a fall-through for now.
1118  Result.suppressDiagnostics();
1119  return NameClassification::Unknown();
1120  }
1121 
1122  QualType T = Context.getObjCInterfaceType(Class);
1123  return ParsedType::make(T);
1124  }
1125 
1126  // We can have a type template here if we're classifying a template argument.
1127  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128  !isa<VarTemplateDecl>(FirstDecl))
1129  return NameClassification::TypeTemplate(
1130  TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132  // Check for a tag type hidden by a non-type decl in a few cases where it
1133  // seems likely a type is wanted instead of the non-type that was found.
1134  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135  if ((NextToken.is(tok::identifier) ||
1136  (NextIsOp &&
1137  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140  DiagnoseUseOfDecl(Type, NameLoc);
1141  QualType T = Context.getTypeDeclType(Type);
1142  if (SS.isNotEmpty())
1143  return buildNestedType(*this, SS, T, NameLoc);
1144  return ParsedType::make(T);
1145  }
1146 
1147  if (FirstDecl->isCXXClassMember())
1148  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149  nullptr, S);
1150 
1151  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152  return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1157  auto *TD = Name.getAsTemplateDecl();
1158  if (!TD)
1159  return TemplateNameKindForDiagnostics::DependentTemplate;
1160  if (isa<ClassTemplateDecl>(TD))
1161  return TemplateNameKindForDiagnostics::ClassTemplate;
1162  if (isa<FunctionTemplateDecl>(TD))
1163  return TemplateNameKindForDiagnostics::FunctionTemplate;
1164  if (isa<VarTemplateDecl>(TD))
1165  return TemplateNameKindForDiagnostics::VarTemplate;
1166  if (isa<TypeAliasTemplateDecl>(TD))
1167  return TemplateNameKindForDiagnostics::AliasTemplate;
1168  if (isa<TemplateTemplateParmDecl>(TD))
1169  return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170  return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context. This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1177 
1178  // Functions defined inline within classes aren't parsed until we've
1179  // finished parsing the top-level class, so the top-level class is
1180  // the context we'll need to return to.
1181  // A Lambda call operator whose parent is a class must not be treated
1182  // as an inline member function. A Lambda can be used legally
1183  // either as an in-class member initializer or a default argument. These
1184  // are parsed once the class has been marked complete and so the containing
1185  // context would be the nested class (when the lambda is defined in one);
1186  // If the class is not complete, then the lambda is being used in an
1187  // ill-formed fashion (such as to specify the width of a bit-field, or
1188  // in an array-bound) - in which case we still want to return the
1189  // lexically containing DC (which could be a nested class).
1190  if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191  DC = DC->getLexicalParent();
1192 
1193  // A function not defined within a class will always return to its
1194  // lexical context.
1195  if (!isa<CXXRecordDecl>(DC))
1196  return DC;
1197 
1198  // A C++ inline method/friend is parsed *after* the topmost class
1199  // it was declared in is fully parsed ("complete"); the topmost
1200  // class is the context we need to return to.
1201  while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202  DC = RD;
1203 
1204  // Return the declaration context of the topmost class the inline method is
1205  // declared in.
1206  return DC;
1207  }
1208 
1209  return DC->getLexicalParent();
1210 }
1211 
1213  assert(getContainingDC(DC) == CurContext &&
1214  "The next DeclContext should be lexically contained in the current one.");
1215  CurContext = DC;
1216  S->setEntity(DC);
1217 }
1218 
1220  assert(CurContext && "DeclContext imbalance!");
1221 
1222  CurContext = getContainingDC(CurContext);
1223  assert(CurContext && "Popped translation unit!");
1224 }
1225 
1227  Decl *D) {
1228  // Unlike PushDeclContext, the context to which we return is not necessarily
1229  // the containing DC of TD, because the new context will be some pre-existing
1230  // TagDecl definition instead of a fresh one.
1231  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232  CurContext = cast<TagDecl>(D)->getDefinition();
1233  assert(CurContext && "skipping definition of undefined tag");
1234  // Start lookups from the parent of the current context; we don't want to look
1235  // into the pre-existing complete definition.
1236  S->setEntity(CurContext->getLookupParent());
1237  return Result;
1238 }
1239 
1241  CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1248  // C++0x [basic.lookup.unqual]p13:
1249  // A name used in the definition of a static data member of class
1250  // X (after the qualified-id of the static member) is looked up as
1251  // if the name was used in a member function of X.
1252  // C++0x [basic.lookup.unqual]p14:
1253  // If a variable member of a namespace is defined outside of the
1254  // scope of its namespace then any name used in the definition of
1255  // the variable member (after the declarator-id) is looked up as
1256  // if the definition of the variable member occurred in its
1257  // namespace.
1258  // Both of these imply that we should push a scope whose context
1259  // is the semantic context of the declaration. We can't use
1260  // PushDeclContext here because that context is not necessarily
1261  // lexically contained in the current context. Fortunately,
1262  // the containing scope should have the appropriate information.
1263 
1264  assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267  Scope *Ancestor = S->getParent();
1268  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272  CurContext = DC;
1273  S->setEntity(DC);
1274 }
1275 
1277  assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279  // Switch back to the lexical context. The safety of this is
1280  // enforced by an assert in EnterDeclaratorContext.
1281  Scope *Ancestor = S->getParent();
1282  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283  CurContext = Ancestor->getEntity();
1284 
1285  // We don't need to do anything with the scope, which is going to
1286  // disappear.
1287 }
1288 
1290  // We assume that the caller has already called
1291  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292  FunctionDecl *FD = D->getAsFunction();
1293  if (!FD)
1294  return;
1295 
1296  // Same implementation as PushDeclContext, but enters the context
1297  // from the lexical parent, rather than the top-level class.
1298  assert(CurContext == FD->getLexicalParent() &&
1299  "The next DeclContext should be lexically contained in the current one.");
1300  CurContext = FD;
1301  S->setEntity(CurContext);
1302 
1303  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304  ParmVarDecl *Param = FD->getParamDecl(P);
1305  // If the parameter has an identifier, then add it to the scope
1306  if (Param->getIdentifier()) {
1307  S->AddDecl(Param);
1308  IdResolver.AddDecl(Param);
1309  }
1310  }
1311 }
1312 
1314  // Same implementation as PopDeclContext, but returns to the lexical parent,
1315  // rather than the top-level class.
1316  assert(CurContext && "DeclContext imbalance!");
1317  CurContext = CurContext->getLexicalParent();
1318  assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// \brief Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1331  ASTContext &Context,
1332  const FunctionDecl *New) {
1333  if (Context.getLangOpts().CPlusPlus)
1334  return true;
1335 
1336  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337  return true;
1338 
1339  return Previous.getResultKind() == LookupResult::Found &&
1340  (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341  New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346  // Move up the scope chain until we find the nearest enclosing
1347  // non-transparent context. The declaration will be introduced into this
1348  // scope.
1349  while (S->getEntity() && S->getEntity()->isTransparentContext())
1350  S = S->getParent();
1351 
1352  // Add scoped declarations into their context, so that they can be
1353  // found later. Declarations without a context won't be inserted
1354  // into any context.
1355  if (AddToContext)
1356  CurContext->addDecl(D);
1357 
1358  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359  // are function-local declarations.
1360  if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1364  return;
1365 
1366  // Template instantiations should also not be pushed into scope.
1367  if (isa<FunctionDecl>(D) &&
1368  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369  return;
1370 
1371  // If this replaces anything in the current scope,
1372  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373  IEnd = IdResolver.end();
1374  for (; I != IEnd; ++I) {
1375  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376  S->RemoveDecl(*I);
1377  IdResolver.RemoveDecl(*I);
1378 
1379  // Should only need to replace one decl.
1380  break;
1381  }
1382  }
1383 
1384  S->AddDecl(D);
1385 
1386  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387  // Implicitly-generated labels may end up getting generated in an order that
1388  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389  // the label at the appropriate place in the identifier chain.
1390  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392  if (IDC == CurContext) {
1393  if (!S->isDeclScope(*I))
1394  continue;
1395  } else if (IDC->Encloses(CurContext))
1396  break;
1397  }
1398 
1399  IdResolver.InsertDeclAfter(I, D);
1400  } else {
1401  IdResolver.AddDecl(D);
1402  }
1403 }
1404 
1406  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407  TUScope->AddDecl(D);
1408 }
1409 
1411  bool AllowInlineNamespace) {
1412  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1416  DeclContext *TargetDC = DC->getPrimaryContext();
1417  do {
1418  if (DeclContext *ScopeDC = S->getEntity())
1419  if (ScopeDC->getPrimaryContext() == TargetDC)
1420  return S;
1421  } while ((S = S->getParent()));
1422 
1423  return nullptr;
1424 }
1425 
1427  DeclContext*,
1428  ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1433  bool ConsiderLinkage,
1434  bool AllowInlineNamespace) {
1436  while (F.hasNext()) {
1437  NamedDecl *D = F.next();
1438 
1439  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440  continue;
1441 
1442  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443  continue;
1444 
1445  F.erase();
1446  }
1447 
1448  F.done();
1449 }
1450 
1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1454  // FIXME: The Modules TS is not clear about how friend declarations are
1455  // to be treated. It's not meaningful to have different owning modules for
1456  // linkage in redeclarations of the same entity, so for now allow the
1457  // redeclaration and change the owning modules to match.
1458  if (New->getFriendObjectKind() &&
1461  makeMergedDefinitionVisible(New);
1462  return false;
1463  }
1464 
1465  Module *NewM = New->getOwningModule();
1466  Module *OldM = Old->getOwningModule();
1467  if (NewM == OldM)
1468  return false;
1469 
1470  // FIXME: Check proclaimed-ownership-declarations here too.
1471  bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472  bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473  if (NewIsModuleInterface || OldIsModuleInterface) {
1474  // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475  // if a declaration of D [...] appears in the purview of a module, all
1476  // other such declarations shall appear in the purview of the same module
1477  Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478  << New
1479  << NewIsModuleInterface
1480  << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481  << OldIsModuleInterface
1482  << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483  Diag(Old->getLocation(), diag::note_previous_declaration);
1484  New->setInvalidDecl();
1485  return true;
1486  }
1487 
1488  return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492  return isa<UsingShadowDecl>(D) ||
1493  isa<UnresolvedUsingTypenameDecl>(D) ||
1494  isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1500  while (F.hasNext())
1501  if (isUsingDecl(F.next()))
1502  F.erase();
1503 
1504  F.done();
1505 }
1506 
1507 /// \brief Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 /// S(const S&); // DO NOT IMPLEMENT
1511 /// void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1515  // FIXME: Should check for private access too but access is set after we get
1516  // the decl here.
1518  return false;
1519 
1520  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521  return CD->isCopyConstructor();
1522  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1523  return Method->isCopyAssignmentOperator();
1524  return false;
1525 }
1526 
1527 // We need this to handle
1528 //
1529 // typedef struct {
1530 // void *foo() { return 0; }
1531 // } A;
1532 //
1533 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1534 // for example. If 'A', foo will have external linkage. If we have '*A',
1535 // foo will have no linkage. Since we can't know until we get to the end
1536 // of the typedef, this function finds out if D might have non-external linkage.
1537 // Callers should verify at the end of the TU if it D has external linkage or
1538 // not.
1539 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1540  const DeclContext *DC = D->getDeclContext();
1541  while (!DC->isTranslationUnit()) {
1542  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1543  if (!RD->hasNameForLinkage())
1544  return true;
1545  }
1546  DC = DC->getParent();
1547  }
1548 
1549  return !D->isExternallyVisible();
1550 }
1551 
1552 // FIXME: This needs to be refactored; some other isInMainFile users want
1553 // these semantics.
1554 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1555  if (S.TUKind != TU_Complete)
1556  return false;
1557  return S.SourceMgr.isInMainFile(Loc);
1558 }
1559 
1561  assert(D);
1562 
1563  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1564  return false;
1565 
1566  // Ignore all entities declared within templates, and out-of-line definitions
1567  // of members of class templates.
1568  if (D->getDeclContext()->isDependentContext() ||
1570  return false;
1571 
1572  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1573  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1574  return false;
1575  // A non-out-of-line declaration of a member specialization was implicitly
1576  // instantiated; it's the out-of-line declaration that we're interested in.
1577  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1578  FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1579  return false;
1580 
1581  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1582  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1583  return false;
1584  } else {
1585  // 'static inline' functions are defined in headers; don't warn.
1586  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1587  return false;
1588  }
1589 
1590  if (FD->doesThisDeclarationHaveABody() &&
1591  Context.DeclMustBeEmitted(FD))
1592  return false;
1593  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594  // Constants and utility variables are defined in headers with internal
1595  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1596  // like "inline".)
1597  if (!isMainFileLoc(*this, VD->getLocation()))
1598  return false;
1599 
1600  if (Context.DeclMustBeEmitted(VD))
1601  return false;
1602 
1603  if (VD->isStaticDataMember() &&
1604  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1605  return false;
1606  if (VD->isStaticDataMember() &&
1607  VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1608  VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1609  return false;
1610 
1611  if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1612  return false;
1613  } else {
1614  return false;
1615  }
1616 
1617  // Only warn for unused decls internal to the translation unit.
1618  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1619  // for inline functions defined in the main source file, for instance.
1620  return mightHaveNonExternalLinkage(D);
1621 }
1622 
1624  if (!D)
1625  return;
1626 
1627  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1628  const FunctionDecl *First = FD->getFirstDecl();
1629  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630  return; // First should already be in the vector.
1631  }
1632 
1633  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1634  const VarDecl *First = VD->getFirstDecl();
1635  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1636  return; // First should already be in the vector.
1637  }
1638 
1639  if (ShouldWarnIfUnusedFileScopedDecl(D))
1640  UnusedFileScopedDecls.push_back(D);
1641 }
1642 
1643 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1644  if (D->isInvalidDecl())
1645  return false;
1646 
1647  bool Referenced = false;
1648  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1649  // For a decomposition declaration, warn if none of the bindings are
1650  // referenced, instead of if the variable itself is referenced (which
1651  // it is, by the bindings' expressions).
1652  for (auto *BD : DD->bindings()) {
1653  if (BD->isReferenced()) {
1654  Referenced = true;
1655  break;
1656  }
1657  }
1658  } else if (!D->getDeclName()) {
1659  return false;
1660  } else if (D->isReferenced() || D->isUsed()) {
1661  Referenced = true;
1662  }
1663 
1664  if (Referenced || D->hasAttr<UnusedAttr>() ||
1665  D->hasAttr<ObjCPreciseLifetimeAttr>())
1666  return false;
1667 
1668  if (isa<LabelDecl>(D))
1669  return true;
1670 
1671  // Except for labels, we only care about unused decls that are local to
1672  // functions.
1673  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1674  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1675  // For dependent types, the diagnostic is deferred.
1676  WithinFunction =
1677  WithinFunction || (R->isLocalClass() && !R->isDependentType());
1678  if (!WithinFunction)
1679  return false;
1680 
1681  if (isa<TypedefNameDecl>(D))
1682  return true;
1683 
1684  // White-list anything that isn't a local variable.
1685  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1686  return false;
1687 
1688  // Types of valid local variables should be complete, so this should succeed.
1689  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1690 
1691  // White-list anything with an __attribute__((unused)) type.
1692  const auto *Ty = VD->getType().getTypePtr();
1693 
1694  // Only look at the outermost level of typedef.
1695  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1696  if (TT->getDecl()->hasAttr<UnusedAttr>())
1697  return false;
1698  }
1699 
1700  // If we failed to complete the type for some reason, or if the type is
1701  // dependent, don't diagnose the variable.
1702  if (Ty->isIncompleteType() || Ty->isDependentType())
1703  return false;
1704 
1705  // Look at the element type to ensure that the warning behaviour is
1706  // consistent for both scalars and arrays.
1707  Ty = Ty->getBaseElementTypeUnsafe();
1708 
1709  if (const TagType *TT = Ty->getAs<TagType>()) {
1710  const TagDecl *Tag = TT->getDecl();
1711  if (Tag->hasAttr<UnusedAttr>())
1712  return false;
1713 
1714  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1715  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1716  return false;
1717 
1718  if (const Expr *Init = VD->getInit()) {
1719  if (const ExprWithCleanups *Cleanups =
1720  dyn_cast<ExprWithCleanups>(Init))
1721  Init = Cleanups->getSubExpr();
1722  const CXXConstructExpr *Construct =
1723  dyn_cast<CXXConstructExpr>(Init);
1724  if (Construct && !Construct->isElidable()) {
1725  CXXConstructorDecl *CD = Construct->getConstructor();
1726  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1727  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1728  return false;
1729  }
1730  }
1731  }
1732  }
1733 
1734  // TODO: __attribute__((unused)) templates?
1735  }
1736 
1737  return true;
1738 }
1739 
1740 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1741  FixItHint &Hint) {
1742  if (isa<LabelDecl>(D)) {
1744  tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1745  if (AfterColon.isInvalid())
1746  return;
1748  getCharRange(D->getLocStart(), AfterColon));
1749  }
1750 }
1751 
1753  if (D->getTypeForDecl()->isDependentType())
1754  return;
1755 
1756  for (auto *TmpD : D->decls()) {
1757  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1758  DiagnoseUnusedDecl(T);
1759  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1760  DiagnoseUnusedNestedTypedefs(R);
1761  }
1762 }
1763 
1764 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1765 /// unless they are marked attr(unused).
1767  if (!ShouldDiagnoseUnusedDecl(D))
1768  return;
1769 
1770  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1771  // typedefs can be referenced later on, so the diagnostics are emitted
1772  // at end-of-translation-unit.
1773  UnusedLocalTypedefNameCandidates.insert(TD);
1774  return;
1775  }
1776 
1777  FixItHint Hint;
1778  GenerateFixForUnusedDecl(D, Context, Hint);
1779 
1780  unsigned DiagID;
1781  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1782  DiagID = diag::warn_unused_exception_param;
1783  else if (isa<LabelDecl>(D))
1784  DiagID = diag::warn_unused_label;
1785  else
1786  DiagID = diag::warn_unused_variable;
1787 
1788  Diag(D->getLocation(), DiagID) << D << Hint;
1789 }
1790 
1791 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1792  // Verify that we have no forward references left. If so, there was a goto
1793  // or address of a label taken, but no definition of it. Label fwd
1794  // definitions are indicated with a null substmt which is also not a resolved
1795  // MS inline assembly label name.
1796  bool Diagnose = false;
1797  if (L->isMSAsmLabel())
1798  Diagnose = !L->isResolvedMSAsmLabel();
1799  else
1800  Diagnose = L->getStmt() == nullptr;
1801  if (Diagnose)
1802  S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1803 }
1804 
1806  S->mergeNRVOIntoParent();
1807 
1808  if (S->decl_empty()) return;
1809  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1810  "Scope shouldn't contain decls!");
1811 
1812  for (auto *TmpD : S->decls()) {
1813  assert(TmpD && "This decl didn't get pushed??");
1814 
1815  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1816  NamedDecl *D = cast<NamedDecl>(TmpD);
1817 
1818  // Diagnose unused variables in this scope.
1819  if (!S->hasUnrecoverableErrorOccurred()) {
1820  DiagnoseUnusedDecl(D);
1821  if (const auto *RD = dyn_cast<RecordDecl>(D))
1822  DiagnoseUnusedNestedTypedefs(RD);
1823  }
1824 
1825  if (!D->getDeclName()) continue;
1826 
1827  // If this was a forward reference to a label, verify it was defined.
1828  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1829  CheckPoppedLabel(LD, *this);
1830 
1831  // Remove this name from our lexical scope, and warn on it if we haven't
1832  // already.
1833  IdResolver.RemoveDecl(D);
1834  auto ShadowI = ShadowingDecls.find(D);
1835  if (ShadowI != ShadowingDecls.end()) {
1836  if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1837  Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1838  << D << FD << FD->getParent();
1839  Diag(FD->getLocation(), diag::note_previous_declaration);
1840  }
1841  ShadowingDecls.erase(ShadowI);
1842  }
1843  }
1844 }
1845 
1846 /// \brief Look for an Objective-C class in the translation unit.
1847 ///
1848 /// \param Id The name of the Objective-C class we're looking for. If
1849 /// typo-correction fixes this name, the Id will be updated
1850 /// to the fixed name.
1851 ///
1852 /// \param IdLoc The location of the name in the translation unit.
1853 ///
1854 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1855 /// if there is no class with the given name.
1856 ///
1857 /// \returns The declaration of the named Objective-C class, or NULL if the
1858 /// class could not be found.
1860  SourceLocation IdLoc,
1861  bool DoTypoCorrection) {
1862  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1863  // creation from this context.
1864  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1865 
1866  if (!IDecl && DoTypoCorrection) {
1867  // Perform typo correction at the given location, but only if we
1868  // find an Objective-C class name.
1869  if (TypoCorrection C = CorrectTypo(
1870  DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1871  llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1872  CTK_ErrorRecovery)) {
1873  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1874  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1875  Id = IDecl->getIdentifier();
1876  }
1877  }
1878  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1879  // This routine must always return a class definition, if any.
1880  if (Def && Def->getDefinition())
1881  Def = Def->getDefinition();
1882  return Def;
1883 }
1884 
1885 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1886 /// from S, where a non-field would be declared. This routine copes
1887 /// with the difference between C and C++ scoping rules in structs and
1888 /// unions. For example, the following code is well-formed in C but
1889 /// ill-formed in C++:
1890 /// @code
1891 /// struct S6 {
1892 /// enum { BAR } e;
1893 /// };
1894 ///
1895 /// void test_S6() {
1896 /// struct S6 a;
1897 /// a.e = BAR;
1898 /// }
1899 /// @endcode
1900 /// For the declaration of BAR, this routine will return a different
1901 /// scope. The scope S will be the scope of the unnamed enumeration
1902 /// within S6. In C++, this routine will return the scope associated
1903 /// with S6, because the enumeration's scope is a transparent
1904 /// context but structures can contain non-field names. In C, this
1905 /// routine will return the translation unit scope, since the
1906 /// enumeration's scope is a transparent context and structures cannot
1907 /// contain non-field names.
1909  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1910  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1911  (S->isClassScope() && !getLangOpts().CPlusPlus))
1912  S = S->getParent();
1913  return S;
1914 }
1915 
1916 /// \brief Looks up the declaration of "struct objc_super" and
1917 /// saves it for later use in building builtin declaration of
1918 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1919 /// pre-existing declaration exists no action takes place.
1920 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1921  IdentifierInfo *II) {
1922  if (!II->isStr("objc_msgSendSuper"))
1923  return;
1924  ASTContext &Context = ThisSema.Context;
1925 
1926  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1928  ThisSema.LookupName(Result, S);
1929  if (Result.getResultKind() == LookupResult::Found)
1930  if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1931  Context.setObjCSuperType(Context.getTagDeclType(TD));
1932 }
1933 
1935  switch (Error) {
1936  case ASTContext::GE_None:
1937  return "";
1939  return "stdio.h";
1941  return "setjmp.h";
1943  return "ucontext.h";
1944  }
1945  llvm_unreachable("unhandled error kind");
1946 }
1947 
1948 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1949 /// file scope. lazily create a decl for it. ForRedeclaration is true
1950 /// if we're creating this built-in in anticipation of redeclaring the
1951 /// built-in.
1953  Scope *S, bool ForRedeclaration,
1954  SourceLocation Loc) {
1955  LookupPredefedObjCSuperType(*this, S, II);
1956 
1958  QualType R = Context.GetBuiltinType(ID, Error);
1959  if (Error) {
1960  if (ForRedeclaration)
1961  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1962  << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1963  return nullptr;
1964  }
1965 
1966  if (!ForRedeclaration &&
1967  (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1968  Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1969  Diag(Loc, diag::ext_implicit_lib_function_decl)
1970  << Context.BuiltinInfo.getName(ID) << R;
1971  if (Context.BuiltinInfo.getHeaderName(ID) &&
1972  !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1973  Diag(Loc, diag::note_include_header_or_declare)
1974  << Context.BuiltinInfo.getHeaderName(ID)
1975  << Context.BuiltinInfo.getName(ID);
1976  }
1977 
1978  if (R.isNull())
1979  return nullptr;
1980 
1982  if (getLangOpts().CPlusPlus) {
1983  LinkageSpecDecl *CLinkageDecl =
1984  LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1985  LinkageSpecDecl::lang_c, false);
1986  CLinkageDecl->setImplicit();
1987  Parent->addDecl(CLinkageDecl);
1988  Parent = CLinkageDecl;
1989  }
1990 
1991  FunctionDecl *New = FunctionDecl::Create(Context,
1992  Parent,
1993  Loc, Loc, II, R, /*TInfo=*/nullptr,
1994  SC_Extern,
1995  false,
1996  R->isFunctionProtoType());
1997  New->setImplicit();
1998 
1999  // Create Decl objects for each parameter, adding them to the
2000  // FunctionDecl.
2001  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2003  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2004  ParmVarDecl *parm =
2006  nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2007  SC_None, nullptr);
2008  parm->setScopeInfo(0, i);
2009  Params.push_back(parm);
2010  }
2011  New->setParams(Params);
2012  }
2013 
2014  AddKnownFunctionAttributes(New);
2015  RegisterLocallyScopedExternCDecl(New, S);
2016 
2017  // TUScope is the translation-unit scope to insert this function into.
2018  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2019  // relate Scopes to DeclContexts, and probably eliminate CurContext
2020  // entirely, but we're not there yet.
2021  DeclContext *SavedContext = CurContext;
2022  CurContext = Parent;
2023  PushOnScopeChains(New, TUScope);
2024  CurContext = SavedContext;
2025  return New;
2026 }
2027 
2028 /// Typedef declarations don't have linkage, but they still denote the same
2029 /// entity if their types are the same.
2030 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2031 /// isSameEntity.
2035  // This is only interesting when modules are enabled.
2036  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2037  return;
2038 
2039  // Empty sets are uninteresting.
2040  if (Previous.empty())
2041  return;
2042 
2043  LookupResult::Filter Filter = Previous.makeFilter();
2044  while (Filter.hasNext()) {
2045  NamedDecl *Old = Filter.next();
2046 
2047  // Non-hidden declarations are never ignored.
2048  if (S.isVisible(Old))
2049  continue;
2050 
2051  // Declarations of the same entity are not ignored, even if they have
2052  // different linkages.
2053  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2054  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2055  Decl->getUnderlyingType()))
2056  continue;
2057 
2058  // If both declarations give a tag declaration a typedef name for linkage
2059  // purposes, then they declare the same entity.
2060  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2062  continue;
2063  }
2064 
2065  Filter.erase();
2066  }
2067 
2068  Filter.done();
2069 }
2070 
2072  QualType OldType;
2073  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2074  OldType = OldTypedef->getUnderlyingType();
2075  else
2076  OldType = Context.getTypeDeclType(Old);
2077  QualType NewType = New->getUnderlyingType();
2078 
2079  if (NewType->isVariablyModifiedType()) {
2080  // Must not redefine a typedef with a variably-modified type.
2081  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2082  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2083  << Kind << NewType;
2084  if (Old->getLocation().isValid())
2085  notePreviousDefinition(Old, New->getLocation());
2086  New->setInvalidDecl();
2087  return true;
2088  }
2089 
2090  if (OldType != NewType &&
2091  !OldType->isDependentType() &&
2092  !NewType->isDependentType() &&
2093  !Context.hasSameType(OldType, NewType)) {
2094  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2095  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2096  << Kind << NewType << OldType;
2097  if (Old->getLocation().isValid())
2098  notePreviousDefinition(Old, New->getLocation());
2099  New->setInvalidDecl();
2100  return true;
2101  }
2102  return false;
2103 }
2104 
2105 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2106 /// same name and scope as a previous declaration 'Old'. Figure out
2107 /// how to resolve this situation, merging decls or emitting
2108 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2109 ///
2111  LookupResult &OldDecls) {
2112  // If the new decl is known invalid already, don't bother doing any
2113  // merging checks.
2114  if (New->isInvalidDecl()) return;
2115 
2116  // Allow multiple definitions for ObjC built-in typedefs.
2117  // FIXME: Verify the underlying types are equivalent!
2118  if (getLangOpts().ObjC1) {
2119  const IdentifierInfo *TypeID = New->getIdentifier();
2120  switch (TypeID->getLength()) {
2121  default: break;
2122  case 2:
2123  {
2124  if (!TypeID->isStr("id"))
2125  break;
2126  QualType T = New->getUnderlyingType();
2127  if (!T->isPointerType())
2128  break;
2129  if (!T->isVoidPointerType()) {
2130  QualType PT = T->getAs<PointerType>()->getPointeeType();
2131  if (!PT->isStructureType())
2132  break;
2133  }
2134  Context.setObjCIdRedefinitionType(T);
2135  // Install the built-in type for 'id', ignoring the current definition.
2136  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2137  return;
2138  }
2139  case 5:
2140  if (!TypeID->isStr("Class"))
2141  break;
2143  // Install the built-in type for 'Class', ignoring the current definition.
2144  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2145  return;
2146  case 3:
2147  if (!TypeID->isStr("SEL"))
2148  break;
2150  // Install the built-in type for 'SEL', ignoring the current definition.
2151  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2152  return;
2153  }
2154  // Fall through - the typedef name was not a builtin type.
2155  }
2156 
2157  // Verify the old decl was also a type.
2158  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2159  if (!Old) {
2160  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2161  << New->getDeclName();
2162 
2163  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2164  if (OldD->getLocation().isValid())
2165  notePreviousDefinition(OldD, New->getLocation());
2166 
2167  return New->setInvalidDecl();
2168  }
2169 
2170  // If the old declaration is invalid, just give up here.
2171  if (Old->isInvalidDecl())
2172  return New->setInvalidDecl();
2173 
2174  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2175  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2176  auto *NewTag = New->getAnonDeclWithTypedefName();
2177  NamedDecl *Hidden = nullptr;
2178  if (OldTag && NewTag &&
2179  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2180  !hasVisibleDefinition(OldTag, &Hidden)) {
2181  // There is a definition of this tag, but it is not visible. Use it
2182  // instead of our tag.
2183  New->setTypeForDecl(OldTD->getTypeForDecl());
2184  if (OldTD->isModed())
2185  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2186  OldTD->getUnderlyingType());
2187  else
2188  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2189 
2190  // Make the old tag definition visible.
2191  makeMergedDefinitionVisible(Hidden);
2192 
2193  // If this was an unscoped enumeration, yank all of its enumerators
2194  // out of the scope.
2195  if (isa<EnumDecl>(NewTag)) {
2196  Scope *EnumScope = getNonFieldDeclScope(S);
2197  for (auto *D : NewTag->decls()) {
2198  auto *ED = cast<EnumConstantDecl>(D);
2199  assert(EnumScope->isDeclScope(ED));
2200  EnumScope->RemoveDecl(ED);
2201  IdResolver.RemoveDecl(ED);
2202  ED->getLexicalDeclContext()->removeDecl(ED);
2203  }
2204  }
2205  }
2206  }
2207 
2208  // If the typedef types are not identical, reject them in all languages and
2209  // with any extensions enabled.
2210  if (isIncompatibleTypedef(Old, New))
2211  return;
2212 
2213  // The types match. Link up the redeclaration chain and merge attributes if
2214  // the old declaration was a typedef.
2215  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2216  New->setPreviousDecl(Typedef);
2217  mergeDeclAttributes(New, Old);
2218  }
2219 
2220  if (getLangOpts().MicrosoftExt)
2221  return;
2222 
2223  if (getLangOpts().CPlusPlus) {
2224  // C++ [dcl.typedef]p2:
2225  // In a given non-class scope, a typedef specifier can be used to
2226  // redefine the name of any type declared in that scope to refer
2227  // to the type to which it already refers.
2228  if (!isa<CXXRecordDecl>(CurContext))
2229  return;
2230 
2231  // C++0x [dcl.typedef]p4:
2232  // In a given class scope, a typedef specifier can be used to redefine
2233  // any class-name declared in that scope that is not also a typedef-name
2234  // to refer to the type to which it already refers.
2235  //
2236  // This wording came in via DR424, which was a correction to the
2237  // wording in DR56, which accidentally banned code like:
2238  //
2239  // struct S {
2240  // typedef struct A { } A;
2241  // };
2242  //
2243  // in the C++03 standard. We implement the C++0x semantics, which
2244  // allow the above but disallow
2245  //
2246  // struct S {
2247  // typedef int I;
2248  // typedef int I;
2249  // };
2250  //
2251  // since that was the intent of DR56.
2252  if (!isa<TypedefNameDecl>(Old))
2253  return;
2254 
2255  Diag(New->getLocation(), diag::err_redefinition)
2256  << New->getDeclName();
2257  notePreviousDefinition(Old, New->getLocation());
2258  return New->setInvalidDecl();
2259  }
2260 
2261  // Modules always permit redefinition of typedefs, as does C11.
2262  if (getLangOpts().Modules || getLangOpts().C11)
2263  return;
2264 
2265  // If we have a redefinition of a typedef in C, emit a warning. This warning
2266  // is normally mapped to an error, but can be controlled with
2267  // -Wtypedef-redefinition. If either the original or the redefinition is
2268  // in a system header, don't emit this for compatibility with GCC.
2269  if (getDiagnostics().getSuppressSystemWarnings() &&
2270  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2271  (Old->isImplicit() ||
2272  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2273  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2274  return;
2275 
2276  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2277  << New->getDeclName();
2278  notePreviousDefinition(Old, New->getLocation());
2279 }
2280 
2281 /// DeclhasAttr - returns true if decl Declaration already has the target
2282 /// attribute.
2283 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2284  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2285  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2286  for (const auto *i : D->attrs())
2287  if (i->getKind() == A->getKind()) {
2288  if (Ann) {
2289  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2290  return true;
2291  continue;
2292  }
2293  // FIXME: Don't hardcode this check
2294  if (OA && isa<OwnershipAttr>(i))
2295  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2296  return true;
2297  }
2298 
2299  return false;
2300 }
2301 
2303  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2304  return VD->isThisDeclarationADefinition();
2305  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2306  return TD->isCompleteDefinition() || TD->isBeingDefined();
2307  return true;
2308 }
2309 
2310 /// Merge alignment attributes from \p Old to \p New, taking into account the
2311 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2312 ///
2313 /// \return \c true if any attributes were added to \p New.
2314 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2315  // Look for alignas attributes on Old, and pick out whichever attribute
2316  // specifies the strictest alignment requirement.
2317  AlignedAttr *OldAlignasAttr = nullptr;
2318  AlignedAttr *OldStrictestAlignAttr = nullptr;
2319  unsigned OldAlign = 0;
2320  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2321  // FIXME: We have no way of representing inherited dependent alignments
2322  // in a case like:
2323  // template<int A, int B> struct alignas(A) X;
2324  // template<int A, int B> struct alignas(B) X {};
2325  // For now, we just ignore any alignas attributes which are not on the
2326  // definition in such a case.
2327  if (I->isAlignmentDependent())
2328  return false;
2329 
2330  if (I->isAlignas())
2331  OldAlignasAttr = I;
2332 
2333  unsigned Align = I->getAlignment(S.Context);
2334  if (Align > OldAlign) {
2335  OldAlign = Align;
2336  OldStrictestAlignAttr = I;
2337  }
2338  }
2339 
2340  // Look for alignas attributes on New.
2341  AlignedAttr *NewAlignasAttr = nullptr;
2342  unsigned NewAlign = 0;
2343  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2344  if (I->isAlignmentDependent())
2345  return false;
2346 
2347  if (I->isAlignas())
2348  NewAlignasAttr = I;
2349 
2350  unsigned Align = I->getAlignment(S.Context);
2351  if (Align > NewAlign)
2352  NewAlign = Align;
2353  }
2354 
2355  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2356  // Both declarations have 'alignas' attributes. We require them to match.
2357  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2358  // fall short. (If two declarations both have alignas, they must both match
2359  // every definition, and so must match each other if there is a definition.)
2360 
2361  // If either declaration only contains 'alignas(0)' specifiers, then it
2362  // specifies the natural alignment for the type.
2363  if (OldAlign == 0 || NewAlign == 0) {
2364  QualType Ty;
2365  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2366  Ty = VD->getType();
2367  else
2368  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2369 
2370  if (OldAlign == 0)
2371  OldAlign = S.Context.getTypeAlign(Ty);
2372  if (NewAlign == 0)
2373  NewAlign = S.Context.getTypeAlign(Ty);
2374  }
2375 
2376  if (OldAlign != NewAlign) {
2377  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2378  << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2379  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2380  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2381  }
2382  }
2383 
2384  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2385  // C++11 [dcl.align]p6:
2386  // if any declaration of an entity has an alignment-specifier,
2387  // every defining declaration of that entity shall specify an
2388  // equivalent alignment.
2389  // C11 6.7.5/7:
2390  // If the definition of an object does not have an alignment
2391  // specifier, any other declaration of that object shall also
2392  // have no alignment specifier.
2393  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2394  << OldAlignasAttr;
2395  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2396  << OldAlignasAttr;
2397  }
2398 
2399  bool AnyAdded = false;
2400 
2401  // Ensure we have an attribute representing the strictest alignment.
2402  if (OldAlign > NewAlign) {
2403  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2404  Clone->setInherited(true);
2405  New->addAttr(Clone);
2406  AnyAdded = true;
2407  }
2408 
2409  // Ensure we have an alignas attribute if the old declaration had one.
2410  if (OldAlignasAttr && !NewAlignasAttr &&
2411  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2412  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2413  Clone->setInherited(true);
2414  New->addAttr(Clone);
2415  AnyAdded = true;
2416  }
2417 
2418  return AnyAdded;
2419 }
2420 
2421 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2422  const InheritableAttr *Attr,
2424  // This function copies an attribute Attr from a previous declaration to the
2425  // new declaration D if the new declaration doesn't itself have that attribute
2426  // yet or if that attribute allows duplicates.
2427  // If you're adding a new attribute that requires logic different from
2428  // "use explicit attribute on decl if present, else use attribute from
2429  // previous decl", for example if the attribute needs to be consistent
2430  // between redeclarations, you need to call a custom merge function here.
2431  InheritableAttr *NewAttr = nullptr;
2432  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2433  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2434  NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2435  AA->isImplicit(), AA->getIntroduced(),
2436  AA->getDeprecated(),
2437  AA->getObsoleted(), AA->getUnavailable(),
2438  AA->getMessage(), AA->getStrict(),
2439  AA->getReplacement(), AMK,
2440  AttrSpellingListIndex);
2441  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2442  NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2443  AttrSpellingListIndex);
2444  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2445  NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2446  AttrSpellingListIndex);
2447  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2448  NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2449  AttrSpellingListIndex);
2450  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2451  NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2452  AttrSpellingListIndex);
2453  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2454  NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2455  FA->getFormatIdx(), FA->getFirstArg(),
2456  AttrSpellingListIndex);
2457  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2458  NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2459  AttrSpellingListIndex);
2460  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2461  NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2462  AttrSpellingListIndex,
2463  IA->getSemanticSpelling());
2464  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2465  NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2466  &S.Context.Idents.get(AA->getSpelling()),
2467  AttrSpellingListIndex);
2468  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2469  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2470  isa<CUDAGlobalAttr>(Attr))) {
2471  // CUDA target attributes are part of function signature for
2472  // overloading purposes and must not be merged.
2473  return false;
2474  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2475  NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2476  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2477  NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2478  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2479  NewAttr = S.mergeInternalLinkageAttr(
2480  D, InternalLinkageA->getRange(),
2481  &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2482  AttrSpellingListIndex);
2483  else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2484  NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2485  &S.Context.Idents.get(CommonA->getSpelling()),
2486  AttrSpellingListIndex);
2487  else if (isa<AlignedAttr>(Attr))
2488  // AlignedAttrs are handled separately, because we need to handle all
2489  // such attributes on a declaration at the same time.
2490  NewAttr = nullptr;
2491  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2492  (AMK == Sema::AMK_Override ||
2494  NewAttr = nullptr;
2495  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2496  NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2497  UA->getGuid());
2498  else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2499  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2500 
2501  if (NewAttr) {
2502  NewAttr->setInherited(true);
2503  D->addAttr(NewAttr);
2504  if (isa<MSInheritanceAttr>(NewAttr))
2505  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2506  return true;
2507  }
2508 
2509  return false;
2510 }
2511 
2512 static const NamedDecl *getDefinition(const Decl *D) {
2513  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2514  return TD->getDefinition();
2515  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2516  const VarDecl *Def = VD->getDefinition();
2517  if (Def)
2518  return Def;
2519  return VD->getActingDefinition();
2520  }
2521  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2522  return FD->getDefinition();
2523  return nullptr;
2524 }
2525 
2526 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2527  for (const auto *Attribute : D->attrs())
2528  if (Attribute->getKind() == Kind)
2529  return true;
2530  return false;
2531 }
2532 
2533 /// checkNewAttributesAfterDef - If we already have a definition, check that
2534 /// there are no new attributes in this declaration.
2535 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2536  if (!New->hasAttrs())
2537  return;
2538 
2539  const NamedDecl *Def = getDefinition(Old);
2540  if (!Def || Def == New)
2541  return;
2542 
2543  AttrVec &NewAttributes = New->getAttrs();
2544  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2545  const Attr *NewAttribute = NewAttributes[I];
2546 
2547  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2548  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2549  Sema::SkipBodyInfo SkipBody;
2550  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2551 
2552  // If we're skipping this definition, drop the "alias" attribute.
2553  if (SkipBody.ShouldSkip) {
2554  NewAttributes.erase(NewAttributes.begin() + I);
2555  --E;
2556  continue;
2557  }
2558  } else {
2559  VarDecl *VD = cast<VarDecl>(New);
2560  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2562  ? diag::err_alias_after_tentative
2563  : diag::err_redefinition;
2564  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2565  if (Diag == diag::err_redefinition)
2566  S.notePreviousDefinition(Def, VD->getLocation());
2567  else
2568  S.Diag(Def->getLocation(), diag::note_previous_definition);
2569  VD->setInvalidDecl();
2570  }
2571  ++I;
2572  continue;
2573  }
2574 
2575  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2576  // Tentative definitions are only interesting for the alias check above.
2577  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2578  ++I;
2579  continue;
2580  }
2581  }
2582 
2583  if (hasAttribute(Def, NewAttribute->getKind())) {
2584  ++I;
2585  continue; // regular attr merging will take care of validating this.
2586  }
2587 
2588  if (isa<C11NoReturnAttr>(NewAttribute)) {
2589  // C's _Noreturn is allowed to be added to a function after it is defined.
2590  ++I;
2591  continue;
2592  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2593  if (AA->isAlignas()) {
2594  // C++11 [dcl.align]p6:
2595  // if any declaration of an entity has an alignment-specifier,
2596  // every defining declaration of that entity shall specify an
2597  // equivalent alignment.
2598  // C11 6.7.5/7:
2599  // If the definition of an object does not have an alignment
2600  // specifier, any other declaration of that object shall also
2601  // have no alignment specifier.
2602  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2603  << AA;
2604  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2605  << AA;
2606  NewAttributes.erase(NewAttributes.begin() + I);
2607  --E;
2608  continue;
2609  }
2610  }
2611 
2612  S.Diag(NewAttribute->getLocation(),
2613  diag::warn_attribute_precede_definition);
2614  S.Diag(Def->getLocation(), diag::note_previous_definition);
2615  NewAttributes.erase(NewAttributes.begin() + I);
2616  --E;
2617  }
2618 }
2619 
2620 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2622  AvailabilityMergeKind AMK) {
2623  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2624  UsedAttr *NewAttr = OldAttr->clone(Context);
2625  NewAttr->setInherited(true);
2626  New->addAttr(NewAttr);
2627  }
2628 
2629  if (!Old->hasAttrs() && !New->hasAttrs())
2630  return;
2631 
2632  // Attributes declared post-definition are currently ignored.
2633  checkNewAttributesAfterDef(*this, New, Old);
2634 
2635  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2636  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2637  if (OldA->getLabel() != NewA->getLabel()) {
2638  // This redeclaration changes __asm__ label.
2639  Diag(New->getLocation(), diag::err_different_asm_label);
2640  Diag(OldA->getLocation(), diag::note_previous_declaration);
2641  }
2642  } else if (Old->isUsed()) {
2643  // This redeclaration adds an __asm__ label to a declaration that has
2644  // already been ODR-used.
2645  Diag(New->getLocation(), diag::err_late_asm_label_name)
2646  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2647  }
2648  }
2649 
2650  // Re-declaration cannot add abi_tag's.
2651  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2652  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2653  for (const auto &NewTag : NewAbiTagAttr->tags()) {
2654  if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2655  NewTag) == OldAbiTagAttr->tags_end()) {
2656  Diag(NewAbiTagAttr->getLocation(),
2657  diag::err_new_abi_tag_on_redeclaration)
2658  << NewTag;
2659  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2660  }
2661  }
2662  } else {
2663  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2664  Diag(Old->getLocation(), diag::note_previous_declaration);
2665  }
2666  }
2667 
2668  // This redeclaration adds a section attribute.
2669  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2670  if (auto *VD = dyn_cast<VarDecl>(New)) {
2671  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2672  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2673  Diag(Old->getLocation(), diag::note_previous_declaration);
2674  }
2675  }
2676  }
2677 
2678  if (!Old->hasAttrs())
2679  return;
2680 
2681  bool foundAny = New->hasAttrs();
2682 
2683  // Ensure that any moving of objects within the allocated map is done before
2684  // we process them.
2685  if (!foundAny) New->setAttrs(AttrVec());
2686 
2687  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2688  // Ignore deprecated/unavailable/availability attributes if requested.
2689  AvailabilityMergeKind LocalAMK = AMK_None;
2690  if (isa<DeprecatedAttr>(I) ||
2691  isa<UnavailableAttr>(I) ||
2692  isa<AvailabilityAttr>(I)) {
2693  switch (AMK) {
2694  case AMK_None:
2695  continue;
2696 
2697  case AMK_Redeclaration:
2698  case AMK_Override:
2699  case AMK_ProtocolImplementation:
2700  LocalAMK = AMK;
2701  break;
2702  }
2703  }
2704 
2705  // Already handled.
2706  if (isa<UsedAttr>(I))
2707  continue;
2708 
2709  if (mergeDeclAttribute(*this, New, I, LocalAMK))
2710  foundAny = true;
2711  }
2712 
2713  if (mergeAlignedAttrs(*this, New, Old))
2714  foundAny = true;
2715 
2716  if (!foundAny) New->dropAttrs();
2717 }
2718 
2719 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2720 /// to the new one.
2722  const ParmVarDecl *oldDecl,
2723  Sema &S) {
2724  // C++11 [dcl.attr.depend]p2:
2725  // The first declaration of a function shall specify the
2726  // carries_dependency attribute for its declarator-id if any declaration
2727  // of the function specifies the carries_dependency attribute.
2728  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2729  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2730  S.Diag(CDA->getLocation(),
2731  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2732  // Find the first declaration of the parameter.
2733  // FIXME: Should we build redeclaration chains for function parameters?
2734  const FunctionDecl *FirstFD =
2735  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2736  const ParmVarDecl *FirstVD =
2737  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2738  S.Diag(FirstVD->getLocation(),
2739  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2740  }
2741 
2742  if (!oldDecl->hasAttrs())
2743  return;
2744 
2745  bool foundAny = newDecl->hasAttrs();
2746 
2747  // Ensure that any moving of objects within the allocated map is
2748  // done before we process them.
2749  if (!foundAny) newDecl->setAttrs(AttrVec());
2750 
2751  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2752  if (!DeclHasAttr(newDecl, I)) {
2753  InheritableAttr *newAttr =
2754  cast<InheritableParamAttr>(I->clone(S.Context));
2755  newAttr->setInherited(true);
2756  newDecl->addAttr(newAttr);
2757  foundAny = true;
2758  }
2759  }
2760 
2761  if (!foundAny) newDecl->dropAttrs();
2762 }
2763 
2764 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2765  const ParmVarDecl *OldParam,
2766  Sema &S) {
2767  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2768  if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2769  if (*Oldnullability != *Newnullability) {
2770  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2772  *Newnullability,
2774  != 0))
2776  *Oldnullability,
2778  != 0));
2779  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2780  }
2781  } else {
2782  QualType NewT = NewParam->getType();
2783  NewT = S.Context.getAttributedType(
2784  AttributedType::getNullabilityAttrKind(*Oldnullability),
2785  NewT, NewT);
2786  NewParam->setType(NewT);
2787  }
2788  }
2789 }
2790 
2791 namespace {
2792 
2793 /// Used in MergeFunctionDecl to keep track of function parameters in
2794 /// C.
2795 struct GNUCompatibleParamWarning {
2796  ParmVarDecl *OldParm;
2797  ParmVarDecl *NewParm;
2798  QualType PromotedType;
2799 };
2800 
2801 } // end anonymous namespace
2802 
2803 /// getSpecialMember - get the special member enum for a method.
2805  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2806  if (Ctor->isDefaultConstructor())
2808 
2809  if (Ctor->isCopyConstructor())
2810  return Sema::CXXCopyConstructor;
2811 
2812  if (Ctor->isMoveConstructor())
2813  return Sema::CXXMoveConstructor;
2814  } else if (isa<CXXDestructorDecl>(MD)) {
2815  return Sema::CXXDestructor;
2816  } else if (MD->isCopyAssignmentOperator()) {
2817  return Sema::CXXCopyAssignment;
2818  } else if (MD->isMoveAssignmentOperator()) {
2819  return Sema::CXXMoveAssignment;
2820  }
2821 
2822  return Sema::CXXInvalid;
2823 }
2824 
2825 // Determine whether the previous declaration was a definition, implicit
2826 // declaration, or a declaration.
2827 template <typename T>
2828 static std::pair<diag::kind, SourceLocation>
2829 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2830  diag::kind PrevDiag;
2831  SourceLocation OldLocation = Old->getLocation();
2832  if (Old->isThisDeclarationADefinition())
2833  PrevDiag = diag::note_previous_definition;
2834  else if (Old->isImplicit()) {
2835  PrevDiag = diag::note_previous_implicit_declaration;
2836  if (OldLocation.isInvalid())
2837  OldLocation = New->getLocation();
2838  } else
2839  PrevDiag = diag::note_previous_declaration;
2840  return std::make_pair(PrevDiag, OldLocation);
2841 }
2842 
2843 /// canRedefineFunction - checks if a function can be redefined. Currently,
2844 /// only extern inline functions can be redefined, and even then only in
2845 /// GNU89 mode.
2846 static bool canRedefineFunction(const FunctionDecl *FD,
2847  const LangOptions& LangOpts) {
2848  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2849  !LangOpts.CPlusPlus &&
2850  FD->isInlineSpecified() &&
2851  FD->getStorageClass() == SC_Extern);
2852 }
2853 
2855  const AttributedType *AT = T->getAs<AttributedType>();
2856  while (AT && !AT->isCallingConv())
2857  AT = AT->getModifiedType()->getAs<AttributedType>();
2858  return AT;
2859 }
2860 
2861 template <typename T>
2862 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2863  const DeclContext *DC = Old->getDeclContext();
2864  if (DC->isRecord())
2865  return false;
2866 
2867  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2868  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2869  return true;
2870  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2871  return true;
2872  return false;
2873 }
2874 
2875 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2876 static bool isExternC(VarTemplateDecl *) { return false; }
2877 
2878 /// \brief Check whether a redeclaration of an entity introduced by a
2879 /// using-declaration is valid, given that we know it's not an overload
2880 /// (nor a hidden tag declaration).
2881 template<typename ExpectedDecl>
2883  ExpectedDecl *New) {
2884  // C++11 [basic.scope.declarative]p4:
2885  // Given a set of declarations in a single declarative region, each of
2886  // which specifies the same unqualified name,
2887  // -- they shall all refer to the same entity, or all refer to functions
2888  // and function templates; or
2889  // -- exactly one declaration shall declare a class name or enumeration
2890  // name that is not a typedef name and the other declarations shall all
2891  // refer to the same variable or enumerator, or all refer to functions
2892  // and function templates; in this case the class name or enumeration
2893  // name is hidden (3.3.10).
2894 
2895  // C++11 [namespace.udecl]p14:
2896  // If a function declaration in namespace scope or block scope has the
2897  // same name and the same parameter-type-list as a function introduced
2898  // by a using-declaration, and the declarations do not declare the same
2899  // function, the program is ill-formed.
2900 
2901  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2902  if (Old &&
2903  !Old->getDeclContext()->getRedeclContext()->Equals(
2904  New->getDeclContext()->getRedeclContext()) &&
2905  !(isExternC(Old) && isExternC(New)))
2906  Old = nullptr;
2907 
2908  if (!Old) {
2909  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2910  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2911  S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2912  return true;
2913  }
2914  return false;
2915 }
2916 
2918  const FunctionDecl *B) {
2919  assert(A->getNumParams() == B->getNumParams());
2920 
2921  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2922  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2923  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2924  if (AttrA == AttrB)
2925  return true;
2926  return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2927  };
2928 
2929  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2930 }
2931 
2932 /// MergeFunctionDecl - We just parsed a function 'New' from
2933 /// declarator D which has the same name and scope as a previous
2934 /// declaration 'Old'. Figure out how to resolve this situation,
2935 /// merging decls or emitting diagnostics as appropriate.
2936 ///
2937 /// In C++, New and Old must be declarations that are not
2938 /// overloaded. Use IsOverload to determine whether New and Old are
2939 /// overloaded, and to select the Old declaration that New should be
2940 /// merged with.
2941 ///
2942 /// Returns true if there was an error, false otherwise.
2944  Scope *S, bool MergeTypeWithOld) {
2945  // Verify the old decl was also a function.
2946  FunctionDecl *Old = OldD->getAsFunction();
2947  if (!Old) {
2948  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2949  if (New->getFriendObjectKind()) {
2950  Diag(New->getLocation(), diag::err_using_decl_friend);
2951  Diag(Shadow->getTargetDecl()->getLocation(),
2952  diag::note_using_decl_target);
2953  Diag(Shadow->getUsingDecl()->getLocation(),
2954  diag::note_using_decl) << 0;
2955  return true;
2956  }
2957 
2958  // Check whether the two declarations might declare the same function.
2959  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2960  return true;
2961  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2962  } else {
2963  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2964  << New->getDeclName();
2965  notePreviousDefinition(OldD, New->getLocation());
2966  return true;
2967  }
2968  }
2969 
2970  // If the old declaration is invalid, just give up here.
2971  if (Old->isInvalidDecl())
2972  return true;
2973 
2974  diag::kind PrevDiag;
2975  SourceLocation OldLocation;
2976  std::tie(PrevDiag, OldLocation) =
2978 
2979  // Don't complain about this if we're in GNU89 mode and the old function
2980  // is an extern inline function.
2981  // Don't complain about specializations. They are not supposed to have
2982  // storage classes.
2983  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2984  New->getStorageClass() == SC_Static &&
2985  Old->hasExternalFormalLinkage() &&
2987  !canRedefineFunction(Old, getLangOpts())) {
2988  if (getLangOpts().MicrosoftExt) {
2989  Diag(New->getLocation(), diag::ext_static_non_static) << New;
2990  Diag(OldLocation, PrevDiag);
2991  } else {
2992  Diag(New->getLocation(), diag::err_static_non_static) << New;
2993  Diag(OldLocation, PrevDiag);
2994  return true;
2995  }
2996  }
2997 
2998  if (New->hasAttr<InternalLinkageAttr>() &&
2999  !Old->hasAttr<InternalLinkageAttr>()) {
3000  Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3001  << New->getDeclName();
3002  notePreviousDefinition(Old, New->getLocation());
3003  New->dropAttr<InternalLinkageAttr>();
3004  }
3005 
3006  if (CheckRedeclarationModuleOwnership(New, Old))
3007  return true;
3008 
3009  if (!getLangOpts().CPlusPlus) {
3010  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3011  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3012  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3013  << New << OldOvl;
3014 
3015  // Try our best to find a decl that actually has the overloadable
3016  // attribute for the note. In most cases (e.g. programs with only one
3017  // broken declaration/definition), this won't matter.
3018  //
3019  // FIXME: We could do this if we juggled some extra state in
3020  // OverloadableAttr, rather than just removing it.
3021  const Decl *DiagOld = Old;
3022  if (OldOvl) {
3023  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3024  const auto *A = D->getAttr<OverloadableAttr>();
3025  return A && !A->isImplicit();
3026  });
3027  // If we've implicitly added *all* of the overloadable attrs to this
3028  // chain, emitting a "previous redecl" note is pointless.
3029  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3030  }
3031 
3032  if (DiagOld)
3033  Diag(DiagOld->getLocation(),
3034  diag::note_attribute_overloadable_prev_overload)
3035  << OldOvl;
3036 
3037  if (OldOvl)
3038  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3039  else
3040  New->dropAttr<OverloadableAttr>();
3041  }
3042  }
3043 
3044  // If a function is first declared with a calling convention, but is later
3045  // declared or defined without one, all following decls assume the calling
3046  // convention of the first.
3047  //
3048  // It's OK if a function is first declared without a calling convention,
3049  // but is later declared or defined with the default calling convention.
3050  //
3051  // To test if either decl has an explicit calling convention, we look for
3052  // AttributedType sugar nodes on the type as written. If they are missing or
3053  // were canonicalized away, we assume the calling convention was implicit.
3054  //
3055  // Note also that we DO NOT return at this point, because we still have
3056  // other tests to run.
3057  QualType OldQType = Context.getCanonicalType(Old->getType());
3058  QualType NewQType = Context.getCanonicalType(New->getType());
3059  const FunctionType *OldType = cast<FunctionType>(OldQType);
3060  const FunctionType *NewType = cast<FunctionType>(NewQType);
3061  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3062  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3063  bool RequiresAdjustment = false;
3064 
3065  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3066  FunctionDecl *First = Old->getFirstDecl();
3067  const FunctionType *FT =
3069  FunctionType::ExtInfo FI = FT->getExtInfo();
3070  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3071  if (!NewCCExplicit) {
3072  // Inherit the CC from the previous declaration if it was specified
3073  // there but not here.
3074  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3075  RequiresAdjustment = true;
3076  } else {
3077  // Calling conventions aren't compatible, so complain.
3078  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3079  Diag(New->getLocation(), diag::err_cconv_change)
3080  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3081  << !FirstCCExplicit
3082  << (!FirstCCExplicit ? "" :
3083  FunctionType::getNameForCallConv(FI.getCC()));
3084 
3085  // Put the note on the first decl, since it is the one that matters.
3086  Diag(First->getLocation(), diag::note_previous_declaration);
3087  return true;
3088  }
3089  }
3090 
3091  // FIXME: diagnose the other way around?
3092  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3093  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3094  RequiresAdjustment = true;
3095  }
3096 
3097  // Merge regparm attribute.
3098  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3099  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3100  if (NewTypeInfo.getHasRegParm()) {
3101  Diag(New->getLocation(), diag::err_regparm_mismatch)
3102  << NewType->getRegParmType()
3103  << OldType->getRegParmType();
3104  Diag(OldLocation, diag::note_previous_declaration);
3105  return true;
3106  }
3107 
3108  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3109  RequiresAdjustment = true;
3110  }
3111 
3112  // Merge ns_returns_retained attribute.
3113  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3114  if (NewTypeInfo.getProducesResult()) {
3115  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3116  << "'ns_returns_retained'";
3117  Diag(OldLocation, diag::note_previous_declaration);
3118  return true;
3119  }
3120 
3121  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3122  RequiresAdjustment = true;
3123  }
3124 
3125  if (OldTypeInfo.getNoCallerSavedRegs() !=
3126  NewTypeInfo.getNoCallerSavedRegs()) {
3127  if (NewTypeInfo.getNoCallerSavedRegs()) {
3128  AnyX86NoCallerSavedRegistersAttr *Attr =
3129  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3130  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3131  Diag(OldLocation, diag::note_previous_declaration);
3132  return true;
3133  }
3134 
3135  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3136  RequiresAdjustment = true;
3137  }
3138 
3139  if (RequiresAdjustment) {
3140  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3141  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3142  New->setType(QualType(AdjustedType, 0));
3143  NewQType = Context.getCanonicalType(New->getType());
3144  NewType = cast<FunctionType>(NewQType);
3145  }
3146 
3147  // If this redeclaration makes the function inline, we may need to add it to
3148  // UndefinedButUsed.
3149  if (!Old->isInlined() && New->isInlined() &&
3150  !New->hasAttr<GNUInlineAttr>() &&
3151  !getLangOpts().GNUInline &&
3152  Old->isUsed(false) &&
3153  !Old->isDefined() && !New->isThisDeclarationADefinition())
3154  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3155  SourceLocation()));
3156 
3157  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3158  // about it.
3159  if (New->hasAttr<GNUInlineAttr>() &&
3160  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3161  UndefinedButUsed.erase(Old->getCanonicalDecl());
3162  }
3163 
3164  // If pass_object_size params don't match up perfectly, this isn't a valid
3165  // redeclaration.
3166  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3167  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3168  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3169  << New->getDeclName();
3170  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3171  return true;
3172  }
3173 
3174  if (getLangOpts().CPlusPlus) {
3175  // C++1z [over.load]p2
3176  // Certain function declarations cannot be overloaded:
3177  // -- Function declarations that differ only in the return type,
3178  // the exception specification, or both cannot be overloaded.
3179 
3180  // Check the exception specifications match. This may recompute the type of
3181  // both Old and New if it resolved exception specifications, so grab the
3182  // types again after this. Because this updates the type, we do this before
3183  // any of the other checks below, which may update the "de facto" NewQType
3184  // but do not necessarily update the type of New.
3185  if (CheckEquivalentExceptionSpec(Old, New))
3186  return true;
3187  OldQType = Context.getCanonicalType(Old->getType());
3188  NewQType = Context.getCanonicalType(New->getType());
3189 
3190  // Go back to the type source info to compare the declared return types,
3191  // per C++1y [dcl.type.auto]p13:
3192  // Redeclarations or specializations of a function or function template
3193  // with a declared return type that uses a placeholder type shall also
3194  // use that placeholder, not a deduced type.
3195  QualType OldDeclaredReturnType =
3196  (Old->getTypeSourceInfo()
3198  : OldType)->getReturnType();
3199  QualType NewDeclaredReturnType =
3200  (New->getTypeSourceInfo()
3202  : NewType)->getReturnType();
3203  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3204  !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3205  New->isLocalExternDecl())) {
3206  QualType ResQT;
3207  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3208  OldDeclaredReturnType->isObjCObjectPointerType())
3209  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3210  if (ResQT.isNull()) {
3211  if (New->isCXXClassMember() && New->isOutOfLine())
3212  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3213  << New << New->getReturnTypeSourceRange();
3214  else
3215  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3216  << New->getReturnTypeSourceRange();
3217  Diag(OldLocation, PrevDiag) << Old << Old->getType()
3218  << Old->getReturnTypeSourceRange();
3219  return true;
3220  }
3221  else
3222  NewQType = ResQT;
3223  }
3224 
3225  QualType OldReturnType = OldType->getReturnType();
3226  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3227  if (OldReturnType != NewReturnType) {
3228  // If this function has a deduced return type and has already been
3229  // defined, copy the deduced value from the old declaration.
3230  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3231  if (OldAT && OldAT->isDeduced()) {
3232  New->setType(
3233  SubstAutoType(New->getType(),
3234  OldAT->isDependentType() ? Context.DependentTy
3235  : OldAT->getDeducedType()));
3236  NewQType = Context.getCanonicalType(
3237  SubstAutoType(NewQType,
3238  OldAT->isDependentType() ? Context.DependentTy
3239  : OldAT->getDeducedType()));
3240  }
3241  }
3242 
3243  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3244  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3245  if (OldMethod && NewMethod) {
3246  // Preserve triviality.
3247  NewMethod->setTrivial(OldMethod->isTrivial());
3248 
3249  // MSVC allows explicit template specialization at class scope:
3250  // 2 CXXMethodDecls referring to the same function will be injected.
3251  // We don't want a redeclaration error.
3252  bool IsClassScopeExplicitSpecialization =
3253  OldMethod->isFunctionTemplateSpecialization() &&
3254  NewMethod->isFunctionTemplateSpecialization();
3255  bool isFriend = NewMethod->getFriendObjectKind();
3256 
3257  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3258  !IsClassScopeExplicitSpecialization) {
3259  // -- Member function declarations with the same name and the
3260  // same parameter types cannot be overloaded if any of them
3261  // is a static member function declaration.
3262  if (OldMethod->isStatic() != NewMethod->isStatic()) {
3263  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3264  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3265  return true;
3266  }
3267 
3268  // C++ [class.mem]p1:
3269  // [...] A member shall not be declared twice in the
3270  // member-specification, except that a nested class or member
3271  // class template can be declared and then later defined.
3272  if (!inTemplateInstantiation()) {
3273  unsigned NewDiag;
3274  if (isa<CXXConstructorDecl>(OldMethod))
3275  NewDiag = diag::err_constructor_redeclared;
3276  else if (isa<CXXDestructorDecl>(NewMethod))
3277  NewDiag = diag::err_destructor_redeclared;
3278  else if (isa<CXXConversionDecl>(NewMethod))
3279  NewDiag = diag::err_conv_function_redeclared;
3280  else
3281  NewDiag = diag::err_member_redeclared;
3282 
3283  Diag(New->getLocation(), NewDiag);
3284  } else {
3285  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3286  << New << New->getType();
3287  }
3288  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3289  return true;
3290 
3291  // Complain if this is an explicit declaration of a special
3292  // member that was initially declared implicitly.
3293  //
3294  // As an exception, it's okay to befriend such methods in order
3295  // to permit the implicit constructor/destructor/operator calls.
3296  } else if (OldMethod->isImplicit()) {
3297  if (isFriend) {
3298  NewMethod->setImplicit();
3299  } else {
3300  Diag(NewMethod->getLocation(),
3301  diag::err_definition_of_implicitly_declared_member)
3302  << New << getSpecialMember(OldMethod);
3303  return true;
3304  }
3305  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3306  Diag(NewMethod->getLocation(),
3307  diag::err_definition_of_explicitly_defaulted_member)
3308  << getSpecialMember(OldMethod);
3309  return true;
3310  }
3311  }
3312 
3313  // C++11 [dcl.attr.noreturn]p1:
3314  // The first declaration of a function shall specify the noreturn
3315  // attribute if any declaration of that function specifies the noreturn
3316  // attribute.
3317  const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3318  if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3319  Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3320  Diag(Old->getFirstDecl()->getLocation(),
3321  diag::note_noreturn_missing_first_decl);
3322  }
3323 
3324  // C++11 [dcl.attr.depend]p2:
3325  // The first declaration of a function shall specify the
3326  // carries_dependency attribute for its declarator-id if any declaration
3327  // of the function specifies the carries_dependency attribute.
3328  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3329  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3330  Diag(CDA->getLocation(),
3331  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3332  Diag(Old->getFirstDecl()->getLocation(),
3333  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3334  }
3335 
3336  // (C++98 8.3.5p3):
3337  // All declarations for a function shall agree exactly in both the
3338  // return type and the parameter-type-list.
3339  // We also want to respect all the extended bits except noreturn.
3340 
3341  // noreturn should now match unless the old type info didn't have it.
3342  QualType OldQTypeForComparison = OldQType;
3343  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3344  auto *OldType = OldQType->castAs<FunctionProtoType>();
3345  const FunctionType *OldTypeForComparison
3346  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3347  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3348  assert(OldQTypeForComparison.isCanonical());
3349  }
3350 
3351  if (haveIncompatibleLanguageLinkages(Old, New)) {
3352  // As a special case, retain the language linkage from previous
3353  // declarations of a friend function as an extension.
3354  //
3355  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3356  // and is useful because there's otherwise no way to specify language
3357  // linkage within class scope.
3358  //
3359  // Check cautiously as the friend object kind isn't yet complete.
3360  if (New->getFriendObjectKind() != Decl::FOK_None) {
3361  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3362  Diag(OldLocation, PrevDiag);
3363  } else {
3364  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3365  Diag(OldLocation, PrevDiag);
3366  return true;
3367  }
3368  }
3369 
3370  if (OldQTypeForComparison == NewQType)
3371  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3372 
3373  if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3374  New->isLocalExternDecl()) {
3375  // It's OK if we couldn't merge types for a local function declaraton
3376  // if either the old or new type is dependent. We'll merge the types
3377  // when we instantiate the function.
3378  return false;
3379  }
3380 
3381  // Fall through for conflicting redeclarations and redefinitions.
3382  }
3383 
3384  // C: Function types need to be compatible, not identical. This handles
3385  // duplicate function decls like "void f(int); void f(enum X);" properly.
3386  if (!getLangOpts().CPlusPlus &&
3387  Context.typesAreCompatible(OldQType, NewQType)) {
3388  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3389  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3390  const FunctionProtoType *OldProto = nullptr;
3391  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3392  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3393  // The old declaration provided a function prototype, but the
3394  // new declaration does not. Merge in the prototype.
3395  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3396  SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3397  NewQType =
3398  Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3399  OldProto->getExtProtoInfo());
3400  New->setType(NewQType);
3401  New->setHasInheritedPrototype();
3402 
3403  // Synthesize parameters with the same types.
3405  for (const auto &ParamType : OldProto->param_types()) {
3406  ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3407  SourceLocation(), nullptr,
3408  ParamType, /*TInfo=*/nullptr,
3409  SC_None, nullptr);
3410  Param->setScopeInfo(0, Params.size());
3411  Param->setImplicit();
3412  Params.push_back(Param);
3413  }
3414 
3415  New->setParams(Params);
3416  }
3417 
3418  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3419  }
3420 
3421  // GNU C permits a K&R definition to follow a prototype declaration
3422  // if the declared types of the parameters in the K&R definition
3423  // match the types in the prototype declaration, even when the
3424  // promoted types of the parameters from the K&R definition differ
3425  // from the types in the prototype. GCC then keeps the types from
3426  // the prototype.
3427  //
3428  // If a variadic prototype is followed by a non-variadic K&R definition,
3429  // the K&R definition becomes variadic. This is sort of an edge case, but
3430  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3431  // C99 6.9.1p8.
3432  if (!getLangOpts().CPlusPlus &&
3433  Old->hasPrototype() && !New->hasPrototype() &&
3434  New->getType()->getAs<FunctionProtoType>() &&
3435  Old->getNumParams() == New->getNumParams()) {
3436  SmallVector<QualType, 16> ArgTypes;
3438  const FunctionProtoType *OldProto
3439  = Old->getType()->getAs<FunctionProtoType>();
3440  const FunctionProtoType *NewProto
3441  = New->getType()->getAs<FunctionProtoType>();
3442 
3443  // Determine whether this is the GNU C extension.
3444  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3445  NewProto->getReturnType());
3446  bool LooseCompatible = !MergedReturn.isNull();
3447  for (unsigned Idx = 0, End = Old->getNumParams();
3448  LooseCompatible && Idx != End; ++Idx) {
3449  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3450  ParmVarDecl *NewParm = New->getParamDecl(Idx);
3451  if (Context.typesAreCompatible(OldParm->getType(),
3452  NewProto->getParamType(Idx))) {
3453  ArgTypes.push_back(NewParm->getType());
3454  } else if (Context.typesAreCompatible(OldParm->getType(),
3455  NewParm->getType(),
3456  /*CompareUnqualified=*/true)) {
3457  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3458  NewProto->getParamType(Idx) };
3459  Warnings.push_back(Warn);
3460  ArgTypes.push_back(NewParm->getType());
3461  } else
3462  LooseCompatible = false;
3463  }
3464 
3465  if (LooseCompatible) {
3466  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3467  Diag(Warnings[Warn].NewParm->getLocation(),
3468  diag::ext_param_promoted_not_compatible_with_prototype)
3469  << Warnings[Warn].PromotedType
3470  << Warnings[Warn].OldParm->getType();
3471  if (Warnings[Warn].OldParm->getLocation().isValid())
3472  Diag(Warnings[Warn].OldParm->getLocation(),
3473  diag::note_previous_declaration);
3474  }
3475 
3476  if (MergeTypeWithOld)
3477  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3478  OldProto->getExtProtoInfo()));
3479  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3480  }
3481 
3482  // Fall through to diagnose conflicting types.
3483  }
3484 
3485  // A function that has already been declared has been redeclared or
3486  // defined with a different type; show an appropriate diagnostic.
3487 
3488  // If the previous declaration was an implicitly-generated builtin
3489  // declaration, then at the very least we should use a specialized note.
3490  unsigned BuiltinID;
3491  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3492  // If it's actually a library-defined builtin function like 'malloc'
3493  // or 'printf', just warn about the incompatible redeclaration.
3494  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3495  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3496  Diag(OldLocation, diag::note_previous_builtin_declaration)
3497  << Old << Old->getType();
3498 
3499  // If this is a global redeclaration, just forget hereafter
3500  // about the "builtin-ness" of the function.
3501  //
3502  // Doing this for local extern declarations is problematic. If
3503  // the builtin declaration remains visible, a second invalid
3504  // local declaration will produce a hard error; if it doesn't
3505  // remain visible, a single bogus local redeclaration (which is
3506  // actually only a warning) could break all the downstream code.
3508  New->getIdentifier()->revertBuiltin();
3509 
3510  return false;
3511  }
3512 
3513  PrevDiag = diag::note_previous_builtin_declaration;
3514  }
3515 
3516  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3517  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3518  return true;
3519 }
3520 
3521 /// \brief Completes the merge of two function declarations that are
3522 /// known to be compatible.
3523 ///
3524 /// This routine handles the merging of attributes and other
3525 /// properties of function declarations from the old declaration to
3526 /// the new declaration, once we know that New is in fact a
3527 /// redeclaration of Old.
3528 ///
3529 /// \returns false
3531  Scope *S, bool MergeTypeWithOld) {
3532  // Merge the attributes
3533  mergeDeclAttributes(New, Old);
3534 
3535  // Merge "pure" flag.
3536  if (Old->isPure())
3537  New->setPure();
3538 
3539  // Merge "used" flag.
3540  if (Old->getMostRecentDecl()->isUsed(false))
3541  New->setIsUsed();
3542 
3543  // Merge attributes from the parameters. These can mismatch with K&R
3544  // declarations.
3545  if (New->getNumParams() == Old->getNumParams())
3546  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3547  ParmVarDecl *NewParam = New->getParamDecl(i);
3548  ParmVarDecl *OldParam = Old->getParamDecl(i);
3549  mergeParamDeclAttributes(NewParam, OldParam, *this);
3550  mergeParamDeclTypes(NewParam, OldParam, *this);
3551  }
3552 
3553  if (getLangOpts().CPlusPlus)
3554  return MergeCXXFunctionDecl(New, Old, S);
3555 
3556  // Merge the function types so the we get the composite types for the return
3557  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3558  // was visible.
3559  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3560  if (!Merged.isNull() && MergeTypeWithOld)
3561  New->setType(Merged);
3562 
3563  return false;
3564 }
3565 
3567  ObjCMethodDecl *oldMethod) {
3568  // Merge the attributes, including deprecated/unavailable
3569  AvailabilityMergeKind MergeKind =
3570  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3571  ? AMK_ProtocolImplementation
3572  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3573  : AMK_Override;
3574 
3575  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3576 
3577  // Merge attributes from the parameters.
3579  oe = oldMethod->param_end();
3581  ni = newMethod->param_begin(), ne = newMethod->param_end();
3582  ni != ne && oi != oe; ++ni, ++oi)
3583  mergeParamDeclAttributes(*ni, *oi, *this);
3584 }
3585 
3586 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3587  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3588 
3590  ? diag::err_redefinition_different_type
3591  : diag::err_redeclaration_different_type)
3592  << New->getDeclName() << New->getType() << Old->getType();
3593 
3594  diag::kind PrevDiag;
3595  SourceLocation OldLocation;
3596  std::tie(PrevDiag, OldLocation)
3598  S.Diag(OldLocation, PrevDiag);
3599  New->setInvalidDecl();
3600 }
3601 
3602 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3603 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3604 /// emitting diagnostics as appropriate.
3605 ///
3606 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3607 /// to here in AddInitializerToDecl. We can't check them before the initializer
3608 /// is attached.
3610  bool MergeTypeWithOld) {
3611  if (New->isInvalidDecl() || Old->isInvalidDecl())
3612  return;
3613 
3614  QualType MergedT;
3615  if (getLangOpts().CPlusPlus) {
3616  if (New->getType()->isUndeducedType()) {
3617  // We don't know what the new type is until the initializer is attached.
3618  return;
3619  } else if (Context.hasSameType(New->getType(), Old->getType())) {
3620  // These could still be something that needs exception specs checked.
3621  return MergeVarDeclExceptionSpecs(New, Old);
3622  }
3623  // C++ [basic.link]p10:
3624  // [...] the types specified by all declarations referring to a given
3625  // object or function shall be identical, except that declarations for an
3626  // array object can specify array types that differ by the presence or
3627  // absence of a major array bound (8.3.4).
3628  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3629  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3630  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3631 
3632  // We are merging a variable declaration New into Old. If it has an array
3633  // bound, and that bound differs from Old's bound, we should diagnose the
3634  // mismatch.
3635  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3636  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3637  PrevVD = PrevVD->getPreviousDecl()) {
3638  const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3639  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3640  continue;
3641 
3642  if (!Context.hasSameType(NewArray, PrevVDTy))
3643  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3644  }
3645  }
3646 
3647  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3648  if (Context.hasSameType(OldArray->getElementType(),
3649  NewArray->getElementType()))
3650  MergedT = New->getType();
3651  }
3652  // FIXME: Check visibility. New is hidden but has a complete type. If New
3653  // has no array bound, it should not inherit one from Old, if Old is not
3654  // visible.
3655  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3656  if (Context.hasSameType(OldArray->getElementType(),
3657  NewArray->getElementType()))
3658  MergedT = Old->getType();
3659  }
3660  }
3661  else if (New->getType()->isObjCObjectPointerType() &&
3662  Old->getType()->isObjCObjectPointerType()) {
3663  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3664  Old->getType());
3665  }
3666  } else {
3667  // C 6.2.7p2:
3668  // All declarations that refer to the same object or function shall have
3669  // compatible type.
3670  MergedT = Context.mergeTypes(New->getType(), Old->getType());
3671  }
3672  if (MergedT.isNull()) {
3673  // It's OK if we couldn't merge types if either type is dependent, for a
3674  // block-scope variable. In other cases (static data members of class
3675  // templates, variable templates, ...), we require the types to be
3676  // equivalent.
3677  // FIXME: The C++ standard doesn't say anything about this.
3678  if ((New->getType()->isDependentType() ||
3679  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3680  // If the old type was dependent, we can't merge with it, so the new type
3681  // becomes dependent for now. We'll reproduce the original type when we
3682  // instantiate the TypeSourceInfo for the variable.
3683  if (!New->getType()->isDependentType() && MergeTypeWithOld)
3684  New->setType(Context.DependentTy);
3685  return;
3686  }
3687  return diagnoseVarDeclTypeMismatch(*this, New, Old);
3688  }
3689 
3690  // Don't actually update the type on the new declaration if the old
3691  // declaration was an extern declaration in a different scope.
3692  if (MergeTypeWithOld)
3693  New->setType(MergedT);
3694 }
3695 
3696 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3698  // C11 6.2.7p4:
3699  // For an identifier with internal or external linkage declared
3700  // in a scope in which a prior declaration of that identifier is
3701  // visible, if the prior declaration specifies internal or
3702  // external linkage, the type of the identifier at the later
3703  // declaration becomes the composite type.
3704  //
3705  // If the variable isn't visible, we do not merge with its type.
3706  if (Previous.isShadowed())
3707  return false;
3708 
3709  if (S.getLangOpts().CPlusPlus) {
3710  // C++11 [dcl.array]p3:
3711  // If there is a preceding declaration of the entity in the same
3712  // scope in which the bound was specified, an omitted array bound
3713  // is taken to be the same as in that earlier declaration.
3714  return NewVD->isPreviousDeclInSameBlockScope() ||
3715  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3717  } else {
3718  // If the old declaration was function-local, don't merge with its
3719  // type unless we're in the same function.
3720  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3721  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3722  }
3723 }
3724 
3725 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3726 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3727 /// situation, merging decls or emitting diagnostics as appropriate.
3728 ///
3729 /// Tentative definition rules (C99 6.9.2p2) are checked by
3730 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3731 /// definitions here, since the initializer hasn't been attached.
3732 ///
3734  // If the new decl is already invalid, don't do any other checking.
3735  if (New->isInvalidDecl())
3736  return;
3737 
3738  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3739  return;
3740 
3741  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3742 
3743  // Verify the old decl was also a variable or variable template.
3744  VarDecl *Old = nullptr;
3745  VarTemplateDecl *OldTemplate = nullptr;
3746  if (Previous.isSingleResult()) {
3747  if (NewTemplate) {
3748  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3749  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3750 
3751  if (auto *Shadow =
3752  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3753  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3754  return New->setInvalidDecl();
3755  } else {
3756  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3757 
3758  if (auto *Shadow =
3759  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3760  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3761  return New->setInvalidDecl();
3762  }
3763  }
3764  if (!Old) {
3765  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3766  << New->getDeclName();
3767  notePreviousDefinition(Previous.getRepresentativeDecl(),
3768  New->getLocation());
3769  return New->setInvalidDecl();
3770  }
3771 
3772  // Ensure the template parameters are compatible.
3773  if (NewTemplate &&
3774  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3775  OldTemplate->getTemplateParameters(),
3776  /*Complain=*/true, TPL_TemplateMatch))
3777  return New->setInvalidDecl();
3778 
3779  // C++ [class.mem]p1:
3780  // A member shall not be declared twice in the member-specification [...]
3781  //
3782  // Here, we need only consider static data members.
3783  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3784  Diag(New->getLocation(), diag::err_duplicate_member)
3785  << New->getIdentifier();
3786  Diag(Old->getLocation(), diag::note_previous_declaration);
3787  New->setInvalidDecl();
3788  }
3789 
3790  mergeDeclAttributes(New, Old);
3791  // Warn if an already-declared variable is made a weak_import in a subsequent
3792  // declaration
3793  if (New->hasAttr<WeakImportAttr>() &&
3794  Old->getStorageClass() == SC_None &&
3795  !Old->hasAttr<WeakImportAttr>()) {
3796  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3797  notePreviousDefinition(Old, New->getLocation());
3798  // Remove weak_import attribute on new declaration.
3799  New->dropAttr<WeakImportAttr>();
3800  }
3801 
3802  if (New->hasAttr<InternalLinkageAttr>() &&
3803  !Old->hasAttr<InternalLinkageAttr>()) {
3804  Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3805  << New->getDeclName();
3806  notePreviousDefinition(Old, New->getLocation());
3807  New->dropAttr<InternalLinkageAttr>();
3808  }
3809 
3810  // Merge the types.
3811  VarDecl *MostRecent = Old->getMostRecentDecl();
3812  if (MostRecent != Old) {
3813  MergeVarDeclTypes(New, MostRecent,
3814  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3815  if (New->isInvalidDecl())
3816  return;
3817  }
3818 
3819  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3820  if (New->isInvalidDecl())
3821  return;
3822 
3823  diag::kind PrevDiag;
3824  SourceLocation OldLocation;
3825  std::tie(PrevDiag, OldLocation) =
3827 
3828  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3829  if (New->getStorageClass() == SC_Static &&
3830  !New->isStaticDataMember() &&
3831  Old->hasExternalFormalLinkage()) {
3832  if (getLangOpts().MicrosoftExt) {
3833  Diag(New->getLocation(), diag::ext_static_non_static)
3834  << New->getDeclName();
3835  Diag(OldLocation, PrevDiag);
3836  } else {
3837  Diag(New->getLocation(), diag::err_static_non_static)
3838  << New->getDeclName();
3839  Diag(OldLocation, PrevDiag);
3840  return New->setInvalidDecl();
3841  }
3842  }
3843  // C99 6.2.2p4:
3844  // For an identifier declared with the storage-class specifier
3845  // extern in a scope in which a prior declaration of that
3846  // identifier is visible,23) if the prior declaration specifies
3847  // internal or external linkage, the linkage of the identifier at
3848  // the later declaration is the same as the linkage specified at
3849  // the prior declaration. If no prior declaration is visible, or
3850  // if the prior declaration specifies no linkage, then the
3851  // identifier has external linkage.
3852  if (New->hasExternalStorage() && Old->hasLinkage())
3853  /* Okay */;
3854  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3855  !New->isStaticDataMember() &&
3857  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3858  Diag(OldLocation, PrevDiag);
3859  return New->setInvalidDecl();
3860  }
3861 
3862  // Check if extern is followed by non-extern and vice-versa.
3863  if (New->hasExternalStorage() &&
3864  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3865  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3866  Diag(OldLocation, PrevDiag);
3867  return New->setInvalidDecl();
3868  }
3869  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3870  !New->hasExternalStorage()) {
3871  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3872  Diag(OldLocation, PrevDiag);
3873  return New->setInvalidDecl();
3874  }
3875 
3876  if (CheckRedeclarationModuleOwnership(New, Old))
3877  return;
3878 
3879  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3880 
3881  // FIXME: The test for external storage here seems wrong? We still
3882  // need to check for mismatches.
3883  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3884  // Don't complain about out-of-line definitions of static members.
3885  !(Old->getLexicalDeclContext()->isRecord() &&
3886  !New->getLexicalDeclContext()->isRecord())) {
3887  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3888  Diag(OldLocation, PrevDiag);
3889  return New->setInvalidDecl();
3890  }
3891 
3892  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3893  if (VarDecl *Def = Old->getDefinition()) {
3894  // C++1z [dcl.fcn.spec]p4:
3895  // If the definition of a variable appears in a translation unit before
3896  // its first declaration as inline, the program is ill-formed.
3897  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3898  Diag(Def->getLocation(), diag::note_previous_definition);
3899  }
3900  }
3901 
3902  // If this redeclaration makes the variable inline, we may need to add it to
3903  // UndefinedButUsed.
3904  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3905  !Old->getDefinition() && !New->isThisDeclarationADefinition())
3906  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3907  SourceLocation()));
3908 
3909  if (New->getTLSKind() != Old->getTLSKind()) {
3910  if (!Old->getTLSKind()) {
3911  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3912  Diag(OldLocation, PrevDiag);
3913  } else if (!New->getTLSKind()) {
3914  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3915  Diag(OldLocation, PrevDiag);
3916  } else {
3917  // Do not allow redeclaration to change the variable between requiring
3918  // static and dynamic initialization.
3919  // FIXME: GCC allows this, but uses the TLS keyword on the first
3920  // declaration to determine the kind. Do we need to be compatible here?
3921  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3922  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3923  Diag(OldLocation, PrevDiag);
3924  }
3925  }
3926 
3927  // C++ doesn't have tentative definitions, so go right ahead and check here.
3928  if (getLangOpts().CPlusPlus &&
3930  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3931  Old->getCanonicalDecl()->isConstexpr()) {
3932  // This definition won't be a definition any more once it's been merged.
3933  Diag(New->getLocation(),
3934  diag::warn_deprecated_redundant_constexpr_static_def);
3935  } else if (VarDecl *Def = Old->getDefinition()) {
3936  if (checkVarDeclRedefinition(Def, New))
3937  return;
3938  }
3939  }
3940 
3941  if (haveIncompatibleLanguageLinkages(Old, New)) {
3942  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3943  Diag(OldLocation, PrevDiag);
3944  New->setInvalidDecl();
3945  return;
3946  }
3947 
3948  // Merge "used" flag.
3949  if (Old->getMostRecentDecl()->isUsed(false))
3950  New->setIsUsed();
3951 
3952  // Keep a chain of previous declarations.
3953  New->setPreviousDecl(Old);
3954  if (NewTemplate)
3955  NewTemplate->setPreviousDecl(OldTemplate);
3956 
3957  // Inherit access appropriately.
3958  New->setAccess(Old->getAccess());
3959  if (NewTemplate)
3960  NewTemplate->setAccess(New->getAccess());
3961 
3962  if (Old->isInline())
3963  New->setImplicitlyInline();
3964 }
3965 
3967  SourceManager &SrcMgr = getSourceManager();
3968  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3969  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3970  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3971  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3972  auto &HSI = PP.getHeaderSearchInfo();
3973  StringRef HdrFilename =
3974  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3975 
3976  auto noteFromModuleOrInclude = [&](Module *Mod,
3977  SourceLocation IncLoc) -> bool {
3978  // Redefinition errors with modules are common with non modular mapped
3979  // headers, example: a non-modular header H in module A that also gets
3980  // included directly in a TU. Pointing twice to the same header/definition
3981  // is confusing, try to get better diagnostics when modules is on.
3982  if (IncLoc.isValid()) {
3983  if (Mod) {
3984  Diag(IncLoc, diag::note_redefinition_modules_same_file)
3985  << HdrFilename.str() << Mod->getFullModuleName();
3986  if (!Mod->DefinitionLoc.isInvalid())
3987  Diag(Mod->DefinitionLoc, diag::note_defined_here)
3988  << Mod->getFullModuleName();
3989  } else {
3990  Diag(IncLoc, diag::note_redefinition_include_same_file)
3991  << HdrFilename.str();
3992  }
3993  return true;
3994  }
3995 
3996  return false;
3997  };
3998 
3999  // Is it the same file and same offset? Provide more information on why
4000  // this leads to a redefinition error.
4001  bool EmittedDiag = false;
4002  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4003  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4004  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4005  EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4006  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4007 
4008  // If the header has no guards, emit a note suggesting one.
4009  if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4010  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4011 
4012  if (EmittedDiag)
4013  return;
4014  }
4015 
4016  // Redefinition coming from different files or couldn't do better above.
4017  Diag(Old->getLocation(), diag::note_previous_definition);
4018 }
4019 
4020 /// We've just determined that \p Old and \p New both appear to be definitions
4021 /// of the same variable. Either diagnose or fix the problem.
4023  if (!hasVisibleDefinition(Old) &&
4024  (New->getFormalLinkage() == InternalLinkage ||
4025  New->isInline() ||
4026  New->getDescribedVarTemplate() ||
4028  New->getDeclContext()->isDependentContext())) {
4029  // The previous definition is hidden, and multiple definitions are
4030  // permitted (in separate TUs). Demote this to a declaration.
4032 
4033  // Make the canonical definition visible.
4034  if (auto *OldTD = Old->getDescribedVarTemplate())
4035  makeMergedDefinitionVisible(OldTD);
4036  makeMergedDefinitionVisible(Old);
4037  return false;
4038  } else {
4039  Diag(New->getLocation(), diag::err_redefinition) << New;
4040  notePreviousDefinition(Old, New->getLocation());
4041  New->setInvalidDecl();
4042  return true;
4043  }
4044 }
4045 
4046 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4047 /// no declarator (e.g. "struct foo;") is parsed.
4048 Decl *
4050  RecordDecl *&AnonRecord) {
4051  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4052  AnonRecord);
4053 }
4054 
4055 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4056 // disambiguate entities defined in different scopes.
4057 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4058 // compatibility.
4059 // We will pick our mangling number depending on which version of MSVC is being
4060 // targeted.
4061 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4063  ? S->getMSCurManglingNumber()
4064  : S->getMSLastManglingNumber();
4065 }
4066 
4067 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4068  if (!Context.getLangOpts().CPlusPlus)
4069  return;
4070 
4071  if (isa<CXXRecordDecl>(Tag->getParent())) {
4072  // If this tag is the direct child of a class, number it if
4073  // it is anonymous.
4074  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4075  return;
4076  MangleNumberingContext &MCtx =
4077  Context.getManglingNumberContext(Tag->getParent());
4078  Context.setManglingNumber(
4079  Tag, MCtx.getManglingNumber(
4080  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4081  return;
4082  }
4083 
4084  // If this tag isn't a direct child of a class, number it if it is local.
4085  Decl *ManglingContextDecl;
4086  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4087  Tag->getDeclContext(), ManglingContextDecl)) {
4088  Context.setManglingNumber(
4089  Tag, MCtx->getManglingNumber(
4090  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4091  }
4092 }
4093 
4095  TypedefNameDecl *NewTD) {
4096  if (TagFromDeclSpec->isInvalidDecl())
4097  return;
4098 
4099  // Do nothing if the tag already has a name for linkage purposes.
4100  if (TagFromDeclSpec->hasNameForLinkage())
4101  return;
4102 
4103  // A well-formed anonymous tag must always be a TUK_Definition.
4104  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4105 
4106  // The type must match the tag exactly; no qualifiers allowed.
4107  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4108  Context.getTagDeclType(TagFromDeclSpec))) {
4109  if (getLangOpts().CPlusPlus)
4110  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4111  return;
4112  }
4113 
4114  // If we've already computed linkage for the anonymous tag, then
4115  // adding a typedef name for the anonymous decl can change that
4116  // linkage, which might be a serious problem. Diagnose this as
4117  // unsupported and ignore the typedef name. TODO: we should
4118  // pursue this as a language defect and establish a formal rule
4119  // for how to handle it.
4120  if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4121  Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4122 
4123  SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4124  tagLoc = getLocForEndOfToken(tagLoc);
4125 
4126  llvm::SmallString<40> textToInsert;
4127  textToInsert += ' ';
4128  textToInsert += NewTD->getIdentifier()->getName();
4129  Diag(tagLoc, diag::note_typedef_changes_linkage)
4130  << FixItHint::CreateInsertion(tagLoc, textToInsert);
4131  return;
4132  }
4133 
4134  // Otherwise, set this is the anon-decl typedef for the tag.
4135  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4136 }
4137 
4139  switch (T) {
4140  case DeclSpec::TST_class:
4141  return 0;
4142  case DeclSpec::TST_struct:
4143  return 1;
4145  return 2;
4146  case DeclSpec::TST_union:
4147  return 3;
4148  case DeclSpec::TST_enum:
4149  return 4;
4150  default:
4151  llvm_unreachable("unexpected type specifier");
4152  }
4153 }
4154 
4155 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4156 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4157 /// parameters to cope with template friend declarations.
4158 Decl *
4160  MultiTemplateParamsArg TemplateParams,
4161  bool IsExplicitInstantiation,
4162  RecordDecl *&AnonRecord) {
4163  Decl *TagD = nullptr;
4164  TagDecl *Tag = nullptr;
4165  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4170  TagD = DS.getRepAsDecl();
4171 
4172  if (!TagD) // We probably had an error
4173  return nullptr;
4174 
4175  // Note that the above type specs guarantee that the
4176  // type rep is a Decl, whereas in many of the others
4177  // it's a Type.
4178  if (isa<TagDecl>(TagD))
4179  Tag = cast<TagDecl>(TagD);
4180  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4181  Tag = CTD->getTemplatedDecl();
4182  }
4183 
4184  if (Tag) {
4185  handleTagNumbering(Tag, S);
4186  Tag->setFreeStanding();
4187  if (Tag->isInvalidDecl())
4188  return Tag;
4189  }
4190 
4191  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4192  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4193  // or incomplete types shall not be restrict-qualified."
4194  if (TypeQuals & DeclSpec::TQ_restrict)
4195  Diag(DS.getRestrictSpecLoc(),
4196  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4197  << DS.getSourceRange();
4198  }
4199 
4200  if (DS.isInlineSpecified())
4201  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4202  << getLangOpts().CPlusPlus17;
4203 
4204  if (DS.isConstexprSpecified()) {
4205  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4206  // and definitions of functions and variables.
4207  if (Tag)
4208  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4210  else
4211  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4212  // Don't emit warnings after this error.
4213  return TagD;
4214  }
4215 
4216  DiagnoseFunctionSpecifiers(DS);
4217 
4218  if (DS.isFriendSpecified()) {
4219  // If we're dealing with a decl but not a TagDecl, assume that
4220  // whatever routines created it handled the friendship aspect.
4221  if (TagD && !Tag)
4222  return nullptr;
4223  return ActOnFriendTypeDecl(S, DS, TemplateParams);
4224  }
4225 
4226  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4227  bool IsExplicitSpecialization =
4228  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4229  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4230  !IsExplicitInstantiation && !IsExplicitSpecialization &&
4231  !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4232  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4233  // nested-name-specifier unless it is an explicit instantiation
4234  // or an explicit specialization.
4235  //
4236  // FIXME: We allow class template partial specializations here too, per the
4237  // obvious intent of DR1819.
4238  //
4239  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4240  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4242  return nullptr;
4243  }
4244 
4245  // Track whether this decl-specifier declares anything.
4246  bool DeclaresAnything = true;
4247 
4248  // Handle anonymous struct definitions.
4249  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4250  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4252  if (getLangOpts().CPlusPlus ||
4253  Record->getDeclContext()->isRecord()) {
4254  // If CurContext is a DeclContext that can contain statements,
4255  // RecursiveASTVisitor won't visit the decls that
4256  // BuildAnonymousStructOrUnion() will put into CurContext.
4257  // Also store them here so that they can be part of the
4258  // DeclStmt that gets created in this case.
4259  // FIXME: Also return the IndirectFieldDecls created by
4260  // BuildAnonymousStructOr union, for the same reason?
4261  if (CurContext->isFunctionOrMethod())
4262  AnonRecord = Record;
4263  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4264  Context.getPrintingPolicy());
4265  }
4266 
4267  DeclaresAnything = false;
4268  }
4269  }
4270 
4271  // C11 6.7.2.1p2:
4272  // A struct-declaration that does not declare an anonymous structure or
4273  // anonymous union shall contain a struct-declarator-list.
4274  //
4275  // This rule also existed in C89 and C99; the grammar for struct-declaration
4276  // did not permit a struct-declaration without a struct-declarator-list.
4277  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4279  // Check for Microsoft C extension: anonymous struct/union member.
4280  // Handle 2 kinds of anonymous struct/union:
4281  // struct STRUCT;
4282  // union UNION;
4283  // and
4284  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4285  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4286  if ((Tag && Tag->getDeclName()) ||
4288  RecordDecl *Record = nullptr;
4289  if (Tag)
4290  Record = dyn_cast<RecordDecl>(Tag);
4291  else if (const RecordType *RT =
4293  Record = RT->getDecl();
4294  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4295  Record = UT->getDecl();
4296 
4297  if (Record && getLangOpts().MicrosoftExt) {
4298  Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4299  << Record->isUnion() << DS.getSourceRange();
4300  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4301  }
4302 
4303  DeclaresAnything = false;
4304  }
4305  }
4306 
4307  // Skip all the checks below if we have a type error.
4308  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4309  (TagD && TagD->isInvalidDecl()))
4310  return TagD;
4311 
4312  if (getLangOpts().CPlusPlus &&
4314  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4315  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4316  !Enum->getIdentifier() && !Enum->isInvalidDecl())
4317  DeclaresAnything = false;
4318 
4319  if (!DS.isMissingDeclaratorOk()) {
4320  // Customize diagnostic for a typedef missing a name.
4322  Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4323  << DS.getSourceRange();
4324  else
4325  DeclaresAnything = false;
4326  }
4327 
4328  if (DS.isModulePrivateSpecified() &&
4329  Tag && Tag->getDeclContext()->isFunctionOrMethod())
4330  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4331  << Tag->getTagKind()
4333 
4334  ActOnDocumentableDecl(TagD);
4335 
4336  // C 6.7/2:
4337  // A declaration [...] shall declare at least a declarator [...], a tag,
4338  // or the members of an enumeration.
4339  // C++ [dcl.dcl]p3:
4340  // [If there are no declarators], and except for the declaration of an
4341  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4342  // names into the program, or shall redeclare a name introduced by a
4343  // previous declaration.
4344  if (!DeclaresAnything) {
4345  // In C, we allow this as a (popular) extension / bug. Don't bother
4346  // producing further diagnostics for redundant qualifiers after this.
4347  Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4348  return TagD;
4349  }
4350 
4351  // C++ [dcl.stc]p1:
4352  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4353  // init-declarator-list of the declaration shall not be empty.
4354  // C++ [dcl.fct.spec]p1:
4355  // If a cv-qualifier appears in a decl-specifier-seq, the
4356  // init-declarator-list of the declaration shall not be empty.
4357  //
4358  // Spurious qualifiers here appear to be valid in C.
4359  unsigned DiagID = diag::warn_standalone_specifier;
4360  if (getLangOpts().CPlusPlus)
4361  DiagID = diag::ext_standalone_specifier;
4362 
4363  // Note that a linkage-specification sets a storage class, but
4364  // 'extern "C" struct foo;' is actually valid and not theoretically
4365  // useless.
4366  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4367  if (SCS == DeclSpec::SCS_mutable)
4368  // Since mutable is not a viable storage class specifier in C, there is
4369  // no reason to treat it as an extension. Instead, diagnose as an error.
4370  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4371  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4372  Diag(DS.getStorageClassSpecLoc(), DiagID)
4374  }
4375 
4376  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4377  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4378  << DeclSpec::getSpecifierName(TSCS);
4379  if (DS.getTypeQualifiers()) {
4381  Diag(DS.getConstSpecLoc(), DiagID) << "const";
4383  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4384  // Restrict is covered above.
4386  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4388  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4389  }
4390 
4391  // Warn about ignored type attributes, for example:
4392  // __attribute__((aligned)) struct A;
4393  // Attributes should be placed after tag to apply to type declaration.
4394  if (!DS.getAttributes().empty()) {
4395  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4396  if (TypeSpecType == DeclSpec::TST_class ||
4397  TypeSpecType == DeclSpec::TST_struct ||
4398  TypeSpecType == DeclSpec::TST_interface ||
4399  TypeSpecType == DeclSpec::TST_union ||
4400  TypeSpecType == DeclSpec::TST_enum) {
4401  for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4402  attrs = attrs->getNext())
4403  Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4404  << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4405  }
4406  }
4407 
4408  return TagD;
4409 }
4410 
4411 /// We are trying to inject an anonymous member into the given scope;
4412 /// check if there's an existing declaration that can't be overloaded.
4413 ///
4414 /// \return true if this is a forbidden redeclaration
4415 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4416  Scope *S,
4417  DeclContext *Owner,
4418  DeclarationName Name,
4419  SourceLocation NameLoc,
4420  bool IsUnion) {
4421  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4423  if (!SemaRef.LookupName(R, S)) return false;
4424 
4425  // Pick a representative declaration.
4427  assert(PrevDecl && "Expected a non-null Decl");
4428 
4429  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4430  return false;
4431 
4432  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4433  << IsUnion << Name;
4434  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4435 
4436  return true;
4437 }
4438 
4439 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4440 /// anonymous struct or union AnonRecord into the owning context Owner
4441 /// and scope S. This routine will be invoked just after we realize
4442 /// that an unnamed union or struct is actually an anonymous union or
4443 /// struct, e.g.,
4444 ///
4445 /// @code
4446 /// union {
4447 /// int i;
4448 /// float f;
4449 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4450 /// // f into the surrounding scope.x
4451 /// @endcode
4452 ///
4453 /// This routine is recursive, injecting the names of nested anonymous
4454 /// structs/unions into the owning context and scope as well.
4455 static bool
4457  RecordDecl *AnonRecord, AccessSpecifier AS,
4458  SmallVectorImpl<NamedDecl *> &Chaining) {
4459  bool Invalid = false;
4460 
4461  // Look every FieldDecl and IndirectFieldDecl with a name.
4462  for (auto *D : AnonRecord->decls()) {
4463  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4464  cast<NamedDecl>(D)->getDeclName()) {
4465  ValueDecl *VD = cast<ValueDecl>(D);
4466  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4467  VD->getLocation(),
4468  AnonRecord->isUnion())) {
4469  // C++ [class.union]p2:
4470  // The names of the members of an anonymous union shall be
4471  // distinct from the names of any other entity in the
4472  // scope in which the anonymous union is declared.
4473  Invalid = true;
4474  } else {
4475  // C++ [class.union]p2:
4476  // For the purpose of name lookup, after the anonymous union
4477  // definition, the members of the anonymous union are
4478  // considered to have been defined in the scope in which the
4479  // anonymous union is declared.
4480  unsigned OldChainingSize = Chaining.size();
4481  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4482  Chaining.append(IF->chain_begin(), IF->chain_end());
4483  else
4484  Chaining.push_back(VD);
4485 
4486  assert(Chaining.size() >= 2);
4487  NamedDecl **NamedChain =
4488  new (SemaRef.Context)NamedDecl*[Chaining.size()];
4489  for (unsigned i = 0; i < Chaining.size(); i++)
4490  NamedChain[i] = Chaining[i];
4491 
4493  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4494  VD->getType(), {NamedChain, Chaining.size()});
4495 
4496  for (const auto *Attr : VD->attrs())
4497  IndirectField->addAttr(Attr->clone(SemaRef.Context));
4498 
4499  IndirectField->setAccess(AS);
4500  IndirectField->setImplicit();
4501  SemaRef.PushOnScopeChains(IndirectField, S);
4502 
4503  // That includes picking up the appropriate access specifier.
4504  if (AS != AS_none) IndirectField->setAccess(AS);
4505 
4506  Chaining.resize(OldChainingSize);
4507  }
4508  }
4509  }
4510 
4511  return Invalid;
4512 }
4513 
4514 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4515 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4516 /// illegal input values are mapped to SC_None.
4517 static StorageClass
4519  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4520  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4521  "Parser allowed 'typedef' as storage class VarDecl.");
4522  switch (StorageClassSpec) {
4523  case DeclSpec::SCS_unspecified: return SC_None;
4524  case DeclSpec::SCS_extern:
4525  if (DS.isExternInLinkageSpec())
4526  return SC_None;
4527  return SC_Extern;
4528  case DeclSpec::SCS_static: return SC_Static;
4529  case DeclSpec::SCS_auto: return SC_Auto;
4530  case DeclSpec::SCS_register: return SC_Register;
4532  // Illegal SCSs map to None: error reporting is up to the caller.
4533  case DeclSpec::SCS_mutable: // Fall through.
4534  case DeclSpec::SCS_typedef: return SC_None;
4535  }
4536  llvm_unreachable("unknown storage class specifier");
4537 }
4538 
4540  assert(Record->hasInClassInitializer());
4541 
4542  for (const auto *I : Record->decls()) {
4543  const auto *FD = dyn_cast<FieldDecl>(I);
4544  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4545  FD = IFD->getAnonField();
4546  if (FD && FD->hasInClassInitializer())
4547  return FD->getLocation();
4548  }
4549 
4550  llvm_unreachable("couldn't find in-class initializer");
4551 }
4552 
4554  SourceLocation DefaultInitLoc) {
4555  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4556  return;
4557 
4558  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4559  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4560 }
4561 
4563  CXXRecordDecl *AnonUnion) {
4564  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4565  return;
4566 
4567  checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4568 }
4569 
4570 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4571 /// anonymous structure or union. Anonymous unions are a C++ feature
4572 /// (C++ [class.union]) and a C11 feature; anonymous structures
4573 /// are a C11 feature and GNU C++ extension.
4575  AccessSpecifier AS,
4576  RecordDecl *Record,
4577  const PrintingPolicy &Policy) {
4578  DeclContext *Owner = Record->getDeclContext();
4579 
4580  // Diagnose whether this anonymous struct/union is an extension.
4581  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4582  Diag(Record->getLocation(), diag::ext_anonymous_union);
4583  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4584  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4585  else if (!Record->isUnion() && !getLangOpts().C11)
4586  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4587 
4588  // C and C++ require different kinds of checks for anonymous
4589  // structs/unions.
4590  bool Invalid = false;
4591  if (getLangOpts().CPlusPlus) {
4592  const char *PrevSpec = nullptr;
4593  unsigned DiagID;
4594  if (Record->isUnion()) {
4595  // C++ [class.union]p6:
4596  // Anonymous unions declared in a named namespace or in the
4597  // global namespace shall be declared static.
4599  (isa<TranslationUnitDecl>(Owner) ||
4600  (isa<NamespaceDecl>(Owner) &&
4601  cast<NamespaceDecl>(Owner)->getDeclName()))) {
4602  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4603  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4604 
4605  // Recover by adding 'static'.
4607  PrevSpec, DiagID, Policy);
4608  }
4609  // C++ [class.union]p6:
4610  // A storage class is not allowed in a declaration of an
4611  // anonymous union in a class scope.
4613  isa<RecordDecl>(Owner)) {
4615  diag::err_anonymous_union_with_storage_spec)
4617 
4618  // Recover by removing the storage specifier.
4620  SourceLocation(),
4621  PrevSpec, DiagID, Context.getPrintingPolicy());
4622  }
4623  }
4624 
4625  // Ignore const/volatile/restrict qualifiers.
4626  if (DS.getTypeQualifiers()) {
4628  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4629  << Record->isUnion() << "const"
4632  Diag(DS.getVolatileSpecLoc(),
4633  diag::ext_anonymous_struct_union_qualified)
4634  << Record->isUnion() << "volatile"
4637  Diag(DS.getRestrictSpecLoc(),
4638  diag::ext_anonymous_struct_union_qualified)
4639  << Record->isUnion() << "restrict"
4642  Diag(DS.getAtomicSpecLoc(),
4643  diag::ext_anonymous_struct_union_qualified)
4644  << Record->isUnion() << "_Atomic"
4648  diag::ext_anonymous_struct_union_qualified)
4649  << Record->isUnion() << "__unaligned"
4651 
4652  DS.ClearTypeQualifiers();
4653  }
4654 
4655  // C++ [class.union]p2:
4656  // The member-specification of an anonymous union shall only
4657  // define non-static data members. [Note: nested types and
4658  // functions cannot be declared within an anonymous union. ]
4659  for (auto *Mem : Record->decls()) {
4660  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4661  // C++ [class.union]p3:
4662  // An anonymous union shall not have private or protected
4663  // members (clause 11).
4664  assert(FD->getAccess() != AS_none);
4665  if (FD->getAccess() != AS_public) {
4666  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4667  << Record->isUnion() << (FD->getAccess() == AS_protected);
4668  Invalid = true;
4669  }
4670 
4671  // C++ [class.union]p1
4672  // An object of a class with a non-trivial constructor, a non-trivial
4673  // copy constructor, a non-trivial destructor, or a non-trivial copy
4674  // assignment operator cannot be a member of a union, nor can an
4675  // array of such objects.
4676  if (CheckNontrivialField(FD))
4677  Invalid = true;
4678  } else if (Mem->isImplicit()) {
4679  // Any implicit members are fine.
4680  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4681  // This is a type that showed up in an
4682  // elaborated-type-specifier inside the anonymous struct or
4683  // union, but which actually declares a type outside of the
4684  // anonymous struct or union. It's okay.
4685  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4686  if (!MemRecord->isAnonymousStructOrUnion() &&
4687  MemRecord->getDeclName()) {
4688  // Visual C++ allows type definition in anonymous struct or union.
4689  if (getLangOpts().MicrosoftExt)
4690  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4691  << Record->isUnion();
4692  else {
4693  // This is a nested type declaration.
4694  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4695  << Record->isUnion();
4696  Invalid = true;
4697  }
4698  } else {
4699  // This is an anonymous type definition within another anonymous type.
4700  // This is a popular extension, provided by Plan9, MSVC and GCC, but
4701  // not part of standard C++.
4702  Diag(MemRecord->getLocation(),
4703  diag::ext_anonymous_record_with_anonymous_type)
4704  << Record->isUnion();
4705  }
4706  } else if (isa<AccessSpecDecl>(Mem)) {
4707  // Any access specifier is fine.
4708  } else if (isa<StaticAssertDecl>(Mem)) {
4709  // In C++1z, static_assert declarations are also fine.
4710  } else {
4711  // We have something that isn't a non-static data
4712  // member. Complain about it.
4713  unsigned DK = diag::err_anonymous_record_bad_member;
4714  if (isa<TypeDecl>(Mem))
4715  DK = diag::err_anonymous_record_with_type;
4716  else if (isa<FunctionDecl>(Mem))
4717  DK = diag::err_anonymous_record_with_function;
4718  else if (isa<VarDecl>(Mem))
4719  DK = diag::err_anonymous_record_with_static;
4720 
4721  // Visual C++ allows type definition in anonymous struct or union.
4722  if (getLangOpts().MicrosoftExt &&
4723  DK == diag::err_anonymous_record_with_type)
4724  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4725  << Record->isUnion();
4726  else {
4727  Diag(Mem->getLocation(), DK) << Record->isUnion();
4728  Invalid = true;
4729  }
4730  }
4731  }
4732 
4733  // C++11 [class.union]p8 (DR1460):
4734  // At most one variant member of a union may have a
4735  // brace-or-equal-initializer.
4736  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4737  Owner->isRecord())
4738  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4739  cast<CXXRecordDecl>(Record));
4740  }
4741 
4742  if (!Record->isUnion() && !Owner->isRecord()) {
4743  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4744  << getLangOpts().CPlusPlus;
4745  Invalid = true;
4746  }
4747 
4748  // Mock up a declarator.
4750  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4751  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4752 
4753  // Create a declaration for this anonymous struct/union.
4754  NamedDecl *Anon = nullptr;
4755  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4756  Anon = FieldDecl::Create(Context, OwningClass,
4757  DS.getLocStart(),
4758  Record->getLocation(),
4759  /*IdentifierInfo=*/nullptr,
4760  Context.getTypeDeclType(Record),
4761  TInfo,
4762  /*BitWidth=*/nullptr, /*Mutable=*/false,
4763  /*InitStyle=*/ICIS_NoInit);
4764  Anon->setAccess(AS);
4765  if (getLangOpts().CPlusPlus)
4766  FieldCollector->Add(cast<FieldDecl>(Anon));
4767  } else {
4768  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4770  if (SCSpec == DeclSpec::SCS_mutable) {
4771  // mutable can only appear on non-static class members, so it's always
4772  // an error here
4773  Diag(Record->getLocation(), diag::err_mutable_nonmember);
4774  Invalid = true;
4775  SC = SC_None;
4776  }
4777 
4778  Anon = VarDecl::Create(Context, Owner,
4779  DS.getLocStart(),
4780  Record->getLocation(), /*IdentifierInfo=*/nullptr,
4781  Context.getTypeDeclType(Record),
4782  TInfo, SC);
4783 
4784  // Default-initialize the implicit variable. This initialization will be
4785  // trivial in almost all cases, except if a union member has an in-class
4786  // initializer:
4787  // union { int n = 0; };
4788  ActOnUninitializedDecl(Anon);
4789  }
4790  Anon->setImplicit();
4791 
4792  // Mark this as an anonymous struct/union type.
4793  Record->setAnonymousStructOrUnion(true);
4794 
4795  // Add the anonymous struct/union object to the current
4796  // context. We'll be referencing this object when we refer to one of
4797  // its members.
4798  Owner->addDecl(Anon);
4799 
4800  // Inject the members of the anonymous struct/union into the owning
4801  // context and into the identifier resolver chain for name lookup
4802  // purposes.
4804  Chain.push_back(Anon);
4805 
4806  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4807  Invalid = true;
4808 
4809  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4810  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4811  Decl *ManglingContextDecl;
4812  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4813  NewVD->getDeclContext(), ManglingContextDecl)) {
4814  Context.setManglingNumber(
4815  NewVD, MCtx->getManglingNumber(
4816  NewVD, getMSManglingNumber(getLangOpts(), S)));
4817  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4818  }
4819  }
4820  }
4821 
4822  if (Invalid)
4823  Anon->setInvalidDecl();
4824 
4825  return Anon;
4826 }
4827 
4828 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4829 /// Microsoft C anonymous structure.
4830 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4831 /// Example:
4832 ///
4833 /// struct A { int a; };
4834 /// struct B { struct A; int b; };
4835 ///
4836 /// void foo() {
4837 /// B var;
4838 /// var.a = 3;
4839 /// }
4840 ///
4842  RecordDecl *Record) {
4843  assert(Record && "expected a record!");
4844 
4845  // Mock up a declarator.
4847  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4848  assert(TInfo && "couldn't build declarator info for anonymous struct");
4849 
4850  auto *ParentDecl = cast<RecordDecl>(CurContext);
4851  QualType RecTy = Context.getTypeDeclType(Record);
4852 
4853  // Create a declaration for this anonymous struct.
4854  NamedDecl *Anon = FieldDecl::Create(Context,
4855  ParentDecl,
4856  DS.getLocStart(),
4857  DS.getLocStart(),
4858  /*IdentifierInfo=*/nullptr,
4859  RecTy,
4860  TInfo,
4861  /*BitWidth=*/nullptr, /*Mutable=*/false,
4862  /*InitStyle=*/ICIS_NoInit);
4863  Anon->setImplicit();
4864 
4865  // Add the anonymous struct object to the current context.
4866  CurContext->addDecl(Anon);
4867 
4868  // Inject the members of the anonymous struct into the current
4869  // context and into the identifier resolver chain for name lookup
4870  // purposes.
4872  Chain.push_back(Anon);
4873 
4874  RecordDecl *RecordDef = Record->getDefinition();
4875  if (RequireCompleteType(Anon->getLocation(), RecTy,
4876  diag::err_field_incomplete) ||
4877  InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4878  AS_none, Chain)) {
4879  Anon->setInvalidDecl();
4880  ParentDecl->setInvalidDecl();
4881  }
4882 
4883  return Anon;
4884 }
4885 
4886 /// GetNameForDeclarator - Determine the full declaration name for the
4887 /// given Declarator.
4889  return GetNameFromUnqualifiedId(D.getName());
4890 }
4891 
4892 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4895  DeclarationNameInfo NameInfo;
4896  NameInfo.setLoc(Name.StartLocation);
4897 
4898  switch (Name.getKind()) {
4899 
4902  NameInfo.setName(Name.Identifier);
4903  NameInfo.setLoc(Name.StartLocation);
4904  return NameInfo;
4905 
4907  // C++ [temp.deduct.guide]p3:
4908  // The simple-template-id shall name a class template specialization.
4909  // The template-name shall be the same identifier as the template-name
4910  // of the simple-template-id.
4911  // These together intend to imply that the template-name shall name a
4912  // class template.
4913  // FIXME: template<typename T> struct X {};
4914  // template<typename T> using Y = X<T>;
4915  // Y(int) -> Y<int>;
4916  // satisfies these rules but does not name a class template.
4917  TemplateName TN = Name.TemplateName.get().get();
4918  auto *Template = TN.getAsTemplateDecl();
4919  if (!Template || !isa<ClassTemplateDecl>(Template)) {
4920  Diag(Name.StartLocation,
4921  diag::err_deduction_guide_name_not_class_template)
4922  << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4923  if (Template)
4924  Diag(Template->getLocation(), diag::note_template_decl_here);
4925  return DeclarationNameInfo();
4926  }
4927 
4928  NameInfo.setName(
4929  Context.DeclarationNames.getCXXDeductionGuideName(Template));
4930  NameInfo.setLoc(Name.StartLocation);
4931  return NameInfo;
4932  }
4933 
4935  NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4937  NameInfo.setLoc(Name.StartLocation);
4941  = Name.EndLocation.getRawEncoding();
4942  return NameInfo;
4943 
4946  Name.Identifier));
4947  NameInfo.setLoc(Name.StartLocation);
4949  return NameInfo;
4950 
4952  TypeSourceInfo *TInfo;
4953  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4954  if (Ty.isNull())
4955  return DeclarationNameInfo();
4957  Context.getCanonicalType(Ty)));
4958  NameInfo.setLoc(Name.StartLocation);
4959  NameInfo.setNamedTypeInfo(TInfo);
4960  return NameInfo;
4961  }
4962 
4964  TypeSourceInfo *TInfo;
4965  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4966  if (Ty.isNull())
4967  return DeclarationNameInfo();
4969  Context.getCanonicalType(Ty)));
4970  NameInfo.setLoc(Name.StartLocation);
4971  NameInfo.setNamedTypeInfo(TInfo);
4972  return NameInfo;
4973  }
4974 
4976  // In well-formed code, we can only have a constructor
4977  // template-id that refers to the current context, so go there
4978  // to find the actual type being constructed.
4979  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4980  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4981  return DeclarationNameInfo();
4982 
4983  // Determine the type of the class being constructed.
4984  QualType CurClassType = Context.getTypeDeclType(CurClass);
4985 
4986  // FIXME: Check two things: that the template-id names the same type as
4987  // CurClassType, and that the template-id does not occur when the name
4988  // was qualified.
4989 
4991  Context.getCanonicalType(CurClassType)));
4992  NameInfo.setLoc(Name.StartLocation);
4993  // FIXME: should we retrieve TypeSourceInfo?
4994  NameInfo.setNamedTypeInfo(nullptr);
4995  return NameInfo;
4996  }
4997 
4999  TypeSourceInfo *TInfo;
5000  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5001  if (Ty.isNull())
5002  return DeclarationNameInfo();
5004  Context.getCanonicalType(Ty)));
5005  NameInfo.setLoc(Name.StartLocation);
5006  NameInfo.setNamedTypeInfo(TInfo);
5007  return NameInfo;
5008  }
5009 
5011  TemplateName TName = Name.TemplateId->Template.get();
5012  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5013  return Context.getNameForTemplate(TName, TNameLoc);
5014  }
5015 
5016  } // switch (Name.getKind())
5017 
5018  llvm_unreachable("Unknown name kind");
5019 }
5020 
5022  do {
5023  if (Ty->isPointerType() || Ty->isReferenceType())
5024  Ty = Ty->getPointeeType();
5025  else if (Ty->isArrayType())
5026  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5027  else
5028  return Ty.withoutLocalFastQualifiers();
5029  } while (true);
5030 }
5031 
5032 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5033 /// and Definition have "nearly" matching parameters. This heuristic is
5034 /// used to improve diagnostics in the case where an out-of-line function
5035 /// definition doesn't match any declaration within the class or namespace.
5036 /// Also sets Params to the list of indices to the parameters that differ
5037 /// between the declaration and the definition. If hasSimilarParameters
5038 /// returns true and Params is empty, then all of the parameters match.
5039 static bool hasSimilarParameters(ASTContext &Context,
5040  FunctionDecl *Declaration,
5041  FunctionDecl *Definition,
5042  SmallVectorImpl<unsigned> &Params) {
5043  Params.clear();
5044  if (Declaration->param_size() != Definition->param_size())
5045  return false;
5046  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5047  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5048  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5049 
5050  // The parameter types are identical
5051  if (Context.hasSameType(DefParamTy, DeclParamTy))
5052  continue;
5053 
5054  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5055  QualType DefParamBaseTy = getCoreType(DefParamTy);
5056  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5057  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5058 
5059  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5060  (DeclTyName && DeclTyName == DefTyName))
5061  Params.push_back(Idx);
5062  else // The two parameters aren't even close
5063  return false;
5064  }
5065 
5066  return true;
5067 }
5068 
5069 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5070 /// declarator needs to be rebuilt in the current instantiation.
5071 /// Any bits of declarator which appear before the name are valid for
5072 /// consideration here. That's specifically the type in the decl spec
5073 /// and the base type in any member-pointer chunks.
5075  DeclarationName Name) {
5076  // The types we specifically need to rebuild are:
5077  // - typenames, typeofs, and decltypes
5078  // - types which will become injected class names
5079  // Of course, we also need to rebuild any type referencing such a
5080  // type. It's safest to just say "dependent", but we call out a
5081  // few cases here.
5082 
5083  DeclSpec &DS = D.getMutableDeclSpec();
5084  switch (DS.getTypeSpecType()) {
5088  case DeclSpec::TST_atomic: {
5089  // Grab the type from the parser.
5090  TypeSourceInfo *TSI = nullptr;
5091  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5092  if (T.isNull() || !T->isDependentType()) break;
5093 
5094  // Make sure there's a type source info. This isn't really much
5095  // of a waste; most dependent types should have type source info
5096  // attached already.
5097  if (!TSI)
5099 
5100  // Rebuild the type in the current instantiation.
5101  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5102  if (!TSI) return true;
5103 
5104  // Store the new type back in the decl spec.
5105  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5106  DS.UpdateTypeRep(LocType);
5107  break;
5108  }
5109 
5111  case DeclSpec::TST_typeofExpr: {
5112  Expr *E = DS.getRepAsExpr();
5114  if (Result.isInvalid()) return true;
5115  DS.UpdateExprRep(Result.get());
5116  break;
5117  }
5118 
5119  default:
5120  // Nothing to do for these decl specs.
5121  break;
5122  }
5123 
5124  // It doesn't matter what order we do this in.
5125  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5126  DeclaratorChunk &Chunk = D.getTypeObject(I);
5127 
5128  // The only type information in the declarator which can come
5129  // before the declaration name is the base type of a member
5130  // pointer.
5131  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5132  continue;
5133 
5134  // Rebuild the scope specifier in-place.
5135  CXXScopeSpec &SS = Chunk.Mem.Scope();
5137  return true;
5138  }
5139 
5140  return false;
5141 }
5142 
5145  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5146 
5147  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5148  Dcl && Dcl->getDeclContext()->isFileContext())
5150 
5151  if (getLangOpts().OpenCL)
5152  setCurrentOpenCLExtensionForDecl(Dcl);
5153 
5154  return Dcl;
5155 }
5156 
5157 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5158 /// If T is the name of a class, then each of the following shall have a
5159 /// name different from T:
5160 /// - every static data member of class T;
5161 /// - every member function of class T
5162 /// - every member of class T that is itself a type;
5163 /// \returns true if the declaration name violates these rules.
5165  DeclarationNameInfo NameInfo) {
5166  DeclarationName Name = NameInfo.getName();
5167 
5168  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5169  while (Record && Record->isAnonymousStructOrUnion())
5170  Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5171  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5172  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5173  return true;
5174  }
5175 
5176  return false;
5177 }
5178 
5179 /// \brief Diagnose a declaration whose declarator-id has the given
5180 /// nested-name-specifier.
5181 ///
5182 /// \param SS The nested-name-specifier of the declarator-id.
5183 ///
5184 /// \param DC The declaration context to which the nested-name-specifier
5185 /// resolves.
5186 ///
5187 /// \param Name The name of the entity being declared.
5188 ///
5189 /// \param Loc The location of the name of the entity being declared.
5190 ///
5191 /// \returns true if we cannot safely recover from this error, false otherwise.
5193  DeclarationName Name,
5194  SourceLocation Loc) {
5195  DeclContext *Cur = CurContext;
5196  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5197  Cur = Cur->getParent();
5198 
5199  // If the user provided a superfluous scope specifier that refers back to the
5200  // class in which the entity is already declared, diagnose and ignore it.
5201  //
5202  // class X {
5203  // void X::f();
5204  // };
5205  //
5206  // Note, it was once ill-formed to give redundant qualification in all
5207  // contexts, but that rule was removed by DR482.
5208  if (Cur->Equals(DC)) {
5209  if (Cur->isRecord()) {
5210  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5211  : diag::err_member_extra_qualification)
5212  << Name << FixItHint::CreateRemoval(SS.getRange());
5213  SS.clear();
5214  } else {
5215  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5216  }
5217  return false;
5218  }
5219 
5220  // Check whether the qualifying scope encloses the scope of the original
5221  // declaration.
5222  if (!Cur->Encloses(DC)) {
5223  if (Cur->isRecord())
5224  Diag(Loc, diag::err_member_qualification)
5225  << Name << SS.getRange();
5226  else if (isa<TranslationUnitDecl>(DC))
5227  Diag(Loc, diag::err_invalid_declarator_global_scope)
5228  << Name << SS.getRange();
5229  else if (isa<FunctionDecl>(Cur))
5230  Diag(Loc, diag::err_invalid_declarator_in_function)
5231  << Name << SS.getRange();
5232  else if (isa<BlockDecl>(Cur))
5233  Diag(Loc, diag::err_invalid_declarator_in_block)
5234  << Name << SS.getRange();
5235  else
5236  Diag(Loc, diag::err_invalid_declarator_scope)
5237  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5238 
5239  return true;
5240  }
5241 
5242  if (Cur->isRecord()) {
5243  // Cannot qualify members within a class.
5244  Diag(Loc, diag::err_member_qualification)
5245  << Name << SS.getRange();
5246  SS.clear();
5247 
5248  // C++ constructors and destructors with incorrect scopes can break
5249  // our AST invariants by having the wrong underlying types. If
5250  // that's the case, then drop this declaration entirely.
5253  !Context.hasSameType(Name.getCXXNameType(),
5254  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5255  return true;
5256 
5257  return false;
5258  }
5259 
5260  // C++11 [dcl.meaning]p1:
5261  // [...] "The nested-name-specifier of the qualified declarator-id shall
5262  // not begin with a decltype-specifer"
5263  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5264  while (SpecLoc.getPrefix())
5265  SpecLoc = SpecLoc.getPrefix();
5266  if (dyn_cast_or_null<DecltypeType>(
5267  SpecLoc.getNestedNameSpecifier()->getAsType()))
5268  Diag(Loc, diag::err_decltype_in_declarator)
5269  << SpecLoc.getTypeLoc().getSourceRange();
5270 
5271  return false;
5272 }
5273 
5275  MultiTemplateParamsArg TemplateParamLists) {
5276  // TODO: consider using NameInfo for diagnostic.
5277  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5278  DeclarationName Name = NameInfo.getName();
5279 
5280  // All of these full declarators require an identifier. If it doesn't have
5281  // one, the ParsedFreeStandingDeclSpec action should be used.
5282  if (D.isDecompositionDeclarator()) {
5283  return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5284  } else if (!Name) {
5285  if (!D.isInvalidType()) // Reject this if we think it is valid.
5287  diag::err_declarator_need_ident)
5288  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5289  return nullptr;
5290  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5291  return nullptr;
5292 
5293  // The scope passed in may not be a decl scope. Zip up the scope tree until
5294  // we find one that is.
5295  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5296  (S->getFlags() & Scope::TemplateParamScope) != 0)
5297  S = S->getParent();
5298 
5299  DeclContext *DC = CurContext;
5300  if (D.getCXXScopeSpec().isInvalid())
5301  D.setInvalidType();
5302  else if (D.getCXXScopeSpec().isSet()) {
5303  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5304  UPPC_DeclarationQualifier))
5305  return nullptr;
5306 
5307  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5308  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5309  if (!DC || isa<EnumDecl>(DC)) {
5310  // If we could not compute the declaration context, it's because the
5311  // declaration context is dependent but does not refer to a class,
5312  // class template, or class template partial specialization. Complain
5313  // and return early, to avoid the coming semantic disaster.
5314  Diag(D.getIdentifierLoc(),
5315  diag::err_template_qualified_declarator_no_match)
5316  << D.getCXXScopeSpec().getScopeRep()
5317  << D.getCXXScopeSpec().getRange();
5318  return nullptr;
5319  }
5320  bool IsDependentContext = DC->isDependentContext();
5321 
5322  if (!IsDependentContext &&
5323  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5324  return nullptr;
5325 
5326  // If a class is incomplete, do not parse entities inside it.
5327  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5328  Diag(D.getIdentifierLoc(),
5329  diag::err_member_def_undefined_record)
5330  << Name << DC << D.getCXXScopeSpec().getRange();
5331  return nullptr;
5332  }
5333  if (!D.getDeclSpec().isFriendSpecified()) {
5334  if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5335  Name, D.getIdentifierLoc())) {
5336  if (DC->isRecord())
5337  return nullptr;
5338 
5339  D.setInvalidType();
5340  }
5341  }
5342 
5343  // Check whether we need to rebuild the type of the given
5344  // declaration in the current instantiation.
5345  if (EnteringContext && IsDependentContext &&
5346  TemplateParamLists.size() != 0) {
5347  ContextRAII SavedContext(*this, DC);
5348  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5349  D.setInvalidType();
5350  }
5351  }
5352 
5353  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5354  QualType R = TInfo->getType();
5355 
5356  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5357  UPPC_DeclarationType))
5358  D.setInvalidType();
5359 
5360  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5361  forRedeclarationInCurContext());
5362 
5363  // See if this is a redefinition of a variable in the same scope.
5364  if (!D.getCXXScopeSpec().isSet()) {
5365  bool IsLinkageLookup = false;
5366  bool CreateBuiltins = false;
5367 
5368  // If the declaration we're planning to build will be a function
5369  // or object with linkage, then look for another declaration with
5370  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5371  //
5372  // If the declaration we're planning to build will be declared with
5373  // external linkage in the translation unit, create any builtin with
5374  // the same name.
5376  /* Do nothing*/;
5377  else if (CurContext->isFunctionOrMethod() &&
5379  R->isFunctionType())) {
5380  IsLinkageLookup = true;
5381  CreateBuiltins =
5382  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5383  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5385  CreateBuiltins = true;
5386 
5387  if (IsLinkageLookup) {
5388  Previous.clear(LookupRedeclarationWithLinkage);
5389  Previous.setRedeclarationKind(ForExternalRedeclaration);
5390  }
5391 
5392  LookupName(Previous, S, CreateBuiltins);
5393  } else { // Something like "int foo::x;"
5394  LookupQualifiedName(Previous, DC);
5395 
5396  // C++ [dcl.meaning]p1:
5397  // When the declarator-id is qualified, the declaration shall refer to a
5398  // previously declared member of the class or namespace to which the
5399  // qualifier refers (or, in the case of a namespace, of an element of the
5400  // inline namespace set of that namespace (7.3.1)) or to a specialization
5401  // thereof; [...]
5402  //
5403  // Note that we already checked the context above, and that we do not have
5404  // enough information to make sure that Previous contains the declaration
5405  // we want to match. For example, given:
5406  //
5407  // class X {
5408  // void f();
5409  // void f(float);
5410  // };
5411  //
5412  // void X::f(int) { } // ill-formed
5413  //
5414  // In this case, Previous will point to the overload set
5415  // containing the two f's declared in X, but neither of them
5416  // matches.
5417 
5418  // C++ [dcl.meaning]p1:
5419  // [...] the member shall not merely have been introduced by a
5420  // using-declaration in the scope of the class or namespace nominated by
5421  // the nested-name-specifier of the declarator-id.
5422  RemoveUsingDecls(Previous);
5423  }
5424 
5425  if (Previous.isSingleResult() &&
5426  Previous.getFoundDecl()->isTemplateParameter()) {
5427  // Maybe we will complain about the shadowed template parameter.
5428  if (!D.isInvalidType())
5429  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5430  Previous.getFoundDecl());
5431 
5432  // Just pretend that we didn't see the previous declaration.
5433  Previous.clear();
5434  }
5435 
5436  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5437  // Forget that the previous declaration is the injected-class-name.
5438  Previous.clear();
5439 
5440  // In C++, the previous declaration we find might be a tag type
5441  // (class or enum). In this case, the new declaration will hide the
5442  // tag type. Note that this applies to functions, function templates, and
5443  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5444  if (Previous.isSingleTagDecl() &&
5446  (TemplateParamLists.size() == 0 || R->isFunctionType()))
5447  Previous.clear();
5448 
5449  // Check that there are no default arguments other than in the parameters
5450  // of a function declaration (C++ only).
5451  if (getLangOpts().CPlusPlus)
5452  CheckExtraCXXDefaultArguments(D);
5453 
5454  NamedDecl *New;
5455 
5456  bool AddToScope = true;
5458  if (TemplateParamLists.size()) {
5459  Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5460  return nullptr;
5461  }
5462 
5463  New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5464  } else if (R->isFunctionType()) {
5465  New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5466  TemplateParamLists,
5467  AddToScope);
5468  } else {
5469  New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5470  AddToScope);
5471  }
5472 
5473  if (!New)
5474  return nullptr;
5475 
5476  // If this has an identifier and is not a function template specialization,
5477  // add it to the scope stack.
5478  if (New->getDeclName() && AddToScope) {
5479  // Only make a locally-scoped extern declaration visible if it is the first
5480  // declaration of this entity. Qualified lookup for such an entity should
5481  // only find this declaration if there is no visible declaration of it.
5482  bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5483  PushOnScopeChains(New, S, AddToContext);
5484  if (!AddToContext)
5485  CurContext->addHiddenDecl(New);
5486  }
5487 
5488  if (isInOpenMPDeclareTargetContext())
5489  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5490 
5491  return New;
5492 }
5493 
5494 /// Helper method to turn variable array types into constant array
5495 /// types in certain situations which would otherwise be errors (for
5496 /// GCC compatibility).
5498  ASTContext &Context,
5499  bool &SizeIsNegative,
5500  llvm::APSInt &Oversized) {
5501  // This method tries to turn a variable array into a constant
5502  // array even when the size isn't an ICE. This is necessary
5503  // for compatibility with code that depends on gcc's buggy
5504  // constant expression folding, like struct {char x[(int)(char*)2];}
5505  SizeIsNegative = false;
5506  Oversized = 0;
5507 
5508  if (T->isDependentType())
5509  return QualType();
5510 
5511  QualifierCollector Qs;
5512  const Type *Ty = Qs.strip(T);
5513 
5514  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5515  QualType Pointee = PTy->getPointeeType();
5516  QualType FixedType =
5517  TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5518  Oversized);
5519  if (FixedType.isNull()) return FixedType;
5520  FixedType = Context.getPointerType(FixedType);
5521  return Qs.apply(Context, FixedType);
5522  }
5523  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5524  QualType Inner = PTy->getInnerType();
5525  QualType FixedType =
5526  TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5527  Oversized);
5528  if (FixedType.isNull()) return FixedType;
5529  FixedType = Context.getParenType(FixedType);
5530  return Qs.apply(Context, FixedType);
5531  }
5532 
5533  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5534  if (!VLATy)
5535  return QualType();
5536  // FIXME: We should probably handle this case
5537  if (VLATy->getElementType()->isVariablyModifiedType())
5538  return QualType();
5539 
5540  llvm::APSInt Res;
5541  if (!VLATy->getSizeExpr() ||
5542  !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5543  return QualType();
5544 
5545  // Check whether the array size is negative.
5546  if (Res.isSigned() && Res.isNegative()) {
5547  SizeIsNegative = true;
5548  return QualType();
5549  }
5550 
5551  // Check whether the array is too large to be addressed.
5552  unsigned ActiveSizeBits
5554  Res);
5555  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5556  Oversized = Res;
5557  return QualType();
5558  }
5559 
5560  return Context.getConstantArrayType(VLATy->getElementType(),
5561  Res, ArrayType::Normal, 0);
5562 }
5563 
5564 static void
5566  SrcTL = SrcTL.getUnqualifiedLoc();
5567  DstTL = DstTL.getUnqualifiedLoc();
5568  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5569  PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5570  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5571  DstPTL.getPointeeLoc());
5572  DstPTL.setStarLoc(SrcPTL.getStarLoc());
5573  return;
5574  }
5575  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5576  ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5577  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5578  DstPTL.getInnerLoc());
5579  DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5580  DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5581  return;
5582  }
5583  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5584  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5585  TypeLoc SrcElemTL = SrcATL.getElementLoc();
5586  TypeLoc DstElemTL = DstATL.getElementLoc();
5587  DstElemTL.initializeFullCopy(SrcElemTL);
5588  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5589  DstATL.setSizeExpr(SrcATL.getSizeExpr());
5590  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5591 }
5592 
5593 /// Helper method to turn variable array types into constant array
5594 /// types in certain situations which would otherwise be errors (for
5595 /// GCC compatibility).
5596 static TypeSourceInfo*
5598  ASTContext &Context,
5599  bool &SizeIsNegative,
5600  llvm::APSInt &Oversized) {
5601  QualType FixedTy
5602  = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5603  SizeIsNegative, Oversized);
5604  if (FixedTy.isNull())
5605  return nullptr;
5606  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5608  FixedTInfo->getTypeLoc());
5609  return FixedTInfo;
5610 }
5611 
5612 /// \brief Register the given locally-scoped extern "C" declaration so
5613 /// that it can be found later for redeclarations. We include any extern "C"
5614 /// declaration that is not visible in the translation unit here, not just
5615 /// function-scope declarations.
5616 void
5618  if (!getLangOpts().CPlusPlus &&
5620  // Don't need to track declarations in the TU in C.
5621  return;
5622 
5623  // Note that we have a locally-scoped external with this name.
5625 }
5626 
5628  // FIXME: We can have multiple results via __attribute__((overloadable)).
5629  auto Result = Context.getExternCContextDecl()->lookup(Name);
5630  return Result.empty() ? nullptr : *Result.begin();
5631 }
5632 
5633 /// \brief Diagnose function specifiers on a declaration of an identifier that
5634 /// does not identify a function.
5636  // FIXME: We should probably indicate the identifier in question to avoid
5637  // confusion for constructs like "virtual int a(), b;"
5638  if (DS.isVirtualSpecified())
5639  Diag(DS.getVirtualSpecLoc(),
5640  diag::err_virtual_non_function);
5641 
5642  if (DS.isExplicitSpecified())
5643  Diag(DS.getExplicitSpecLoc(),
5644  diag::err_explicit_non_function);
5645 
5646  if (DS.isNoreturnSpecified())
5647  Diag(DS.getNoreturnSpecLoc(),
5648  diag::err_noreturn_non_function);
5649 }
5650 
5651 NamedDecl*
5654  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5655  if (D.getCXXScopeSpec().isSet()) {
5656  Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5657  << D.getCXXScopeSpec().getRange();
5658  D.setInvalidType();
5659  // Pretend we didn't see the scope specifier.
5660  DC = CurContext;
5661  Previous.clear();
5662  }
5663 
5664  DiagnoseFunctionSpecifiers(D.getDeclSpec());
5665 
5666  if (D.getDeclSpec().isInlineSpecified())
5667  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5668  << getLangOpts().CPlusPlus17;
5670  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5671  << 1;
5672 
5676  diag::err_deduction_guide_invalid_specifier)
5677  << "typedef";
5678  else
5679  Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5680  << D.getName().getSourceRange();
5681  return nullptr;
5682  }
5683 
5684  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5685  if (!NewTD) return nullptr;
5686 
5687  // Handle attributes prior to checking for duplicates in MergeVarDecl
5688  ProcessDeclAttributes(S, NewTD, D);
5689 
5690  CheckTypedefForVariablyModifiedType(S, NewTD);
5691 
5692  bool Redeclaration = D.isRedeclaration();
5693  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5694  D.setRedeclaration(Redeclaration);
5695  return ND;
5696 }
5697 
5698 void
5700  // C99 6.7.7p2: If a typedef name specifies a variably modified type
5701  // then it shall have block scope.
5702  // Note that variably modified types must be fixed before merging the decl so
5703  // that redeclarations will match.
5704  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5705  QualType T = TInfo->getType();
5706  if (T->isVariablyModifiedType()) {
5707  getCurFunction()->setHasBranchProtectedScope();
5708 
5709  if (S->getFnParent() == nullptr) {
5710  bool SizeIsNegative;
5711  llvm::APSInt Oversized;
5712  TypeSourceInfo *FixedTInfo =
5714  SizeIsNegative,
5715  Oversized);
5716  if (FixedTInfo) {
5717  Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5718  NewTD->setTypeSourceInfo(FixedTInfo);
5719  } else {
5720  if (SizeIsNegative)
5721  Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5722  else if (T->isVariableArrayType())
5723  Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5724  else if (Oversized.getBoolValue())
5725  Diag(NewTD->getLocation(), diag::err_array_too_large)
5726  << Oversized.toString(10);
5727  else
5728  Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5729  NewTD->setInvalidDecl();
5730  }
5731  }
5732  }
5733 }
5734 
5735 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5736 /// declares a typedef-name, either using the 'typedef' type specifier or via
5737 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5738 NamedDecl*
5740  LookupResult &Previous, bool &Redeclaration) {
5741 
5742  // Find the shadowed declaration before filtering for scope.
5743  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5744 
5745  // Merge the decl with the existing one if appropriate. If the decl is
5746  // in an outer scope, it isn't the same thing.
5747  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5748  /*AllowInlineNamespace*/false);
5749  filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5750  if (!Previous.empty()) {
5751  Redeclaration = true;
5752  MergeTypedefNameDecl(S, NewTD, Previous);
5753  }
5754 
5755  if (ShadowedDecl && !Redeclaration)
5756  CheckShadow(NewTD, ShadowedDecl, Previous);
5757 
5758  // If this is the C FILE type, notify the AST context.
5759  if (IdentifierInfo *II = NewTD->getIdentifier())
5760  if (!NewTD->isInvalidDecl() &&
5762  if (II->isStr("FILE"))
5763  Context.setFILEDecl(NewTD);
5764  else if (II->isStr("jmp_buf"))
5765  Context.setjmp_bufDecl(NewTD);
5766  else if (II->isStr("sigjmp_buf"))
5767  Context.setsigjmp_bufDecl(NewTD);
5768  else if (II->isStr("ucontext_t"))
5769  Context.setucontext_tDecl(NewTD);
5770  }
5771 
5772  return NewTD;
5773 }
5774 
5775 /// \brief Determines whether the given declaration is an out-of-scope
5776 /// previous declaration.
5777 ///
5778 /// This routine should be invoked when name lookup has found a
5779 /// previous declaration (PrevDecl) that is not in the scope where a
5780 /// new declaration by the same name is being introduced. If the new
5781 /// declaration occurs in a local scope, previous declarations with
5782 /// linkage may still be considered previous declarations (C99
5783 /// 6.2.2p4-5, C++ [basic.link]p6).
5784 ///
5785 /// \param PrevDecl the previous declaration found by name
5786 /// lookup
5787 ///
5788 /// \param DC the context in which the new declaration is being
5789 /// declared.
5790 ///
5791 /// \returns true if PrevDecl is an out-of-scope previous declaration
5792 /// for a new delcaration with the same name.
5793 static bool
5795  ASTContext &Context) {
5796  if (!PrevDecl)
5797  return false;
5798 
5799  if (!PrevDecl->hasLinkage())
5800  return false;
5801 
5802  if (Context.getLangOpts().CPlusPlus) {
5803  // C++ [basic.link]p6:
5804  // If there is a visible declaration of an entity with linkage
5805  // having the same name and type, ignoring entities declared
5806  // outside the innermost enclosing namespace scope, the block
5807  // scope declaration declares that same entity and receives the
5808  // linkage of the previous declaration.
5809  DeclContext *OuterContext = DC->getRedeclContext();
5810  if (!OuterContext->isFunctionOrMethod())
5811  // This rule only applies to block-scope declarations.
5812  return false;
5813 
5814  DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5815  if (PrevOuterContext->isRecord())
5816  // We found a member function: ignore it.
5817  return false;
5818 
5819  // Find the innermost enclosing namespace for the new and
5820  // previous declarations.
5821  OuterContext = OuterContext->getEnclosingNamespaceContext();
5822  PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5823 
5824  // The previous declaration is in a different namespace, so it
5825  // isn't the same function.
5826  if (!OuterContext->Equals(PrevOuterContext))
5827  return false;
5828  }
5829 
5830  return true;
5831 }
5832 
5834  CXXScopeSpec &SS = D.getCXXScopeSpec();
5835  if (!SS.isSet()) return;
5837 }
5838 
5840  QualType type = decl->getType();
5841  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5842  if (lifetime == Qualifiers::OCL_Autoreleasing) {
5843  // Various kinds of declaration aren't allowed to be __autoreleasing.
5844  unsigned kind = -1U;
5845  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5846  if (var->hasAttr<BlocksAttr>())
5847  kind = 0; // __block
5848  else if (!var->hasLocalStorage())
5849  kind = 1; // global
5850  } else if (isa<ObjCIvarDecl>(decl)) {
5851  kind = 3; // ivar
5852  } else if (isa<FieldDecl>(decl)) {
5853  kind = 2; // field
5854  }
5855 
5856  if (kind != -1U) {
5857  Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5858  << kind;
5859  }
5860  } else if (lifetime == Qualifiers::OCL_None) {
5861  // Try to infer lifetime.
5862  if (!type->isObjCLifetimeType())
5863  return false;
5864 
5865  lifetime = type->getObjCARCImplicitLifetime();
5866  type = Context.getLifetimeQualifiedType(type, lifetime);
5867  decl->setType(type);
5868  }
5869 
5870  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5871  // Thread-local variables cannot have lifetime.
5872  if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5873  var->getTLSKind()) {
5874  Diag(var->getLocation(), diag::err_arc_thread_ownership)
5875  << var->getType();
5876  return true;
5877  }
5878  }
5879 
5880  return false;
5881 }
5882 
5884  // Ensure that an auto decl is deduced otherwise the checks below might cache
5885  // the wrong linkage.
5886  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5887 
5888  // 'weak' only applies to declarations with external linkage.
5889  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5890  if (!ND.isExternallyVisible()) {
5891  S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5892  ND.dropAttr<WeakAttr>();
5893  }
5894  }
5895  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5896  if (ND.isExternallyVisible()) {
5897  S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5898  ND.dropAttr<WeakRefAttr>();
5899  ND.dropAttr<AliasAttr>();
5900  }
5901  }
5902 
5903  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5904  if (VD->hasInit()) {
5905  if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5906  assert(VD->isThisDeclarationADefinition() &&
5907  !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5908  S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5909  VD->dropAttr<AliasAttr>();
5910  }
5911  }
5912  }
5913 
5914  // 'selectany' only applies to externally visible variable declarations.
5915  // It does not apply to functions.
5916  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5917  if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5918  S.Diag(Attr->getLocation(),
5919  diag::err_attribute_selectany_non_extern_data);
5920  ND.dropAttr<SelectAnyAttr>();
5921  }
5922  }
5923 
5924  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5925  // dll attributes require external linkage. Static locals may have external
5926  // linkage but still cannot be explicitly imported or exported.
5927  auto *VD = dyn_cast<VarDecl>(&ND);
5928  if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5929  S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5930  << &ND << Attr;
5931  ND.setInvalidDecl();
5932  }
5933  }
5934 
5935  // Virtual functions cannot be marked as 'notail'.
5936  if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5937  if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5938  if (MD->isVirtual()) {
5939  S.Diag(ND.getLocation(),
5940  diag::err_invalid_attribute_on_virtual_function)
5941  << Attr;
5942  ND.dropAttr<NotTailCalledAttr>();
5943  }
5944 }
5945 
5947  NamedDecl *NewDecl,
5948  bool IsSpecialization,
5949  bool IsDefinition) {
5950  if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
5951  return;
5952 
5953  bool IsTemplate = false;
5954  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5955  OldDecl = OldTD->getTemplatedDecl();
5956  IsTemplate = true;
5957  if (!IsSpecialization)
5958  IsDefinition = false;
5959  }
5960  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5961  NewDecl = NewTD->getTemplatedDecl();
5962  IsTemplate = true;
5963  }
5964 
5965  if (!OldDecl || !NewDecl)
5966  return;
5967 
5968  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5969  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5970  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5971  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5972 
5973  // dllimport and dllexport are inheritable attributes so we have to exclude
5974  // inherited attribute instances.
5975  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5976  (NewExportAttr && !NewExportAttr->isInherited());
5977 
5978  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5979  // the only exception being explicit specializations.
5980  // Implicitly generated declarations are also excluded for now because there
5981  // is no other way to switch these to use dllimport or dllexport.
5982  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5983 
5984  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5985  // Allow with a warning for free functions and global variables.
5986  bool JustWarn = false;
5987  if (!OldDecl->isCXXClassMember()) {
5988  auto *VD = dyn_cast<VarDecl>(OldDecl);
5989  if (VD && !VD->getDescribedVarTemplate())
5990  JustWarn = true;
5991  auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5992  if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5993  JustWarn = true;
5994  }
5995 
5996  // We cannot change a declaration that's been used because IR has already
5997  // been emitted. Dllimported functions will still work though (modulo
5998  // address equality) as they can use the thunk.
5999  if (OldDecl->isUsed())
6000  if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6001  JustWarn = false;
6002 
6003  unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6004  : diag::err_attribute_dll_redeclaration;
6005  S.Diag(NewDecl->getLocation(), DiagID)
6006  << NewDecl
6007  << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6008  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6009  if (!JustWarn) {
6010  NewDecl->setInvalidDecl();
6011  return;
6012  }
6013  }
6014 
6015  // A redeclaration is not allowed to drop a dllimport attribute, the only
6016  // exceptions being inline function definitions (except for function
6017  // templates), local extern declarations, qualified friend declarations or
6018  // special MSVC extension: in the last case, the declaration is treated as if
6019  // it were marked dllexport.
6020  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6021  bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6022  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6023  // Ignore static data because out-of-line definitions are diagnosed
6024  // separately.
6025  IsStaticDataMember = VD->isStaticDataMember();
6026  IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6028  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6029  IsInline = FD->isInlined();
6030  IsQualifiedFriend = FD->getQualifier() &&
6031  FD->getFriendObjectKind() == Decl::FOK_Declared;
6032  }
6033 
6034  if (OldImportAttr && !HasNewAttr &&
6035  (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6036  !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6037  if (IsMicrosoft && IsDefinition) {
6038  S.Diag(NewDecl->getLocation(),
6039  diag::warn_redeclaration_without_import_attribute)
6040  << NewDecl;
6041  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6042  NewDecl->dropAttr<DLLImportAttr>();
6043  NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6044  NewImportAttr->getRange(), S.Context,
6045  NewImportAttr->getSpellingListIndex()));
6046  } else {
6047  S.Diag(NewDecl->getLocation(),
6048  diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6049  << NewDecl << OldImportAttr;
6050  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6051  S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6052  OldDecl->dropAttr<DLLImportAttr>();
6053  NewDecl->dropAttr<DLLImportAttr>();
6054  }
6055  } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6056  // In MinGW, seeing a function declared inline drops the dllimport
6057  // attribute.
6058  OldDecl->dropAttr<DLLImportAttr>();
6059  NewDecl->dropAttr<DLLImportAttr>();
6060  S.Diag(NewDecl->getLocation(),
6061  diag::warn_dllimport_dropped_from_inline_function)
6062  << NewDecl << OldImportAttr;
6063  }
6064 
6065  // A specialization of a class template member function is processed here
6066  // since it's a redeclaration. If the parent class is dllexport, the
6067  // specialization inherits that attribute. This doesn't happen automatically
6068  // since the parent class isn't instantiated until later.
6069  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6070  if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6071  !NewImportAttr && !NewExportAttr) {
6072  if (const DLLExportAttr *ParentExportAttr =
6073  MD->getParent()->getAttr<DLLExportAttr>()) {
6074  DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6075  NewAttr->setInherited(true);
6076  NewDecl->addAttr(NewAttr);
6077  }
6078  }
6079  }
6080 }
6081 
6082 /// Given that we are within the definition of the given function,
6083 /// will that definition behave like C99's 'inline', where the
6084 /// definition is discarded except for optimization purposes?
6086  // Try to avoid calling GetGVALinkageForFunction.
6087 
6088  // All cases of this require the 'inline' keyword.
6089  if (!FD->isInlined()) return false;
6090 
6091  // This is only possible in C++ with the gnu_inline attribute.
6092  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6093  return false;
6094 
6095  // Okay, go ahead and call the relatively-more-expensive function.
6097 }
6098 
6099 /// Determine whether a variable is extern "C" prior to attaching
6100 /// an initializer. We can't just call isExternC() here, because that
6101 /// will also compute and cache whether the declaration is externally
6102 /// visible, which might change when we attach the initializer.
6103 ///
6104 /// This can only be used if the declaration is known to not be a
6105 /// redeclaration of an internal linkage declaration.
6106 ///
6107 /// For instance:
6108 ///
6109 /// auto x = []{};
6110 ///
6111 /// Attaching the initializer here makes this declaration not externally
6112 /// visible, because its type has internal linkage.
6113 ///
6114 /// FIXME: This is a hack.
6115 template<typename T>
6116 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6117  if (S.getLangOpts().CPlusPlus) {
6118  // In C++, the overloadable attribute negates the effects of extern "C".
6119  if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6120  return false;
6121 
6122  // So do CUDA's host/device attributes.
6123  if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6124  D->template hasAttr<CUDAHostAttr>()))
6125  return false;
6126  }
6127  return D->isExternC();
6128 }
6129 
6130 static bool shouldConsiderLinkage(const VarDecl *VD) {
6131  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6132  if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6133  return VD->hasExternalStorage();
6134  if (DC->isFileContext())
6135  return true;
6136  if (DC->isRecord())
6137  return false;
6138  llvm_unreachable("Unexpected context");
6139 }
6140 
6141 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6142  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6143  if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6144  isa<OMPDeclareReductionDecl>(DC))
6145  return true;
6146  if (DC->isRecord())
6147  return false;
6148  llvm_unreachable("Unexpected context");
6149 }
6150 
6151 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6153  for (const AttributeList *L = AttrList; L; L = L->getNext())
6154  if (L->getKind() == Kind)
6155  return true;
6156  return false;
6157 }
6158 
6159 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6161  // Check decl attributes on the DeclSpec.
6163  return true;
6164 
6165  // Walk the declarator structure, checking decl attributes that were in a type
6166  // position to the decl itself.
6167  for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6168  if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6169  return true;
6170  }
6171 
6172  // Finally, check attributes on the decl itself.
6173  return hasParsedAttr(S, PD.getAttributes(), Kind);
6174 }
6175 
6176 /// Adjust the \c DeclContext for a function or variable that might be a
6177 /// function-local external declaration.
6179  if (!DC->isFunctionOrMethod())
6180  return false;
6181 
6182  // If this is a local extern function or variable declared within a function
6183  // template, don't add it into the enclosing namespace scope until it is
6184  // instantiated; it might have a dependent type right now.
6185  if (DC->isDependentContext())
6186  return true;
6187 
6188  // C++11 [basic.link]p7:
6189  // When a block scope declaration of an entity with linkage is not found to
6190  // refer to some other declaration, then that entity is a member of the
6191  // innermost enclosing namespace.
6192  //
6193  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6194  // semantically-enclosing namespace, not a lexically-enclosing one.
6195  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6196  DC = DC->getParent();
6197  return true;
6198 }
6199 
6200 /// \brief Returns true if given declaration has external C language linkage.
6201 static bool isDeclExternC(const Decl *D) {
6202  if (const auto *FD = dyn_cast<FunctionDecl>(D))
6203  return FD->isExternC();
6204  if (const auto *VD = dyn_cast<VarDecl>(D))
6205  return VD->isExternC();
6206 
6207  llvm_unreachable("Unknown type of decl!");
6208 }
6209 
6211  Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6212  LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6213  bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6214  QualType R = TInfo->getType();
6215  DeclarationName Name = GetNameForDeclarator(D).getName();
6216 
6217  IdentifierInfo *II = Name.getAsIdentifierInfo();
6218 
6219  if (D.isDecompositionDeclarator()) {
6220  // Take the name of the first declarator as our name for diagnostic
6221  // purposes.
6222  auto &Decomp = D.getDecompositionDeclarator();
6223  if (!Decomp.bindings().empty()) {
6224  II = Decomp.bindings()[0].Name;
6225  Name = II;
6226  }
6227  } else if (!II) {
6228  Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6229  return nullptr;
6230  }
6231 
6232  if (getLangOpts().OpenCL) {
6233  // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6234  // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6235  // argument.
6236  if (R->isImageType() || R->isPipeType()) {
6237  Diag(D.getIdentifierLoc(),
6238  diag::err_opencl_type_can_only_be_used_as_function_parameter)
6239  << R;
6240  D.setInvalidType();
6241  return nullptr;
6242  }
6243 
6244  // OpenCL v1.2 s6.9.r:
6245  // The event type cannot be used to declare a program scope variable.
6246  // OpenCL v2.0 s6.9.q:
6247  // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6248  if (NULL == S->getParent()) {
6249  if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6250  Diag(D.getIdentifierLoc(),
6251  diag::err_invalid_type_for_program_scope_var) << R;
6252  D.setInvalidType();
6253  return nullptr;
6254  }
6255  }
6256 
6257  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6258  QualType NR = R;
6259  while (NR->isPointerType()) {
6260  if (NR->isFunctionPointerType()) {
6261  Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6262  D.setInvalidType();
6263  break;
6264  }
6265  NR = NR->getPointeeType();
6266  }
6267 
6268  if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6269  // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6270  // half array type (unless the cl_khr_fp16 extension is enabled).
6271  if (Context.getBaseElementType(R)->isHalfType()) {
6272  Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6273  D.setInvalidType();
6274  }
6275  }
6276 
6277  if (R->isSamplerT()) {
6278  // OpenCL v1.2 s6.9.b p4:
6279  // The sampler type cannot be used with the __local and __global address
6280  // space qualifiers.
6283  Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6284  }
6285 
6286  // OpenCL v1.2 s6.12.14.1:
6287  // A global sampler must be declared with either the constant address
6288  // space qualifier or with the const qualifier.
6289  if (DC->isTranslationUnit() &&
6291  R.isConstQualified())) {
6292  Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6293  D.setInvalidType();
6294  }
6295  }
6296 
6297  // OpenCL v1.2 s6.9.r:
6298  // The event type cannot be used with the __local, __constant and __global
6299  // address space qualifiers.
6300  if (R->isEventT()) {
6302  Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6303  D.setInvalidType();
6304  }
6305  }
6306  }
6307 
6310 
6311  // dllimport globals without explicit storage class are treated as extern. We
6312  // have to change the storage class this early to get the right DeclContext.
6313  if (SC == SC_None && !DC->isRecord() &&
6314  hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6315  !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6316  SC = SC_Extern;
6317 
6318  DeclContext *OriginalDC = DC;
6319  bool IsLocalExternDecl = SC == SC_Extern &&
6320  adjustContextForLocalExternDecl(DC);
6321 
6322  if (SCSpec == DeclSpec::SCS_mutable) {
6323  // mutable can only appear on non-static class members, so it's always
6324  // an error here
6325  Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6326  D.setInvalidType();
6327  SC = SC_None;
6328  }
6329 
6330  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6331  !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6333  // In C++11, the 'register' storage class specifier is deprecated.
6334  // Suppress the warning in system macros, it's used in macros in some
6335  // popular C system headers, such as in glibc's htonl() macro.
6337  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6338  : diag::warn_deprecated_register)
6340  }
6341 
6342  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6343 
6344  if (!DC->isRecord() && S->getFnParent() == nullptr) {
6345  // C99 6.9p2: The storage-class specifiers auto and register shall not
6346  // appear in the declaration specifiers in an external declaration.
6347  // Global Register+Asm is a GNU extension we support.
6348  if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6349  Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6350  D.setInvalidType();
6351  }
6352  }
6353 
6354  bool IsMemberSpecialization = false;
6355  bool IsVariableTemplateSpecialization = false;
6356  bool IsPartialSpecialization = false;
6357  bool IsVariableTemplate = false;
6358  VarDecl *NewVD = nullptr;
6359  VarTemplateDecl *NewTemplate = nullptr;
6360  TemplateParameterList *TemplateParams = nullptr;
6361  if (!getLangOpts().CPlusPlus) {
6362  NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6363  D.getIdentifierLoc(), II,
6364  R, TInfo, SC);
6365 
6366  if (R->getContainedDeducedType())
6367  ParsingInitForAutoVars.insert(NewVD);
6368 
6369  if (D.isInvalidType())
6370  NewVD->setInvalidDecl();
6371  } else {
6372  bool Invalid = false;
6373 
6374  if (DC->isRecord() && !CurContext->isRecord()) {
6375  // This is an out-of-line definition of a static data member.
6376  switch (SC) {
6377  case SC_None:
6378  break;
6379  case SC_Static:
6381  diag::err_static_out_of_line)
6383  break;
6384  case SC_Auto:
6385  case SC_Register:
6386  case SC_Extern:
6387  // [dcl.stc] p2: The auto or register specifiers shall be applied only
6388  // to names of variables declared in a block or to function parameters.
6389  // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6390  // of class members
6391 
6393  diag::err_storage_class_for_static_member)
6395  break;
6396  case SC_PrivateExtern:
6397  llvm_unreachable("C storage class in c++!");
6398  }
6399  }
6400 
6401  if (SC == SC_Static && CurContext->isRecord()) {
6402  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6403  if (RD->isLocalClass())
6404  Diag(D.getIdentifierLoc(),
6405  diag::err_static_data_member_not_allowed_in_local_class)
6406  << Name << RD->getDeclName();
6407 
6408  // C++98 [class.union]p1: If a union contains a static data member,
6409  // the program is ill-formed. C++11 drops this restriction.
6410  if (RD->isUnion())
6411  Diag(D.getIdentifierLoc(),
6412  getLangOpts().CPlusPlus11
6413  ? diag::warn_cxx98_compat_static_data_member_in_union
6414  : diag::ext_static_data_member_in_union) << Name;
6415  // We conservatively disallow static data members in anonymous structs.
6416  else if (!RD->getDeclName())
6417  Diag(D.getIdentifierLoc(),
6418  diag::err_static_data_member_not_allowed_in_anon_struct)
6419  << Name << RD->isUnion();
6420  }
6421  }
6422 
6423  // Match up the template parameter lists with the scope specifier, then
6424  // determine whether we have a template or a template specialization.
6425  TemplateParams = MatchTemplateParametersToScopeSpecifier(
6427  D.getCXXScopeSpec(),
6429  ? D.getName().TemplateId
6430  : nullptr,
6431  TemplateParamLists,
6432  /*never a friend*/ false, IsMemberSpecialization, Invalid);
6433 
6434  if (TemplateParams) {
6435  if (!TemplateParams->size() &&
6437  // There is an extraneous 'template<>' for this variable. Complain
6438  // about it, but allow the declaration of the variable.
6439  Diag(TemplateParams->getTemplateLoc(),
6440  diag::err_template_variable_noparams)
6441  << II
6442  << SourceRange(TemplateParams->getTemplateLoc(),
6443  TemplateParams->getRAngleLoc());
6444  TemplateParams = nullptr;
6445  } else {
6447  // This is an explicit specialization or a partial specialization.
6448  // FIXME: Check that we can declare a specialization here.
6449  IsVariableTemplateSpecialization = true;
6450  IsPartialSpecialization = TemplateParams->size() > 0;
6451  } else { // if (TemplateParams->size() > 0)
6452  // This is a template declaration.
6453  IsVariableTemplate = true;
6454 
6455  // Check that we can declare a template here.
6456  if (CheckTemplateDeclScope(S, TemplateParams))
6457  return nullptr;
6458 
6459  // Only C++1y supports variable templates (N3651).
6460  Diag(D.getIdentifierLoc(),
6461  getLangOpts().CPlusPlus14
6462  ? diag::warn_cxx11_compat_variable_template
6463  : diag::ext_variable_template);
6464  }
6465  }
6466  } else {
6467  assert((Invalid ||
6469  "should have a 'template<>' for this decl");
6470  }
6471 
6472  if (IsVariableTemplateSpecialization) {
6473  SourceLocation TemplateKWLoc =
6474  TemplateParamLists.size() > 0
6475  ? TemplateParamLists[0]->getTemplateLoc()
6476  : SourceLocation();
6477  DeclResult Res = ActOnVarTemplateSpecialization(
6478  S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6479  IsPartialSpecialization);
6480  if (Res.isInvalid())
6481  return nullptr;
6482  NewVD = cast<VarDecl>(Res.get());
6483  AddToScope = false;
6484  } else if (D.isDecompositionDeclarator()) {
6485  NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6486  D.getIdentifierLoc(), R, TInfo, SC,
6487  Bindings);
6488  } else
6489  NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6490  D.getIdentifierLoc(), II, R, TInfo, SC);
6491 
6492  // If this is supposed to be a variable template, create it as such.
6493  if (IsVariableTemplate) {
6494  NewTemplate =
6495  VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6496  TemplateParams, NewVD);
6497  NewVD->setDescribedVarTemplate(NewTemplate);
6498  }
6499 
6500  // If this decl has an auto type in need of deduction, make a note of the
6501  // Decl so we can diagnose uses of it in its own initializer.
6502  if (R->getContainedDeducedType())
6503  ParsingInitForAutoVars.insert(NewVD);
6504 
6505  if (D.isInvalidType() || Invalid) {
6506  NewVD->setInvalidDecl();
6507  if (NewTemplate)
6508  NewTemplate->setInvalidDecl();
6509  }
6510 
6511  SetNestedNameSpecifier(NewVD, D);
6512 
6513  // If we have any template parameter lists that don't directly belong to
6514  // the variable (matching the scope specifier), store them.
6515  unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6516  if (TemplateParamLists.size() > VDTemplateParamLists)
6517  NewVD->setTemplateParameterListsInfo(
6518  Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6519 
6520  if (D.getDeclSpec().isConstexprSpecified()) {
6521  NewVD->setConstexpr(true);
6522  // C++1z [dcl.spec.constexpr]p1:
6523  // A static data member declared with the constexpr specifier is
6524  // implicitly an inline variable.
6525  if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6526  NewVD->setImplicitlyInline();
6527  }
6528  }
6529 
6530  if (D.getDeclSpec().isInlineSpecified()) {
6531  if (!getLangOpts().CPlusPlus) {
6532  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6533  << 0;
6534  } else if (CurContext->isFunctionOrMethod()) {
6535  // 'inline' is not allowed on block scope variable declaration.
6537  diag::err_inline_declaration_block_scope) << Name
6539  } else {
6541  getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6542  : diag::ext_inline_variable);
6543  NewVD->setInlineSpecified();
6544  }
6545  }
6546 
6547  // Set the lexical context. If the declarator has a C++ scope specifier, the
6548  // lexical context will be different from the semantic context.
6549  NewVD->setLexicalDeclContext(CurContext);
6550  if (NewTemplate)
6551  NewTemplate->setLexicalDeclContext(CurContext);
6552 
6553  if (IsLocalExternDecl) {
6554  if (D.isDecompositionDeclarator())
6555  for (auto *B : Bindings)
6556  B->setLocalExternDecl();
6557  else
6558  NewVD->setLocalExternDecl();
6559  }
6560 
6561  bool EmitTLSUnsupportedError = false;
6563  // C++11 [dcl.stc]p4:
6564  // When thread_local is applied to a variable of block scope the
6565  // storage-class-specifier static is implied if it does not appear
6566  // explicitly.
6567  // Core issue: 'static' is not implied if the variable is declared
6568  // 'extern'.
6569  if (NewVD->hasLocalStorage() &&
6570  (SCSpec != DeclSpec::SCS_unspecified ||
6571  TSCS != DeclSpec::TSCS_thread_local ||
6572  !DC->isFunctionOrMethod()))
6574  diag::err_thread_non_global)
6575  << DeclSpec::getSpecifierName(TSCS);
6576  else if (!Context.getTargetInfo().isTLSSupported()) {
6577  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6578  // Postpone error emission until we've collected attributes required to
6579  // figure out whether it's a host or device variable and whether the
6580  // error should be ignored.
6581  EmitTLSUnsupportedError = true;
6582  // We still need to mark the variable as TLS so it shows up in AST with
6583  // proper storage class for other tools to use even if we're not going
6584  // to emit any code for it.
6585  NewVD->setTSCSpec(TSCS);
6586  } else
6588  diag::err_thread_unsupported);
6589  } else
6590  NewVD->setTSCSpec(TSCS);
6591  }
6592 
6593  // C99 6.7.4p3
6594  // An inline definition of a function with external linkage shall
6595  // not contain a definition of a modifiable object with static or
6596  // thread storage duration...
6597  // We only apply this when the function is required to be defined
6598  // elsewhere, i.e. when the function is not 'extern inline'. Note
6599  // that a local variable with thread storage duration still has to
6600  // be marked 'static'. Also note that it's possible to get these
6601  // semantics in C++ using __attribute__((gnu_inline)).
6602  if (SC == SC_Static && S->getFnParent() != nullptr &&
6603  !NewVD->getType().isConstQualified()) {
6604  FunctionDecl *CurFD = getCurFunctionDecl();
6605  if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6607  diag::warn_static_local_in_extern_inline);
6608  MaybeSuggestAddingStaticToDecl(CurFD);
6609  }
6610  }
6611 
6613  if (IsVariableTemplateSpecialization)
6614  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6615  << (IsPartialSpecialization ? 1 : 0)
6618  else if (IsMemberSpecialization)
6619  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6620  << 2
6622  else if (NewVD->hasLocalStorage())
6623  Diag(NewVD->getLocation(), diag::err_module_private_local)
6624  << 0 << NewVD->getDeclName()
6627  else {
6628  NewVD->setModulePrivate();
6629  if (NewTemplate)
6630  NewTemplate->setModulePrivate();
6631  for (auto *B : Bindings)
6632  B->setModulePrivate();
6633  }
6634  }
6635 
6636  // Handle attributes prior to checking for duplicates in MergeVarDecl
6637  ProcessDeclAttributes(S, NewVD, D);
6638 
6639  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6640  if (EmitTLSUnsupportedError &&
6641  ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6642  (getLangOpts().OpenMPIsDevice &&
6643  NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6645  diag::err_thread_unsupported);
6646  // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6647  // storage [duration]."
6648  if (SC == SC_None && S->getFnParent() != nullptr &&
6649  (NewVD->hasAttr<CUDASharedAttr>() ||
6650  NewVD->hasAttr<CUDAConstantAttr>())) {
6651  NewVD->setStorageClass(SC_Static);
6652  }
6653  }
6654 
6655  // Ensure that dllimport globals without explicit storage class are treated as
6656  // extern. The storage class is set above using parsed attributes. Now we can
6657  // check the VarDecl itself.
6658  assert(!NewVD->hasAttr<DLLImportAttr>() ||
6659  NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6660  NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6661 
6662  // In auto-retain/release, infer strong retension for variables of
6663  // retainable type.
6664  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6665  NewVD->setInvalidDecl();
6666 
6667  // Handle GNU asm-label extension (encoded as an attribute).
6668  if (Expr *E = (Expr*)D.getAsmLabel()) {
6669  // The parser guarantees this is a string.
6670  StringLiteral *SE = cast<StringLiteral>(E);
6671  StringRef Label = SE->getString();
6672  if (S->getFnParent() != nullptr) {
6673  switch (SC) {
6674  case SC_None:
6675  case SC_Auto:
6676  Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6677  break;
6678  case SC_Register:
6679  // Local Named register
6680  if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6681  DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6682  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6683  break;
6684  case SC_Static:
6685  case SC_Extern:
6686  case SC_PrivateExtern:
6687  break;
6688  }
6689  } else if (SC == SC_Register) {
6690  // Global Named register
6691  if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6692  const auto &TI = Context.getTargetInfo();
6693  bool HasSizeMismatch;
6694 
6695  if (!TI.isValidGCCRegisterName(Label))
6696  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6697  else if (!TI.validateGlobalRegisterVariable(Label,
6698  Context.getTypeSize(R),
6699  HasSizeMismatch))
6700  Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6701  else if (HasSizeMismatch)
6702  Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6703  }
6704 
6705  if (!R->isIntegralType(Context) && !R->isPointerType()) {
6706  Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6707  NewVD->setInvalidDecl(true);
6708  }
6709  }
6710 
6711  NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6712  Context, Label, 0));
6713  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6714  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6715  ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6716  if (I != ExtnameUndeclaredIdentifiers.end()) {
6717  if (isDeclExternC(NewVD)) {
6718  NewVD->addAttr(I->second);
6719  ExtnameUndeclaredIdentifiers.erase(I);
6720  } else
6721  Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6722  << /*Variable*/1 << NewVD;
6723  }
6724  }
6725 
6726  // Find the shadowed declaration before filtering for scope.
6727  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6728  ? getShadowedDeclaration(NewVD, Previous)
6729  : nullptr;
6730 
6731  // Don't consider existing declarations that are in a different
6732  // scope and are out-of-semantic-context declarations (if the new
6733  // declaration has linkage).
6734  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6735  D.getCXXScopeSpec().isNotEmpty() ||
6736  IsMemberSpecialization ||
6737  IsVariableTemplateSpecialization);
6738 
6739  // Check whether the previous declaration is in the same block scope. This
6740  // affects whether we merge types with it, per C++11 [dcl.array]p3.
6741  if (getLangOpts().CPlusPlus &&
6742  NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6744  Previous.isSingleResult() && !Previous.isShadowed() &&
6745  isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6746 
6747  if (!getLangOpts().CPlusPlus) {
6748  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6749  } else {
6750  // If this is an explicit specialization of a static data member, check it.
6751  if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6752  CheckMemberSpecialization(NewVD, Previous))
6753  NewVD->setInvalidDecl();
6754 
6755  // Merge the decl with the existing one if appropriate.
6756  if (!Previous.empty()) {
6757  if (Previous.isSingleResult() &&
6758  isa<FieldDecl>(Previous.getFoundDecl()) &&
6759  D.getCXXScopeSpec().isSet()) {
6760  // The user tried to define a non-static data member
6761  // out-of-line (C++ [dcl.meaning]p1).
6762  Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6763  << D.getCXXScopeSpec().getRange();
6764  Previous.clear();
6765  NewVD->setInvalidDecl();
6766  }
6767  } else if (D.getCXXScopeSpec().isSet()) {
6768  // No previous declaration in the qualifying scope.
6769  Diag(D.getIdentifierLoc(), diag::err_no_member)
6770  << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6771  << D.getCXXScopeSpec().getRange();
6772  NewVD->setInvalidDecl();
6773  }
6774 
6775  if (!IsVariableTemplateSpecialization)
6776  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6777 
6778  if (NewTemplate) {
6779  VarTemplateDecl *PrevVarTemplate =
6780  NewVD->getPreviousDecl()
6782  : nullptr;
6783 
6784  // Check the template parameter list of this declaration, possibly
6785  // merging in the template parameter list from the previous variable
6786  // template declaration.
6787  if (CheckTemplateParameterList(
6788  TemplateParams,
6789  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6790  : nullptr,
6791  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6792  DC->isDependentContext())
6793  ? TPC_ClassTemplateMember
6794  : TPC_VarTemplate))
6795  NewVD->setInvalidDecl();
6796 
6797  // If we are providing an explicit specialization of a static variable
6798  // template, make a note of that.
6799  if (PrevVarTemplate &&
6800  PrevVarTemplate->getInstantiatedFromMemberTemplate())
6801  PrevVarTemplate->setMemberSpecialization();
6802  }
6803  }
6804 
6805  // Diagnose shadowed variables iff this isn't a redeclaration.
6806  if (ShadowedDecl && !D.isRedeclaration())
6807  CheckShadow(NewVD, ShadowedDecl, Previous);
6808 
6809  ProcessPragmaWeak(S, NewVD);
6810 
6811  // If this is the first declaration of an extern C variable, update
6812  // the map of such variables.
6813  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6814  isIncompleteDeclExternC(*this, NewVD))
6815  RegisterLocallyScopedExternCDecl(NewVD, S);
6816 
6817  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6818  Decl *ManglingContextDecl;
6819  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6820  NewVD->getDeclContext(), ManglingContextDecl)) {
6821  Context.setManglingNumber(
6822  NewVD, MCtx->getManglingNumber(
6823  NewVD, getMSManglingNumber(getLangOpts(), S)));
6824  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6825  }
6826  }
6827 
6828  // Special handling of variable named 'main'.
6829  if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6831  !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6832 
6833  // C++ [basic.start.main]p3
6834  // A program that declares a variable main at global scope is ill-formed.
6835  if (getLangOpts().CPlusPlus)
6836  Diag(D.getLocStart(), diag::err_main_global_variable);
6837 
6838  // In C, and external-linkage variable named main results in undefined
6839  // behavior.
6840  else if (NewVD->hasExternalFormalLinkage())
6841  Diag(D.getLocStart(), diag::warn_main_redefined);
6842  }
6843 
6844  if (D.isRedeclaration() && !Previous.empty()) {
6846  *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6847  IsMemberSpecialization, D.isFunctionDefinition());
6848  }
6849 
6850  if (NewTemplate) {
6851  if (NewVD->isInvalidDecl())
6852  NewTemplate->setInvalidDecl();
6853  ActOnDocumentableDecl(NewTemplate);
6854  return NewTemplate;
6855  }
6856 
6857  if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6858  CompleteMemberSpecialization(NewVD, Previous);
6859 
6860  return NewVD;
6861 }
6862 
6863 /// Enum describing the %select options in diag::warn_decl_shadow.
6871 };
6872 
6873 /// Determine what kind of declaration we're shadowing.
6875  const DeclContext *OldDC) {
6876  if (isa<TypeAliasDecl>(ShadowedDecl))
6877  return SDK_Using;
6878  else if (isa<TypedefDecl>(ShadowedDecl))
6879  return SDK_Typedef;
6880  else if (isa<RecordDecl>(OldDC))
6881  return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6882 
6883  return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6884 }
6885 
6886 /// Return the location of the capture if the given lambda captures the given
6887 /// variable \p VD, or an invalid source location otherwise.
6889  const VarDecl *VD) {
6890  for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6891  if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6892  return Capture.getLocation();
6893  }
6894  return SourceLocation();
6895 }
6896 
6898  const LookupResult &R) {
6899  // Only diagnose if we're shadowing an unambiguous field or variable.
6901  return false;
6902 
6903  // Return false if warning is ignored.
6904  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6905 }
6906 
6907 /// \brief Return the declaration shadowed by the given variable \p D, or null
6908 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6910  const LookupResult &R) {
6911  if (!shouldWarnIfShadowedDecl(Diags, R))
6912  return nullptr;
6913 
6914  // Don't diagnose declarations at file scope.
6915  if (D->hasGlobalStorage())
6916  return nullptr;
6917 
6918  NamedDecl *ShadowedDecl = R.getFoundDecl();
6919  return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6920  ? ShadowedDecl
6921  : nullptr;
6922 }
6923 
6924 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6925 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6927  const LookupResult &R) {
6928  // Don't warn if typedef declaration is part of a class
6929  if (D->getDeclContext()->isRecord())
6930  return nullptr;
6931 
6932  if (!shouldWarnIfShadowedDecl(Diags, R))
6933  return nullptr;
6934 
6935  NamedDecl *ShadowedDecl = R.getFoundDecl();
6936  return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6937 }
6938 
6939 /// \brief Diagnose variable or built-in function shadowing. Implements
6940 /// -Wshadow.
6941 ///
6942 /// This method is called whenever a VarDecl is added to a "useful"
6943 /// scope.
6944 ///
6945 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6946 /// \param R the lookup of the name
6947 ///
6948 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6949  const LookupResult &R) {
6950  DeclContext *NewDC = D->getDeclContext();
6951 
6952  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6953  // Fields are not shadowed by variables in C++ static methods.
6954  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6955  if (MD->isStatic())
6956  return;
6957 
6958  // Fields shadowed by constructor parameters are a special case. Usually
6959  // the constructor initializes the field with the parameter.
6960  if (isa<CXXConstructorDecl>(NewDC))
6961  if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6962  // Remember that this was shadowed so we can either warn about its
6963  // modification or its existence depending on warning settings.
6964  ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6965  return;
6966  }
6967  }
6968 
6969  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6970  if (shadowedVar->isExternC()) {
6971  // For shadowing external vars, make sure that we point to the global
6972  // declaration, not a locally scoped extern declaration.
6973  for (auto I : shadowedVar->redecls())
6974  if (I->isFileVarDecl()) {
6975  ShadowedDecl = I;
6976  break;
6977  }
6978  }
6979 
6980  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6981 
6982  unsigned WarningDiag = diag::warn_decl_shadow;
6983  SourceLocation CaptureLoc;
6984  if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6985  isa<CXXMethodDecl>(NewDC)) {
6986  if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6987  if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6988  if (RD->getLambdaCaptureDefault() == LCD_None) {
6989  // Try to avoid warnings for lambdas with an explicit capture list.
6990  const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6991  // Warn only when the lambda captures the shadowed decl explicitly.
6992  CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6993  if (CaptureLoc.isInvalid())
6994  WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6995  } else {
6996  // Remember that this was shadowed so we can avoid the warning if the
6997  // shadowed decl isn't captured and the warning settings allow it.
6998  cast<LambdaScopeInfo>(getCurFunction())
6999  ->ShadowingDecls.push_back(
7000  {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7001  return;
7002  }
7003  }
7004 
7005  if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7006  // A variable can't shadow a local variable in an enclosing scope, if
7007  // they are separated by a non-capturing declaration context.
7008  for (DeclContext *ParentDC = NewDC;
7009  ParentDC && !ParentDC->Equals(OldDC);
7010  ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7011  // Only block literals, captured statements, and lambda expressions
7012  // can capture; other scopes don't.
7013  if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7014  !isLambdaCallOperator(ParentDC)) {
7015  return;
7016  }
7017  }
7018  }
7019  }
7020  }
7021 
7022  // Only warn about certain kinds of shadowing for class members.
7023  if (NewDC && NewDC->isRecord()) {
7024  // In particular, don't warn about shadowing non-class members.
7025  if (!OldDC->isRecord())
7026  return;
7027 
7028  // TODO: should we warn about static data members shadowing
7029  // static data members from base classes?
7030 
7031  // TODO: don't diagnose for inaccessible shadowed members.
7032  // This is hard to do perfectly because we might friend the
7033  // shadowing context, but that's just a false negative.
7034  }
7035 
7036 
7037  DeclarationName Name = R.getLookupName();
7038 
7039  // Emit warning and note.
7040  if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7041  return;
7042  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7043  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7044  if (!CaptureLoc.isInvalid())
7045  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7046  << Name << /*explicitly*/ 1;
7047  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048 }
7049 
7050 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7051 /// when these variables are captured by the lambda.
7053  for (const auto &Shadow : LSI->ShadowingDecls) {
7054  const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7055  // Try to avoid the warning when the shadowed decl isn't captured.
7056  SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7057  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7058  Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7059  ? diag::warn_decl_shadow_uncaptured_local
7060  : diag::warn_decl_shadow)
7061  << Shadow.VD->getDeclName()
7062  << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7063  if (!CaptureLoc.isInvalid())
7064  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7065  << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7066  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7067  }
7068 }
7069 
7070 /// \brief Check -Wshadow without the advantage of a previous lookup.
7072  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7073  return;
7074 
7075  LookupResult R(*this, D->getDeclName(), D->getLocation(),
7077  LookupName(R, S);
7078  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7079  CheckShadow(D, ShadowedDecl, R);
7080 }
7081 
7082 /// Check if 'E', which is an expression that is about to be modified, refers
7083 /// to a constructor parameter that shadows a field.
7085  // Quickly ignore expressions that can't be shadowing ctor parameters.
7086  if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7087  return;
7088  E = E->IgnoreParenImpCasts();
7089  auto *DRE = dyn_cast<DeclRefExpr>(E);
7090  if (!DRE)
7091  return;
7092  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7093  auto I = ShadowingDecls.find(D);
7094  if (I == ShadowingDecls.end())
7095  return;
7096  const NamedDecl *ShadowedDecl = I->second;
7097  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7098  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7099  Diag(D->getLocation(), diag::note_var_declared_here) << D;
7100  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7101 
7102  // Avoid issuing multiple warnings about the same decl.
7103  ShadowingDecls.erase(I);
7104 }
7105 
7106 /// Check for conflict between this global or extern "C" declaration and
7107 /// previous global or extern "C" declarations. This is only used in C++.
7108 template<typename T>
7110  Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7111  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7112  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7113 
7114  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7115  // The common case: this global doesn't conflict with any extern "C"
7116  // declaration.
7117  return false;
7118  }
7119 
7120  if (Prev) {
7121  if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7122  // Both the old and new declarations have C language linkage. This is a
7123  // redeclaration.
7124  Previous.clear();
7125  Previous.addDecl(Prev);
7126  return true;
7127  }
7128 
7129  // This is a global, non-extern "C" declaration, and there is a previous
7130  // non-global extern "C" declaration. Diagnose if this is a variable
7131  // declaration.
7132  if (!isa<VarDecl>(ND))
7133  return false;
7134  } else {
7135  // The declaration is extern "C". Check for any declaration in the
7136  // translation unit which might conflict.
7137  if (IsGlobal) {
7138  // We have already performed the lookup into the translation unit.
7139  IsGlobal = false;
7140  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7141  I != E; ++I) {
7142  if (isa<VarDecl>(*I)) {
7143  Prev = *I;
7144  break;
7145  }
7146  }
7147  } else {
7149  S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7150  for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7151  I != E; ++I) {
7152  if (isa<VarDecl>(*I)) {
7153  Prev = *I;
7154  break;
7155  }
7156  // FIXME: If we have any other entity with this name in global scope,
7157  // the declaration is ill-formed, but that is a defect: it breaks the
7158  // 'stat' hack, for instance. Only variables can have mangled name
7159  // clashes with extern "C" declarations, so only they deserve a
7160  // diagnostic.
7161  }
7162  }
7163 
7164  if (!Prev)
7165  return false;
7166  }
7167 
7168  // Use the first declaration's location to ensure we point at something which
7169  // is lexically inside an extern "C" linkage-spec.
7170  assert(Prev && "should have found a previous declaration to diagnose");
7171  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7172  Prev = FD->getFirstDecl();
7173  else
7174  Prev = cast<VarDecl>(Prev)->getFirstDecl();
7175 
7176  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7177  << IsGlobal << ND;
7178  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7179  << IsGlobal;
7180  return false;
7181 }
7182 
7183 /// Apply special rules for handling extern "C" declarations. Returns \c true
7184 /// if we have found that this is a redeclaration of some prior entity.
7185 ///
7186 /// Per C++ [dcl.link]p6:
7187 /// Two declarations [for a function or variable] with C language linkage
7188 /// with the same name that appear in different scopes refer to the same
7189 /// [entity]. An entity with C language linkage shall not be declared with
7190 /// the same name as an entity in global scope.
7191 template<typename T>
7194  if (!S.getLangOpts().CPlusPlus) {
7195  // In C, when declaring a global variable, look for a corresponding 'extern'
7196  // variable declared in function scope. We don't need this in C++, because
7197  // we find local extern decls in the surrounding file-scope DeclContext.
7198  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7199  if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7200  Previous.clear();
7201  Previous.addDecl(Prev);
7202  return true;
7203  }
7204  }
7205  return false;
7206  }
7207 
7208  // A declaration in the translation unit can conflict with an extern "C"
7209  // declaration.
7210  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7211  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7212 
7213  // An extern "C" declaration can conflict with a declaration in the
7214  // translation unit or can be a redeclaration of an extern "C" declaration
7215  // in another scope.
7216  if (isIncompleteDeclExternC(S,ND))
7217  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7218 
7219  // Neither global nor extern "C": nothing to do.
7220  return false;
7221 }
7222 
7224  // If the decl is already known invalid, don't check it.
7225  if (NewVD->isInvalidDecl())
7226  return;
7227 
7228  TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7229  QualType T = TInfo->getType();
7230 
7231  // Defer checking an 'auto' type until its initializer is attached.
7232  if (T->isUndeducedType())
7233  return;
7234 
7235  if (NewVD->hasAttrs())
7236  CheckAlignasUnderalignment(NewVD);
7237 
7238  if (T->isObjCObjectType()) {
7239  Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7240  << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7241  T = Context.getObjCObjectPointerType(T);
7242  NewVD->setType(T);
7243  }
7244 
7245  // Emit an error if an address space was applied to decl with local storage.
7246  // This includes arrays of objects with address space qualifiers, but not
7247  // automatic variables that point to other address spaces.
7248  // ISO/IEC TR 18037 S5.1.2
7249  if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7251  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7252  NewVD->setInvalidDecl();
7253  return;
7254  }
7255 
7256  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7257  // scope.
7258  if (getLangOpts().OpenCLVersion == 120 &&
7259  !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7260  NewVD->isStaticLocal()) {
7261  Diag(NewVD->getLocation(), diag::err_static_function_scope);
7262  NewVD->setInvalidDecl();
7263  return;
7264  }
7265 
7266  if (getLangOpts().OpenCL) {
7267  // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7268  if (NewVD->hasAttr<BlocksAttr>()) {
7269  Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7270  return;
7271  }
7272 
7273  if (T->isBlockPointerType()) {
7274  // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7275  // can't use 'extern' storage class.
7276  if (!T.isConstQualified()) {
7277  Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7278  << 0 /*const*/;
7279  NewVD->setInvalidDecl();
7280  return;
7281  }
7282  if (NewVD->hasExternalStorage()) {
7283  Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7284  NewVD->setInvalidDecl();
7285  return;
7286  }
7287  }
7288  // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7289  // __constant address space.
7290  // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7291  // variables inside a function can also be declared in the global
7292  // address space.
7293  if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7294  NewVD->hasExternalStorage()) {
7295  if (!T->isSamplerT() &&
7298  getLangOpts().OpenCLVersion == 200))) {
7299  int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7300  if (getLangOpts().OpenCLVersion == 200)
7301  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7302  << Scope << "global or constant";
7303  else
7304  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7305  << Scope << "constant";
7306  NewVD->setInvalidDecl();
7307  return;
7308  }
7309  } else {
7311  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7312  << 1 /*is any function*/ << "global";
7313  NewVD->setInvalidDecl();
7314  return;
7315  }
7318  FunctionDecl *FD = getCurFunctionDecl();
7319  // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7320  // in functions.
7321  if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7323  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7324  << 0 /*non-kernel only*/ << "constant";
7325  else
7326  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7327  << 0 /*non-kernel only*/ << "local";
7328  NewVD->setInvalidDecl();
7329  return;
7330  }
7331  // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7332  // in the outermost scope of a kernel function.
7333  if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7334  if (!getCurScope()->isFunctionScope()) {
7336  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7337  << "constant";
7338  else
7339  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7340  << "local";
7341  NewVD->setInvalidDecl();
7342  return;
7343  }
7344  }
7345  } else if (T.getAddressSpace() != LangAS::opencl_private) {
7346  // Do not allow other address spaces on automatic variable.
7347  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7348  NewVD->setInvalidDecl();
7349  return;
7350  }
7351  }
7352  }
7353 
7354  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7355  && !NewVD->hasAttr<BlocksAttr>()) {
7356  if (getLangOpts().getGC() != LangOptions::NonGC)
7357  Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7358  else {
7359  assert(!getLangOpts().ObjCAutoRefCount);
7360  Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7361  }
7362  }
7363 
7364  bool isVM = T->isVariablyModifiedType();
7365  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7366  NewVD->hasAttr<BlocksAttr>())
7367  getCurFunction()->setHasBranchProtectedScope();
7368 
7369  if ((isVM && NewVD->hasLinkage()) ||
7370  (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7371  bool SizeIsNegative;
7372  llvm::APSInt Oversized;
7373  TypeSourceInfo *FixedTInfo =
7375  SizeIsNegative, Oversized);
7376  if (!FixedTInfo && T->isVariableArrayType()) {
7377  const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7378  // FIXME: This won't give the correct result for
7379  // int a[10][n];
7380  SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7381 
7382  if (NewVD->isFileVarDecl())
7383  Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7384  << SizeRange;
7385  else if (NewVD->isStaticLocal())
7386  Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7387  << SizeRange;
7388  else
7389  Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7390  << SizeRange;
7391  NewVD->setInvalidDecl();
7392  return;
7393  }
7394 
7395  if (!FixedTInfo) {
7396  if (NewVD->isFileVarDecl())
7397  Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7398  else
7399  Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7400  NewVD->setInvalidDecl();
7401  return;
7402  }
7403 
7404  Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7405  NewVD->setType(FixedTInfo->getType());
7406  NewVD->setTypeSourceInfo(FixedTInfo);
7407  }
7408 
7409  if (T->isVoidType()) {
7410  // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7411  // of objects and functions.
7412  if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7413  Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7414  << T;
7415  NewVD->setInvalidDecl();
7416  return;
7417  }
7418  }
7419 
7420  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7421  Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7422  NewVD->setInvalidDecl();
7423  return;
7424  }
7425 
7426  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7427  Diag(NewVD->getLocation(), diag::err_block_on_vm);
7428  NewVD->setInvalidDecl();
7429  return;
7430  }
7431 
7432  if (NewVD->isConstexpr() && !T->isDependentType() &&
7433  RequireLiteralType(NewVD->getLocation(), T,
7434  diag::err_constexpr_var_non_literal)) {
7435  NewVD->setInvalidDecl();
7436  return;
7437  }
7438 }
7439 
7440 /// \brief Perform semantic checking on a newly-created variable
7441 /// declaration.
7442 ///
7443 /// This routine performs all of the type-checking required for a
7444 /// variable declaration once it has been built. It is used both to
7445 /// check variables after they have been parsed and their declarators
7446 /// have been translated into a declaration, and to check variables
7447 /// that have been instantiated from a template.
7448 ///
7449 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7450 ///
7451 /// Returns true if the variable declaration is a redeclaration.
7453  CheckVariableDeclarationType(NewVD);
7454 
7455  // If the decl is already known invalid, don't check it.
7456  if (NewVD->isInvalidDecl())
7457  return false;
7458 
7459  // If we did not find anything by this name, look for a non-visible
7460  // extern "C" declaration with the same name.
7461  if (Previous.empty() &&
7462  checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7463  Previous.setShadowed();
7464 
7465  if (!Previous.empty()) {
7466  MergeVarDecl(NewVD, Previous);
7467  return true;
7468  }
7469  return false;
7470 }
7471 
7472 namespace {
7473 struct FindOverriddenMethod {
7474  Sema *S;
7475  CXXMethodDecl *Method;
7476 
7477  /// Member lookup function that determines whether a given C++
7478  /// method overrides a method in a base class, to be used with
7479  /// CXXRecordDecl::lookupInBases().
7480  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7481  RecordDecl *BaseRecord =
7482  Specifier->getType()->getAs<RecordType>()->getDecl();
7483 
7484  DeclarationName Name = Method->getDeclName();
7485 
7486  // FIXME: Do we care about other names here too?
7488  // We really want to find the base class destructor here.
7489  QualType T = S->Context.getTypeDeclType(BaseRecord);
7491 
7493  }
7494 
7495  for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7496  Path.Decls = Path.Decls.slice(1)) {
7497  NamedDecl *D = Path.Decls.front();
7498  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7499  if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7500  return true;
7501  }
7502  }
7503 
7504  return false;
7505  }
7506 };
7507 
7508 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7509 } // end anonymous namespace
7510 
7511 /// \brief Report an error regarding overriding, along with any relevant
7512 /// overriden methods.
7513 ///
7514 /// \param DiagID the primary error to report.
7515 /// \param MD the overriding method.
7516 /// \param OEK which overrides to include as notes.
7517 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7518  OverrideErrorKind OEK = OEK_All) {
7519  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7520  for (const CXXMethodDecl *O : MD->overridden_methods()) {
7521  // This check (& the OEK parameter) could be replaced by a predicate, but
7522  // without lambdas that would be overkill. This is still nicer than writing
7523  // out the diag loop 3 times.
7524  if ((OEK == OEK_All) ||
7525  (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7526  (OEK == OEK_Deleted && O->isDeleted()))
7527  S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7528  }
7529 }
7530 
7531 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7532 /// and if so, check that it's a valid override and remember it.
7534  // Look for methods in base classes that this method might override.
7535  CXXBasePaths Paths;
7536  FindOverriddenMethod FOM;
7537  FOM.Method = MD;
7538  FOM.S = this;
7539  bool hasDeletedOverridenMethods = false;
7540  bool hasNonDeletedOverridenMethods = false;
7541  bool AddedAny = false;
7542  if (DC->lookupInBases(FOM, Paths)) {
7543  for (auto *I : Paths.found_decls()) {
7544  if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7545  MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7546  if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7547  !CheckOverridingFunctionAttributes(MD, OldMD) &&
7548  !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7549  !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7550  hasDeletedOverridenMethods |= OldMD->isDeleted();
7551  hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7552  AddedAny = true;
7553  }
7554  }
7555  }
7556  }
7557 
7558  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7559  ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7560  }
7561  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7562  ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7563  }
7564 
7565  return AddedAny;
7566 }
7567 
7568 namespace {
7569  // Struct for holding all of the extra arguments needed by
7570  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7571  struct ActOnFDArgs {
7572  Scope *S;
7573  Declarator &D;
7574  MultiTemplateParamsArg TemplateParamLists;
7575  bool AddToScope;
7576  };
7577 } // end anonymous namespace
7578 
7579 namespace {
7580 
7581 // Callback to only accept typo corrections that have a non-zero edit distance.
7582 // Also only accept corrections that have the same parent decl.
7583 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7584  public:
7585  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7587  : Context(Context), OriginalFD(TypoFD),
7588  ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7589 
7590  bool ValidateCandidate(const TypoCorrection &candidate) override {
7591  if (candidate.getEditDistance() == 0)
7592  return false;
7593 
7594  SmallVector<unsigned, 1> MismatchedParams;
7595  for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7596  CDeclEnd = candidate.end();
7597  CDecl != CDeclEnd; ++CDecl) {
7598  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7599 
7600  if (FD && !FD->hasBody() &&
7601  hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7602  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7603  CXXRecordDecl *Parent = MD->getParent();
7604  if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7605  return true;
7606  } else if (!ExpectedParent) {
7607  return true;
7608  }
7609  }
7610  }
7611 
7612  return false;
7613  }
7614 
7615  private:
7616  ASTContext &Context;
7617  FunctionDecl *OriginalFD;
7618  CXXRecordDecl *ExpectedParent;
7619 };
7620 
7621 } // end anonymous namespace
7622 
7624  TypoCorrectedFunctionDefinitions.insert(F);
7625 }
7626 
7627 /// \brief Generate diagnostics for an invalid function redeclaration.
7628 ///
7629 /// This routine handles generating the diagnostic messages for an invalid
7630 /// function redeclaration, including finding possible similar declarations
7631 /// or performing typo correction if there are no previous declarations with
7632 /// the same name.
7633 ///
7634 /// Returns a NamedDecl iff typo correction was performed and substituting in
7635 /// the new declaration name does not cause new errors.
7637  Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7638  ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7639  DeclarationName Name = NewFD->getDeclName();
7640  DeclContext *NewDC = NewFD->getDeclContext();
7641  SmallVector<unsigned, 1> MismatchedParams;
7643  TypoCorrection Correction;
7644  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7645  unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7646  : diag::err_member_decl_does_not_match;
7647  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7648  IsLocalFriend ? Sema::LookupLocalFriendName
7651 
7652  NewFD->setInvalidDecl();
7653  if (IsLocalFriend)
7654  SemaRef.LookupName(Prev, S);
7655  else
7656  SemaRef.LookupQualifiedName(Prev, NewDC);
7657  assert(!Prev.isAmbiguous() &&
7658  "Cannot have an ambiguity in previous-declaration lookup");
7659  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7660  if (!Prev.empty()) {
7661  for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7662  Func != FuncEnd; ++Func) {
7663  FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7664  if (FD &&
7665  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7666  // Add 1 to the index so that 0 can mean the mismatch didn't
7667  // involve a parameter
7668  unsigned ParamNum =
7669  MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7670  NearMatches.push_back(std::make_pair(FD, ParamNum));
7671  }
7672  }
7673  // If the qualified name lookup yielded nothing, try typo correction
7674  } else if ((Correction = SemaRef.CorrectTypo(
7675  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7676  &ExtraArgs.D.getCXXScopeSpec(),
7677  llvm::make_unique<DifferentNameValidatorCCC>(
7678  SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7679  Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7680  // Set up everything for the call to ActOnFunctionDeclarator
7681  ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7682  ExtraArgs.D.getIdentifierLoc());
7683  Previous.clear();
7684  Previous.setLookupName(Correction.getCorrection());
7685  for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7686  CDeclEnd = Correction.end();
7687  CDecl != CDeclEnd; ++CDecl) {
7688  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7689  if (FD && !FD->hasBody() &&
7690  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7691  Previous.addDecl(FD);
7692  }
7693  }
7694  bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7695 
7696  NamedDecl *Result;
7697  // Retry building the function declaration with the new previous
7698  // declarations, and with errors suppressed.
7699  {
7700  // Trap errors.
7701  Sema::SFINAETrap Trap(SemaRef);
7702 
7703  // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7704  // pieces need to verify the typo-corrected C++ declaration and hopefully
7705  // eliminate the need for the parameter pack ExtraArgs.
7706  Result = SemaRef.ActOnFunctionDeclarator(
7707  ExtraArgs.S, ExtraArgs.D,
7708  Correction.getCorrectionDecl()->getDeclContext(),
7709  NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7710  ExtraArgs.AddToScope);
7711 
7712  if (Trap.hasErrorOccurred())
7713  Result = nullptr;
7714  }
7715 
7716  if (Result) {
7717  // Determine which correction we picked.
7718  Decl *Canonical = Result->getCanonicalDecl();
7719  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7720  I != E; ++I)
7721  if ((*I)->getCanonicalDecl() == Canonical)
7722  Correction.setCorrectionDecl(*I);
7723 
7724  // Let Sema know about the correction.
7725  SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7726  SemaRef.diagnoseTypo(
7727  Correction,
7728  SemaRef.PDiag(IsLocalFriend
7729  ? diag::err_no_matching_local_friend_suggest
7730  : diag::err_member_decl_does_not_match_suggest)
7731  << Name << NewDC << IsDefinition);
7732  return Result;
7733  }
7734 
7735  // Pretend the typo correction never occurred
7736  ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7737  ExtraArgs.D.getIdentifierLoc());
7738  ExtraArgs.D.setRedeclaration(wasRedeclaration);
7739  Previous.clear();
7740  Previous.setLookupName(Name);
7741  }
7742 
7743  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7744  << Name << NewDC << IsDefinition << NewFD->getLocation();
7745 
7746  bool NewFDisConst = false;
7747  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7748  NewFDisConst = NewMD->isConst();
7749 
7750  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7751  NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7752  NearMatch != NearMatchEnd; ++NearMatch) {
7753  FunctionDecl *FD = NearMatch->first;
7754  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7755  bool FDisConst = MD && MD->isConst();
7756  bool IsMember = MD || !IsLocalFriend;
7757 
7758  // FIXME: These notes are poorly worded for the local friend case.
7759  if (unsigned Idx = NearMatch->second) {
7760  ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7761  SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7762  if (Loc.isInvalid()) Loc = FD->getLocation();
7763  SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7764  : diag::note_local_decl_close_param_match)
7765  << Idx << FDParam->getType()
7766  << NewFD->getParamDecl(Idx - 1)->getType();
7767  } else if (FDisConst != NewFDisConst) {
7768  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7769  << NewFDisConst << FD->getSourceRange().getEnd();
7770  } else
7771  SemaRef.Diag(FD->getLocation(),
7772  IsMember ? diag::note_member_def_close_match
7773  : diag::note_local_decl_close_match);
7774  }
7775  return nullptr;
7776 }
7777 
7779  switch (D.getDeclSpec().getStorageClassSpec()) {
7780  default: llvm_unreachable("Unknown storage class!");
7781  case DeclSpec::SCS_auto:
7783  case DeclSpec::SCS_mutable:
7784  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7785  diag::err_typecheck_sclass_func);
7787  D.setInvalidType();
7788  break;
7789  case DeclSpec::SCS_unspecified: break;
7790  case DeclSpec::SCS_extern:
7792  return SC_None;
7793  return SC_Extern;
7794  case DeclSpec::SCS_static: {
7795  if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7796  // C99 6.7.1p5:
7797  // The declaration of an identifier for a function that has
7798  // block scope shall have no explicit storage-class specifier
7799  // other than extern
7800  // See also (C++ [dcl.stc]p4).
7801  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7802  diag::err_static_block_func);
7803  break;
7804  } else
7805  return SC_Static;
7806  }
7808  }
7809 
7810  // No explicit storage class has already been returned
7811  return SC_None;
7812 }
7813 
7815  DeclContext *DC, QualType &R,
7816  TypeSourceInfo *TInfo,
7817  StorageClass SC,
7818  bool &IsVirtualOkay) {
7819  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7820  DeclarationName Name = NameInfo.getName();
7821 
7822  FunctionDecl *NewFD = nullptr;
7823  bool isInline = D.getDeclSpec().isInlineSpecified();
7824 
7825  if (!SemaRef.getLangOpts().CPlusPlus) {
7826  // Determine whether the function was written with a
7827  // prototype. This true when:
7828  // - there is a prototype in the declarator, or
7829  // - the type R of the function is some kind of typedef or other non-
7830  // attributed reference to a type name (which eventually refers to a
7831  // function type).
7832  bool HasPrototype =
7835 
7836  NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7837  D.getLocStart(), NameInfo, R,
7838  TInfo, SC, isInline,
7839  HasPrototype, false);
7840  if (D.isInvalidType())
7841  NewFD->setInvalidDecl();
7842 
7843  return NewFD;
7844  }
7845 
7846  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7847  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7848 
7849  // Check that the return type is not an abstract class type.
7850  // For record types, this is done by the AbstractClassUsageDiagnoser once
7851  // the class has been completely parsed.
7852  if (!DC->isRecord() &&
7853  SemaRef.RequireNonAbstractType(
7854  D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7855  diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7856  D.setInvalidType();
7857 
7859  // This is a C++ constructor declaration.
7860  assert(DC->isRecord() &&
7861  "Constructors can only be declared in a member context");
7862 
7863  R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7864  return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7865  D.getLocStart(), NameInfo,
7866  R, TInfo, isExplicit, isInline,
7867  /*isImplicitlyDeclared=*/false,
7868  isConstexpr);
7869 
7870  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7871  // This is a C++ destructor declaration.
7872  if (DC->isRecord()) {
7873  R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7874  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7876  SemaRef.Context, Record,
7877  D.getLocStart(),
7878  NameInfo, R, TInfo, isInline,
7879  /*isImplicitlyDeclared=*/false);
7880 
7881  // If the class is complete, then we now create the implicit exception
7882  // specification. If the class is incomplete or dependent, we can't do
7883  // it yet.
7884  if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7885  Record->getDefinition() && !Record->isBeingDefined() &&
7886  R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7887  SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7888  }
7889 
7890  IsVirtualOkay = true;
7891  return NewDD;
7892 
7893  } else {
7894  SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7895  D.setInvalidType();
7896 
7897  // Create a FunctionDecl to satisfy the function definition parsing
7898  // code path.
7899  return FunctionDecl::Create(SemaRef.Context, DC,
7900  D.getLocStart(),
7901  D.getIdentifierLoc(), Name, R, TInfo,
7902  SC, isInline,
7903  /*hasPrototype=*/true, isConstexpr);
7904  }
7905 
7907  if (!DC->isRecord()) {
7908  SemaRef.Diag(D.getIdentifierLoc(),
7909  diag::err_conv_function_not_member);
7910  return nullptr;
7911  }
7912 
7913  SemaRef.CheckConversionDeclarator(D, R, SC);
7914  IsVirtualOkay = true;
7915  return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7916  D.getLocStart(), NameInfo,
7917  R, TInfo, isInline, isExplicit,
7918  isConstexpr, SourceLocation());
7919 
7920  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7921  SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7922 
7923  return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7924  isExplicit, NameInfo, R, TInfo,
7925  D.getLocEnd());
7926  } else if (DC->isRecord()) {
7927  // If the name of the function is the same as the name of the record,
7928  // then this must be an invalid constructor that has a return type.
7929  // (The parser checks for a return type and makes the declarator a
7930  // constructor if it has no return type).
7931  if (Name.getAsIdentifierInfo() &&
7932  Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7933  SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7935  << SourceRange(D.getIdentifierLoc());
7936  return nullptr;
7937  }
7938 
7939  // This is a C++ method declaration.
7941  cast<CXXRecordDecl>(DC),
7942  D.getLocStart(), NameInfo, R,
7943  TInfo, SC, isInline,
7944  isConstexpr, SourceLocation());
7945  IsVirtualOkay = !Ret->isStatic();
7946  return Ret;
7947  } else {
7948  bool isFriend =
7949  SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7950  if (!isFriend && SemaRef.CurContext->isRecord())
7951  return nullptr;
7952 
7953  // Determine whether the function was written with a
7954  // prototype. This true when:
7955  // - we're in C++ (where every function has a prototype),
7956  return FunctionDecl::Create(SemaRef.Context, DC,
7957  D.getLocStart(),
7958  NameInfo, R, TInfo, SC, isInline,
7959  true/*HasPrototype*/, isConstexpr);
7960  }
7961 }
7962 
7970 };
7971 
7973  if (PT->isPointerType()) {
7974  QualType PointeeType = PT->getPointeeType();
7975  if (PointeeType->isPointerType())
7976  return PtrPtrKernelParam;
7977  if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7978  PointeeType.getAddressSpace() == LangAS::opencl_private ||
7979  PointeeType.getAddressSpace() == LangAS::Default)
7981  return PtrKernelParam;
7982  }
7983 
7984  // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7985  // be used as builtin types.
7986 
7987  if (PT->isImageType())
7988  return PtrKernelParam;
7989 
7990  if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7991  return InvalidKernelParam;
7992 
7993  // OpenCL extension spec v1.2 s9.5:
7994  // This extension adds support for half scalar and vector types as built-in
7995  // types that can be used for arithmetic operations, conversions etc.
7996  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7997  return InvalidKernelParam;
7998 
7999  if (PT->isRecordType())
8000  return RecordKernelParam;
8001 
8002  return ValidKernelParam;
8003 }
8004 
8006  Sema &S,
8007  Declarator &D,
8008  ParmVarDecl *Param,
8009  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8010  QualType PT = Param->getType();
8011 
8012  // Cache the valid types we encounter to avoid rechecking structs that are
8013  // used again
8014  if (ValidTypes.count(PT.getTypePtr()))
8015  return;
8016 
8017  switch (getOpenCLKernelParameterType(S, PT)) {
8018  case PtrPtrKernelParam:
8019  // OpenCL v1.2 s6.9.a:
8020  // A kernel function argument cannot be declared as a
8021  // pointer to a pointer type.
8022  S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8023  D.setInvalidType();
8024  return;
8025 
8027  // OpenCL v1.0 s6.5:
8028  // __kernel function arguments declared to be a pointer of a type can point
8029  // to one of the following address spaces only : __global, __local or
8030  // __constant.
8031  S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8032  D.setInvalidType();
8033  return;
8034 
8035  // OpenCL v1.2 s6.9.k:
8036  // Arguments to kernel functions in a program cannot be declared with the
8037  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8038  // uintptr_t or a struct and/or union that contain fields declared to be
8039  // one of these built-in scalar types.
8040 
8041  case InvalidKernelParam:
8042  // OpenCL v1.2 s6.8 n:
8043  // A kernel function argument cannot be declared
8044  // of event_t type.
8045  // Do not diagnose half type since it is diagnosed as invalid argument
8046  // type for any function elsewhere.
8047  if (!PT->isHalfType())
8048  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8049  D.setInvalidType();
8050  return;
8051 
8052  case PtrKernelParam:
8053  case ValidKernelParam:
8054  ValidTypes.insert(PT.getTypePtr());
8055  return;
8056 
8057  case RecordKernelParam:
8058  break;
8059  }
8060 
8061  // Track nested structs we will inspect
8062  SmallVector<const Decl *, 4> VisitStack;
8063 
8064  // Track where we are in the nested structs. Items will migrate from
8065  // VisitStack to HistoryStack as we do the DFS for bad field.
8066  SmallVector<const FieldDecl *, 4> HistoryStack;
8067  HistoryStack.push_back(nullptr);
8068 
8069  const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8070  VisitStack.push_back(PD);
8071 
8072  assert(VisitStack.back() && "First decl null?");
8073 
8074  do {
8075  const Decl *Next = VisitStack.pop_back_val();
8076  if (!Next) {
8077  assert(!HistoryStack.empty());
8078  // Found a marker, we have gone up a level
8079  if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8080  ValidTypes.insert(Hist->getType().getTypePtr());
8081 
8082  continue;
8083  }
8084 
8085  // Adds everything except the original parameter declaration (which is not a
8086  // field itself) to the history stack.
8087  const RecordDecl *RD;
8088  if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8089  HistoryStack.push_back(Field);
8090  RD = Field->getType()->castAs<RecordType>()->getDecl();
8091  } else {
8092  RD = cast<RecordDecl>(Next);
8093  }
8094 
8095  // Add a null marker so we know when we've gone back up a level
8096  VisitStack.push_back(nullptr);
8097 
8098  for (const auto *FD : RD->fields()) {
8099  QualType QT = FD->getType();
8100 
8101  if (ValidTypes.count(QT.getTypePtr()))
8102  continue;
8103 
8104  OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8105  if (ParamType == ValidKernelParam)
8106  continue;
8107 
8108  if (ParamType == RecordKernelParam) {
8109  VisitStack.push_back(FD);
8110  continue;
8111  }
8112 
8113  // OpenCL v1.2 s6.9.p:
8114  // Arguments to kernel functions that are declared to be a struct or union
8115  // do not allow OpenCL objects to be passed as elements of the struct or
8116  // union.
8117  if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8118  ParamType == InvalidAddrSpacePtrKernelParam) {
8119  S.Diag(Param->getLocation(),
8120  diag::err_record_with_pointers_kernel_param)
8121  << PT->isUnionType()
8122  << PT;
8123  } else {
8124  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8125  }
8126 
8127  S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8128  << PD->getDeclName();
8129 
8130  // We have an error, now let's go back up through history and show where
8131  // the offending field came from
8133  I = HistoryStack.begin() + 1,
8134  E = HistoryStack.end();
8135  I != E; ++I) {
8136  const FieldDecl *OuterField = *I;
8137  S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8138  << OuterField->getType();
8139  }
8140 
8141  S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8142  << QT->isPointerType()
8143  << QT;
8144  D.setInvalidType();
8145  return;
8146  }
8147  } while (!VisitStack.empty());
8148 }
8149 
8150 /// Find the DeclContext in which a tag is implicitly declared if we see an
8151 /// elaborated type specifier in the specified context, and lookup finds
8152 /// nothing.
8154  while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8155  DC = DC->getParent();
8156  return DC;
8157 }
8158 
8159 /// Find the Scope in which a tag is implicitly declared if we see an
8160 /// elaborated type specifier in the specified context, and lookup finds
8161 /// nothing.
8162 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8163  while (S->isClassScope() ||
8164  (LangOpts.CPlusPlus &&
8165  S->isFunctionPrototypeScope()) ||
8166  ((S->getFlags() & Scope::DeclScope) == 0) ||
8167  (S->getEntity() && S->getEntity()->isTransparentContext()))
8168  S = S->getParent();
8169  return S;
8170 }
8171 
8172 NamedDecl*
8175  MultiTemplateParamsArg TemplateParamLists,
8176  bool &AddToScope) {
8177  QualType R = TInfo->getType();
8178 
8179  assert(R.getTypePtr()->isFunctionType());
8180 
8181  // TODO: consider using NameInfo for diagnostic.
8182  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8183  DeclarationName Name = NameInfo.getName();
8184  StorageClass SC = getFunctionStorageClass(*this, D);
8185 
8188  diag::err_invalid_thread)
8189  << DeclSpec::getSpecifierName(TSCS);
8190 
8192  adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8193  D.getIdentifierLoc());
8194 
8195  bool isFriend = false;
8196  FunctionTemplateDecl *FunctionTemplate = nullptr;
8197  bool isMemberSpecialization = false;
8198  bool isFunctionTemplateSpecialization = false;
8199 
8200  bool isDependentClassScopeExplicitSpecialization = false;
8201  bool HasExplicitTemplateArgs = false;
8202  TemplateArgumentListInfo TemplateArgs;
8203 
8204  bool isVirtualOkay = false;
8205 
8206  DeclContext *OriginalDC = DC;
8207  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8208 
8209  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8210  isVirtualOkay);
8211  if (!NewFD) return nullptr;
8212 
8213  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8215 
8216  // Set the lexical context. If this is a function-scope declaration, or has a
8217  // C++ scope specifier, or is the object of a friend declaration, the lexical
8218  // context will be different from the semantic context.
8219  NewFD->setLexicalDeclContext(CurContext);
8220 
8221  if (IsLocalExternDecl)
8222  NewFD->setLocalExternDecl();
8223 
8224  if (getLangOpts().CPlusPlus) {
8225  bool isInline = D.getDeclSpec().isInlineSpecified();
8226  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8227  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8228  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8229  isFriend = D.getDeclSpec().isFriendSpecified();
8230  if (isFriend && !isInline && D.isFunctionDefinition()) {
8231  // C++ [class.friend]p5
8232  // A function can be defined in a friend declaration of a
8233  // class . . . . Such a function is implicitly inline.
8234  NewFD->setImplicitlyInline();
8235  }
8236 
8237  // If this is a method defined in an __interface, and is not a constructor
8238  // or an overloaded operator, then set the pure flag (isVirtual will already
8239  // return true).
8240  if (const CXXRecordDecl *Parent =
8241  dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8242  if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8243  NewFD->setPure(true);
8244 
8245  // C++ [class.union]p2
8246  // A union can have member functions, but not virtual functions.
8247  if (isVirtual && Parent->isUnion())
8248  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8249  }
8250 
8251  SetNestedNameSpecifier(NewFD, D);
8252  isMemberSpecialization = false;
8253  isFunctionTemplateSpecialization = false;
8254  if (D.isInvalidType())
8255  NewFD->setInvalidDecl();
8256 
8257  // Match up the template parameter lists with the scope specifier, then
8258  // determine whether we have a template or a template specialization.
8259  bool Invalid = false;
8260  if (TemplateParameterList *TemplateParams =
8261  MatchTemplateParametersToScopeSpecifier(
8263  D.getCXXScopeSpec(),
8265  ? D.getName().TemplateId
8266  : nullptr,
8267  TemplateParamLists, isFriend, isMemberSpecialization,
8268  Invalid)) {
8269  if (TemplateParams->size() > 0) {
8270  // This is a function template
8271 
8272  // Check that we can declare a template here.
8273  if (CheckTemplateDeclScope(S, TemplateParams))
8274  NewFD->setInvalidDecl();
8275 
8276  // A destructor cannot be a template.
8278  Diag(NewFD->getLocation(), diag::err_destructor_template);
8279  NewFD->setInvalidDecl();
8280  }
8281 
8282  // If we're adding a template to a dependent context, we may need to
8283  // rebuilding some of the types used within the template parameter list,
8284  // now that we know what the current instantiation is.
8285  if (DC->isDependentContext()) {
8286  ContextRAII SavedContext(*this, DC);
8287  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8288  Invalid = true;
8289  }
8290 
8291  FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8292  NewFD->getLocation(),
8293  Name, TemplateParams,
8294  NewFD);
8295  FunctionTemplate->setLexicalDeclContext(CurContext);
8296  NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8297 
8298  // For source fidelity, store the other template param lists.
8299  if (TemplateParamLists.size() > 1) {
8300  NewFD->setTemplateParameterListsInfo(Context,
8301  TemplateParamLists.drop_back(1));
8302  }
8303  } else {
8304  // This is a function template specialization.
8305  isFunctionTemplateSpecialization = true;
8306  // For source fidelity, store all the template param lists.
8307  if (TemplateParamLists.size() > 0)
8308  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8309 
8310  // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8311  if (isFriend) {
8312  // We want to remove the "template<>", found here.
8313  SourceRange RemoveRange = TemplateParams->getSourceRange();
8314 
8315  // If we remove the template<> and the name is not a
8316  // template-id, we're actually silently creating a problem:
8317  // the friend declaration will refer to an untemplated decl,
8318  // and clearly the user wants a template specialization. So
8319  // we need to insert '<>' after the name.
8320  SourceLocation InsertLoc;
8322  InsertLoc = D.getName().getSourceRange().getEnd();
8323  InsertLoc = getLocForEndOfToken(InsertLoc);
8324  }
8325 
8326  Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8327  << Name << RemoveRange
8328  << FixItHint::CreateRemoval(RemoveRange)
8329  << FixItHint::CreateInsertion(InsertLoc, "<>");
8330  }
8331  }
8332  }
8333  else {
8334  // All template param lists were matched against the scope specifier:
8335  // this is NOT (an explicit specialization of) a template.
8336  if (TemplateParamLists.size() > 0)
8337  // For source fidelity, store all the template param lists.
8338  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8339  }
8340 
8341  if (Invalid) {
8342  NewFD->setInvalidDecl();
8343  if (FunctionTemplate)
8344  FunctionTemplate->setInvalidDecl();
8345  }
8346 
8347  // C++ [dcl.fct.spec]p5:
8348  // The virtual specifier shall only be used in declarations of
8349  // nonstatic class member functions that appear within a
8350  // member-specification of a class declaration; see 10.3.
8351  //
8352  if (isVirtual && !NewFD->isInvalidDecl()) {
8353  if (!isVirtualOkay) {
8355  diag::err_virtual_non_function);
8356  } else if (!CurContext->isRecord()) {
8357  // 'virtual' was specified outside of the class.
8359  diag::err_virtual_out_of_class)
8361  } else if (NewFD->getDescribedFunctionTemplate()) {
8362  // C++ [temp.mem]p3:
8363  // A member function template shall not be virtual.
8365  diag::err_virtual_member_function_template)
8367  } else {
8368  // Okay: Add virtual to the method.
8369  NewFD->setVirtualAsWritten(true);
8370  }
8371 
8372  if (getLangOpts().CPlusPlus14 &&
8373  NewFD->getReturnType()->isUndeducedType())
8374  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8375  }
8376 
8377  if (getLangOpts().CPlusPlus14 &&
8378  (NewFD->isDependentContext() ||
8379  (isFriend && CurContext->isDependentContext())) &&
8380  NewFD->getReturnType()->isUndeducedType()) {
8381  // If the function template is referenced directly (for instance, as a
8382  // member of the current instantiation), pretend it has a dependent type.
8383  // This is not really justified by the standard, but is the only sane
8384  // thing to do.
8385  // FIXME: For a friend function, we have not marked the function as being
8386  // a friend yet, so 'isDependentContext' on the FD doesn't work.
8387  const FunctionProtoType *FPT =
8388  NewFD->getType()->castAs<FunctionProtoType>();
8389  QualType Result =
8390  SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8391  NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8392  FPT->getExtProtoInfo()));
8393  }
8394 
8395  // C++ [dcl.fct.spec]p3:
8396  // The inline specifier shall not appear on a block scope function
8397  // declaration.
8398  if (isInline && !NewFD->isInvalidDecl()) {
8399  if (CurContext->isFunctionOrMethod()) {
8400  // 'inline' is not allowed on block scope function declaration.
8402  diag::err_inline_declaration_block_scope) << Name
8404  }
8405  }
8406 
8407  // C++ [dcl.fct.spec]p6:
8408  // The explicit specifier shall be used only in the declaration of a
8409  // constructor or conversion function within its class definition;
8410  // see 12.3.1 and 12.3.2.
8411  if (isExplicit && !NewFD->isInvalidDecl() &&
8412  !isa<CXXDeductionGuideDecl>(NewFD)) {
8413  if (!CurContext->isRecord()) {
8414  // 'explicit' was specified outside of the class.
8416  diag::err_explicit_out_of_class)
8418  } else if (!isa<CXXConstructorDecl>(NewFD) &&
8419  !isa<CXXConversionDecl>(NewFD)) {
8420  // 'explicit' was specified on a function that wasn't a constructor
8421  // or conversion function.
8423  diag::err_explicit_non_ctor_or_conv_function)
8425  }
8426  }
8427 
8428  if (isConstexpr) {
8429  // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8430  // are implicitly inline.
8431  NewFD->setImplicitlyInline();
8432 
8433  // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8434  // be either constructors or to return a literal type. Therefore,
8435  // destructors cannot be declared constexpr.
8436  if (isa<CXXDestructorDecl>(NewFD))
8437  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8438  }
8439 
8440  // If __module_private__ was specified, mark the function accordingly.
8442  if (isFunctionTemplateSpecialization) {
8443  SourceLocation ModulePrivateLoc
8445  Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8446  << 0
8447  << FixItHint::CreateRemoval(ModulePrivateLoc);
8448  } else {
8449  NewFD->setModulePrivate();
8450  if (FunctionTemplate)
8451  FunctionTemplate->setModulePrivate();
8452  }
8453  }
8454 
8455  if (isFriend) {
8456  if (FunctionTemplate) {
8457  FunctionTemplate->setObjectOfFriendDecl();
8458  FunctionTemplate->setAccess(AS_public);
8459  }
8460  NewFD->setObjectOfFriendDecl();
8461  NewFD->setAccess(AS_public);
8462  }
8463 
8464  // If a function is defined as defaulted or deleted, mark it as such now.
8465  // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8466  // definition kind to FDK_Definition.
8467  switch (D.getFunctionDefinitionKind()) {
8468  case FDK_Declaration:
8469  case FDK_Definition:
8470  break;
8471 
8472  case FDK_Defaulted:
8473  NewFD->setDefaulted();
8474  break;
8475 
8476  case FDK_Deleted:
8477  NewFD->setDeletedAsWritten();
8478  break;
8479  }
8480 
8481  if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8482  D.isFunctionDefinition()) {
8483  // C++ [class.mfct]p2:
8484  // A member function may be defined (8.4) in its class definition, in
8485  // which case it is an inline member function (7.1.2)
8486  NewFD->setImplicitlyInline();
8487  }
8488 
8489  if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8490  !CurContext->isRecord()) {
8491  // C++ [class.static]p1:
8492  // A data or function member of a class may be declared static
8493  // in a class definition, in which case it is a static member of
8494  // the class.
8495 
8496  // Complain about the 'static' specifier if it's on an out-of-line
8497  // member function definition.
8499  diag::err_static_out_of_line)
8501  }
8502 
8503  // C++11 [except.spec]p15:
8504  // A deallocation function with no exception-specification is treated
8505  // as if it were specified with noexcept(true).
8506  const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8507  if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8508  Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8509  getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8510  NewFD->setType(Context.getFunctionType(
8511  FPT->getReturnType(), FPT->getParamTypes(),
8512  FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8513  }
8514 
8515  // Filter out previous declarations that don't match the scope.
8516  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8517  D.getCXXScopeSpec().isNotEmpty() ||
8518  isMemberSpecialization ||
8519  isFunctionTemplateSpecialization);
8520 
8521  // Handle GNU asm-label extension (encoded as an attribute).
8522  if (Expr *E = (Expr*) D.getAsmLabel()) {
8523  // The parser guarantees this is a string.
8524  StringLiteral *SE = cast<StringLiteral>(E);
8525  NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8526  SE->getString(), 0));
8527  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8528  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8529  ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8530  if (I != ExtnameUndeclaredIdentifiers.end()) {
8531  if (isDeclExternC(NewFD)) {
8532  NewFD->addAttr(I->second);
8533  ExtnameUndeclaredIdentifiers.erase(I);
8534  } else
8535  Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8536  << /*Variable*/0 << NewFD;
8537  }
8538  }
8539 
8540  // Copy the parameter declarations from the declarator D to the function
8541  // declaration NewFD, if they are available. First scavenge them into Params.
8543  unsigned FTIIdx;
8544  if (D.isFunctionDeclarator(FTIIdx)) {
8546 
8547  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8548  // function that takes no arguments, not a function that takes a
8549  // single void argument.
8550  // We let through "const void" here because Sema::GetTypeForDeclarator
8551  // already checks for that case.
8552  if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8553  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8554  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8555  assert(Param->getDeclContext() != NewFD && "Was set before ?");
8556  Param->setDeclContext(NewFD);
8557  Params.push_back(Param);
8558 
8559  if (Param->isInvalidDecl())
8560  NewFD->setInvalidDecl();
8561  }
8562  }
8563 
8564  if (!getLangOpts().CPlusPlus) {
8565  // In C, find all the tag declarations from the prototype and move them
8566  // into the function DeclContext. Remove them from the surrounding tag
8567  // injection context of the function, which is typically but not always
8568  // the TU.
8569  DeclContext *PrototypeTagContext =
8571  for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8572  auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8573 
8574  // We don't want to reparent enumerators. Look at their parent enum
8575  // instead.
8576  if (!TD) {
8577  if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8578  TD = cast<EnumDecl>(ECD->getDeclContext());
8579  }
8580  if (!TD)
8581  continue;
8582  DeclContext *TagDC = TD->getLexicalDeclContext();
8583  if (!TagDC->containsDecl(TD))
8584  continue;
8585  TagDC->removeDecl(TD);
8586  TD->setDeclContext(NewFD);
8587  NewFD->addDecl(TD);
8588 
8589  // Preserve the lexical DeclContext if it is not the surrounding tag
8590  // injection context of the FD. In this example, the semantic context of
8591  // E will be f and the lexical context will be S, while both the
8592  // semantic and lexical contexts of S will be f:
8593  // void f(struct S { enum E { a } f; } s);
8594  if (TagDC != PrototypeTagContext)
8595  TD->setLexicalDeclContext(TagDC);
8596  }
8597  }
8598  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8599  // When we're declaring a function with a typedef, typeof, etc as in the
8600  // following example, we'll need to synthesize (unnamed)
8601  // parameters for use in the declaration.
8602  //
8603  // @code
8604  // typedef void fn(int);
8605  // fn f;
8606  // @endcode
8607 
8608  // Synthesize a parameter for each argument type.
8609  for (const auto &AI : FT->param_types()) {
8610  ParmVarDecl *Param =
8611  BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8612  Param->setScopeInfo(0, Params.size());
8613  Params.push_back(Param);
8614  }
8615  } else {
8616  assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8617  "Should not need args for typedef of non-prototype fn");
8618  }
8619 
8620  // Finally, we know we have the right number of parameters, install them.
8621  NewFD->setParams(Params);
8622 
8623  if (D.getDeclSpec().isNoreturnSpecified())
8624  NewFD->addAttr(
8625  ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8626  Context, 0));
8627 
8628  // Functions returning a variably modified type violate C99 6.7.5.2p2
8629  // because all functions have linkage.
8630  if (!NewFD->isInvalidDecl() &&
8631  NewFD->getReturnType()->isVariablyModifiedType()) {
8632  Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8633  NewFD->setInvalidDecl();
8634  }
8635 
8636  // Apply an implicit SectionAttr if '#pragma clang section text' is active
8637  if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8638  !NewFD->hasAttr<SectionAttr>()) {
8639  NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8640  PragmaClangTextSection.SectionName,
8641  PragmaClangTextSection.PragmaLocation));
8642  }
8643 
8644  // Apply an implicit SectionAttr if #pragma code_seg is active.
8645  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8646  !NewFD->hasAttr<SectionAttr>()) {
8647  NewFD->addAttr(
8648  SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8649  CodeSegStack.CurrentValue->getString(),
8650  CodeSegStack.CurrentPragmaLocation));
8651  if (UnifySection(CodeSegStack.CurrentValue->getString(),
8654  NewFD))
8655  NewFD->dropAttr<SectionAttr>();
8656  }
8657 
8658  // Handle attributes.
8659  ProcessDeclAttributes(S, NewFD, D);
8660 
8661  if (getLangOpts().OpenCL) {
8662  // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8663  // type declaration will generate a compilation error.
8664  LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8665  if (AddressSpace != LangAS::Default) {
8666  Diag(NewFD->getLocation(),
8667  diag::err_opencl_return_value_with_address_space);
8668  NewFD->setInvalidDecl();
8669  }
8670  }
8671 
8672  if (!getLangOpts().CPlusPlus) {
8673  // Perform semantic checking on the function declaration.
8674  if (!NewFD->isInvalidDecl() && NewFD->isMain())
8675  CheckMain(NewFD, D.getDeclSpec());
8676 
8677  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8678  CheckMSVCRTEntryPoint(NewFD);
8679 
8680  if (!NewFD->isInvalidDecl())
8681  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8682  isMemberSpecialization));
8683  else if (!Previous.empty())
8684  // Recover gracefully from an invalid redeclaration.
8685  D.setRedeclaration(true);
8686  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8688  "previous declaration set still overloaded");
8689 
8690  // Diagnose no-prototype function declarations with calling conventions that
8691  // don't support variadic calls. Only do this in C and do it after merging
8692  // possibly prototyped redeclarations.
8693  const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8694  if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8695  CallingConv CC = FT->getExtInfo().getCC();
8696  if (!supportsVariadicCall(CC)) {
8697  // Windows system headers sometimes accidentally use stdcall without
8698  // (void) parameters, so we relax this to a warning.
8699  int DiagID =
8700  CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8701  Diag(NewFD->getLocation(), DiagID)
8703  }
8704  }
8705  } else {
8706  // C++11 [replacement.functions]p3:
8707  // The program's definitions shall not be specified as inline.
8708  //
8709  // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8710  //
8711  // Suppress the diagnostic if the function is __attribute__((used)), since
8712  // that forces an external definition to be emitted.
8713  if (D.getDeclSpec().isInlineSpecified() &&
8715  !NewFD->hasAttr<UsedAttr>())
8717  diag::ext_operator_new_delete_declared_inline)
8718  << NewFD->getDeclName();
8719 
8720  // If the declarator is a template-id, translate the parser's template
8721  // argument list into our AST format.
8723  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8724  TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8725  TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8726  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8727  TemplateId->NumArgs);
8728  translateTemplateArguments(TemplateArgsPtr,
8729  TemplateArgs);
8730 
8731  HasExplicitTemplateArgs = true;
8732 
8733  if (NewFD->isInvalidDecl()) {
8734  HasExplicitTemplateArgs = false;
8735  } else if (FunctionTemplate) {
8736  // Function template with explicit template arguments.
8737  Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8738  << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8739 
8740  HasExplicitTemplateArgs = false;
8741  } else {
8742  assert((isFunctionTemplateSpecialization ||
8743  D.getDeclSpec().isFriendSpecified()) &&
8744  "should have a 'template<>' for this decl");
8745  // "friend void foo<>(int);" is an implicit specialization decl.
8746  isFunctionTemplateSpecialization = true;
8747  }
8748  } else if (isFriend && isFunctionTemplateSpecialization) {
8749  // This combination is only possible in a recovery case; the user
8750  // wrote something like:
8751  // template <> friend void foo(int);
8752  // which we're recovering from as if the user had written:
8753  // friend void foo<>(int);
8754  // Go ahead and fake up a template id.
8755  HasExplicitTemplateArgs = true;
8756  TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8757  TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8758  }
8759 
8760  // We do not add HD attributes to specializations here because
8761  // they may have different constexpr-ness compared to their
8762  // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8763  // may end up with different effective targets. Instead, a
8764  // specialization inherits its target attributes from its template
8765  // in the CheckFunctionTemplateSpecialization() call below.
8766  if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8767  maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8768 
8769  // If it's a friend (and only if it's a friend), it's possible
8770  // that either the specialized function type or the specialized
8771  // template is dependent, and therefore matching will fail. In
8772  // this case, don't check the specialization yet.
8773  bool InstantiationDependent = false;
8774  if (isFunctionTemplateSpecialization && isFriend &&
8775  (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8777  TemplateArgs,
8778  InstantiationDependent))) {
8779  assert(HasExplicitTemplateArgs &&
8780  "friend function specialization without template args");
8781  if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8782  Previous))
8783  NewFD->setInvalidDecl();
8784  } else if (isFunctionTemplateSpecialization) {
8785  if (CurContext->isDependentContext() && CurContext->isRecord()
8786  && !isFriend) {
8787  isDependentClassScopeExplicitSpecialization = true;
8788  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8789  diag::ext_function_specialization_in_class :
8790  diag::err_function_specialization_in_class)
8791  << NewFD->getDeclName();
8792  } else if (!NewFD->isInvalidDecl() &&
8793  CheckFunctionTemplateSpecialization(
8794  NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8795  Previous))
8796  NewFD->setInvalidDecl();
8797 
8798  // C++ [dcl.stc]p1:
8799  // A storage-class-specifier shall not be specified in an explicit
8800  // specialization (14.7.3)
8803  if (Info && SC != SC_None) {
8804  if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8805  Diag(NewFD->getLocation(),
8806  diag::err_explicit_specialization_inconsistent_storage_class)
8807  << SC
8810 
8811  else
8812  Diag(NewFD->getLocation(),
8813  diag::ext_explicit_specialization_storage_class)
8816  }
8817  } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8818  if (CheckMemberSpecialization(NewFD, Previous))
8819  NewFD->setInvalidDecl();
8820  }
8821 
8822  // Perform semantic checking on the function declaration.
8823  if (!isDependentClassScopeExplicitSpecialization) {
8824  if (!NewFD->isInvalidDecl() && NewFD->isMain())
8825  CheckMain(NewFD, D.getDeclSpec());
8826 
8827  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8828  CheckMSVCRTEntryPoint(NewFD);
8829 
8830  if (!NewFD->isInvalidDecl())
8831  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8832  isMemberSpecialization));
8833  else if (!Previous.empty())
8834  // Recover gracefully from an invalid redeclaration.
8835  D.setRedeclaration(true);
8836  }
8837 
8838  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8840  "previous declaration set still overloaded");
8841 
8842  NamedDecl *PrincipalDecl = (FunctionTemplate
8843  ? cast<NamedDecl>(FunctionTemplate)
8844  : NewFD);
8845 
8846  if (isFriend && NewFD->getPreviousDecl()) {
8847  AccessSpecifier Access = AS_public;
8848  if (!NewFD->isInvalidDecl())
8849  Access = NewFD->getPreviousDecl()->getAccess();
8850 
8851  NewFD->setAccess(Access);
8852  if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8853  }
8854 
8855  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8857  PrincipalDecl->setNonMemberOperator();
8858 
8859  // If we have a function template, check the template parameter
8860  // list. This will check and merge default template arguments.
8861  if (FunctionTemplate) {
8862  FunctionTemplateDecl *PrevTemplate =
8863  FunctionTemplate->getPreviousDecl();
8864  CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8865  PrevTemplate ? PrevTemplate->getTemplateParameters()
8866  : nullptr,
8868  ? (D.isFunctionDefinition()
8869  ? TPC_FriendFunctionTemplateDefinition
8870  : TPC_FriendFunctionTemplate)
8871  : (D.getCXXScopeSpec().isSet() &&
8872  DC && DC->isRecord() &&
8873  DC->isDependentContext())
8874  ? TPC_ClassTemplateMember
8875  : TPC_FunctionTemplate);
8876  }
8877 
8878  if (NewFD->isInvalidDecl()) {
8879  // Ignore all the rest of this.
8880  } else if (!D.isRedeclaration()) {
8881  struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8882  AddToScope };
8883  // Fake up an access specifier if it's supposed to be a class member.
8884  if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8885  NewFD->setAccess(AS_public);
8886 
8887  // Qualified decls generally require a previous declaration.
8888  if (D.getCXXScopeSpec().isSet()) {
8889  // ...with the major exception of templated-scope or
8890  // dependent-scope friend declarations.
8891 
8892  // TODO: we currently also suppress this check in dependent
8893  // contexts because (1) the parameter depth will be off when
8894  // matching friend templates and (2) we might actually be
8895  // selecting a friend based on a dependent factor. But there
8896  // are situations where these conditions don't apply and we
8897  // can actually do this check immediately.
8898  if (isFriend &&
8899  (TemplateParamLists.size() ||
8901  CurContext->isDependentContext())) {
8902  // ignore these
8903  } else {
8904  // The user tried to provide an out-of-line definition for a
8905  // function that is a member of a class or namespace, but there
8906  // was no such member function declared (C++ [class.mfct]p2,
8907  // C++ [namespace.memdef]p2). For example:
8908  //
8909  // class X {
8910  // void f() const;
8911  // };
8912  //
8913  // void X::f() { } // ill-formed
8914  //
8915  // Complain about this problem, and attempt to suggest close
8916  // matches (e.g., those that differ only in cv-qualifiers and
8917  // whether the parameter types are references).
8918 
8920  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8921  AddToScope = ExtraArgs.AddToScope;
8922  return Result;
8923  }
8924  }
8925 
8926  // Unqualified local friend declarations are required to resolve
8927  // to something.
8928  } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8930  *this, Previous, NewFD, ExtraArgs, true, S)) {
8931  AddToScope = ExtraArgs.AddToScope;
8932  return Result;
8933  }
8934  }
8935  } else if (!D.isFunctionDefinition() &&
8936  isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8937  !isFriend && !isFunctionTemplateSpecialization &&
8938  !isMemberSpecialization) {
8939  // An out-of-line member function declaration must also be a
8940  // definition (C++ [class.mfct]p2).
8941  // Note that this is not the case for explicit specializations of
8942  // function templates or member functions of class templates, per
8943  // C++ [temp.expl.spec]p2. We also allow these declarations as an
8944  // extension for compatibility with old SWIG code which likes to
8945  // generate them.
8946  Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8947  << D.getCXXScopeSpec().getRange();
8948  }
8949  }
8950 
8951  ProcessPragmaWeak(S, NewFD);
8952  checkAttributesAfterMerging(*this, *NewFD);
8953 
8954  AddKnownFunctionAttributes(NewFD);
8955 
8956  if (NewFD->hasAttr<OverloadableAttr>() &&
8957  !NewFD->getType()->getAs<FunctionProtoType>()) {
8958  Diag(NewFD->getLocation(),
8959  diag::err_attribute_overloadable_no_prototype)
8960  << NewFD;
8961 
8962  // Turn this into a variadic function with no parameters.
8963  const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8965  Context.getDefaultCallingConvention(true, false));
8966  EPI.Variadic = true;
8967  EPI.ExtInfo = FT->getExtInfo();
8968 
8969  QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8970  NewFD->setType(R);
8971  }
8972 
8973  // If there's a #pragma GCC visibility in scope, and this isn't a class
8974  // member, set the visibility of this function.
8975  if (!DC->isRecord() && NewFD->isExternallyVisible())
8976  AddPushedVisibilityAttribute(NewFD);
8977 
8978  // If there's a #pragma clang arc_cf_code_audited in scope, consider
8979  // marking the function.
8980  AddCFAuditedAttribute(NewFD);
8981 
8982  // If this is a function definition, check if we have to apply optnone due to
8983  // a pragma.
8984  if(D.isFunctionDefinition())
8985  AddRangeBasedOptnone(NewFD);
8986 
8987  // If this is the first declaration of an extern C variable, update
8988  // the map of such variables.
8989  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8990  isIncompleteDeclExternC(*this, NewFD))
8991  RegisterLocallyScopedExternCDecl(NewFD, S);
8992 
8993  // Set this FunctionDecl's range up to the right paren.
8994  NewFD->setRangeEnd(D.getSourceRange().getEnd());
8995 
8996  if (D.isRedeclaration() && !Previous.empty()) {
8998  *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8999  isMemberSpecialization || isFunctionTemplateSpecialization,
9000  D.isFunctionDefinition());
9001  }
9002 
9003  if (getLangOpts().CUDA) {
9004  IdentifierInfo *II = NewFD->getIdentifier();
9005  if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9007  if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9008  Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9009 
9010  Context.setcudaConfigureCallDecl(NewFD);
9011  }
9012 
9013  // Variadic functions, other than a *declaration* of printf, are not allowed
9014  // in device-side CUDA code, unless someone passed
9015  // -fcuda-allow-variadic-functions.
9016  if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9017  (NewFD->hasAttr<CUDADeviceAttr>() ||
9018  NewFD->hasAttr<CUDAGlobalAttr>()) &&
9019  !(II && II->isStr("printf") && NewFD->isExternC() &&
9020  !D.isFunctionDefinition())) {
9021  Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9022  }
9023  }
9024 
9025  MarkUnusedFileScopedDecl(NewFD);
9026 
9027  if (getLangOpts().CPlusPlus) {
9028  if (FunctionTemplate) {
9029  if (NewFD->isInvalidDecl())
9030  FunctionTemplate->setInvalidDecl();
9031  return FunctionTemplate;
9032  }
9033 
9034  if (isMemberSpecialization && !NewFD->isInvalidDecl())
9035  CompleteMemberSpecialization(NewFD, Previous);
9036  }
9037 
9038  if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9039  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9040  if ((getLangOpts().OpenCLVersion >= 120)
9041  && (SC == SC_Static)) {
9042  Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9043  D.setInvalidType();
9044  }
9045 
9046  // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9047  if (!NewFD->getReturnType()->isVoidType()) {
9048  SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9049  Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9050  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9051  : FixItHint());
9052  D.setInvalidType();
9053  }
9054 
9055  llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9056  for (auto Param : NewFD->parameters())
9057  checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9058  }
9059  for (const ParmVarDecl *Param : NewFD->parameters()) {
9060  QualType PT = Param->getType();
9061 
9062  // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9063  // types.
9064  if (getLangOpts().OpenCLVersion >= 200) {
9065  if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9066  QualType ElemTy = PipeTy->getElementType();
9067  if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9068  Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9069  D.setInvalidType();
9070  }
9071  }
9072  }
9073  }
9074 
9075  // Here we have an function template explicit specialization at class scope.
9076  // The actually specialization will be postponed to template instatiation
9077  // time via the ClassScopeFunctionSpecializationDecl node.
9078  if (isDependentClassScopeExplicitSpecialization) {
9081  Context, CurContext, SourceLocation(),
9082  cast<CXXMethodDecl>(NewFD),
9083  HasExplicitTemplateArgs, TemplateArgs);
9084  CurContext->addDecl(NewSpec);
9085  AddToScope = false;
9086  }
9087 
9088  return NewFD;
9089 }
9090 
9091 /// \brief Checks if the new declaration declared in dependent context must be
9092 /// put in the same redeclaration chain as the specified declaration.
9093 ///
9094 /// \param D Declaration that is checked.
9095 /// \param PrevDecl Previous declaration found with proper lookup method for the
9096 /// same declaration name.
9097 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9098 /// belongs to.
9099 ///
9101  // Any declarations should be put into redeclaration chains except for
9102  // friend declaration in a dependent context that names a function in
9103  // namespace scope.
9104  //
9105  // This allows to compile code like:
9106  //
9107  // void func();
9108  // template<typename T> class C1 { friend void func() { } };
9109  // template<typename T> class C2 { friend void func() { } };
9110  //
9111  // This code snippet is a valid code unless both templates are instantiated.
9112  return !(D->getLexicalDeclContext()->isDependentContext() &&
9113  D->getDeclContext()->isFileContext() &&
9115 }
9116 
9117 /// \brief Perform semantic checking of a new function declaration.
9118 ///
9119 /// Performs semantic analysis of the new function declaration
9120 /// NewFD. This routine performs all semantic checking that does not
9121 /// require the actual declarator involved in the declaration, and is
9122 /// used both for the declaration of functions as they are parsed
9123 /// (called via ActOnDeclarator) and for the declaration of functions
9124 /// that have been instantiated via C++ template instantiation (called
9125 /// via InstantiateDecl).
9126 ///
9127 /// \param IsMemberSpecialization whether this new function declaration is
9128 /// a member specialization (that replaces any definition provided by the
9129 /// previous declaration).
9130 ///
9131 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9132 ///
9133 /// \returns true if the function declaration is a redeclaration.
9136  bool IsMemberSpecialization) {
9137  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9138  "Variably modified return types are not handled here");
9139 
9140  // Determine whether the type of this function should be merged with
9141  // a previous visible declaration. This never happens for functions in C++,
9142  // and always happens in C if the previous declaration was visible.
9143  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9144  !Previous.isShadowed();
9145 
9146  bool Redeclaration = false;
9147  NamedDecl *OldDecl = nullptr;
9148  bool MayNeedOverloadableChecks = false;
9149 
9150  // Merge or overload the declaration with an existing declaration of
9151  // the same name, if appropriate.
9152  if (!Previous.empty()) {
9153  // Determine whether NewFD is an overload of PrevDecl or
9154  // a declaration that requires merging. If it's an overload,
9155  // there's no more work to do here; we'll just add the new
9156  // function to the scope.
9157  if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9158  NamedDecl *Candidate = Previous.getRepresentativeDecl();
9159  if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9160  Redeclaration = true;
9161  OldDecl = Candidate;
9162  }
9163  } else {
9164  MayNeedOverloadableChecks = true;
9165  switch (CheckOverload(S, NewFD, Previous, OldDecl,
9166  /*NewIsUsingDecl*/ false)) {
9167  case Ovl_Match:
9168  Redeclaration = true;
9169  break;
9170 
9171  case Ovl_NonFunction:
9172  Redeclaration = true;
9173  break;
9174 
9175  case Ovl_Overload:
9176  Redeclaration = false;
9177  break;
9178  }
9179  }
9180  }
9181 
9182  // Check for a previous extern "C" declaration with this name.
9183  if (!Redeclaration &&
9184  checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9185  if (!Previous.empty()) {
9186  // This is an extern "C" declaration with the same name as a previous
9187  // declaration, and thus redeclares that entity...
9188  Redeclaration = true;
9189  OldDecl = Previous.getFoundDecl();
9190  MergeTypeWithPrevious = false;
9191 
9192  // ... except in the presence of __attribute__((overloadable)).
9193  if (OldDecl->hasAttr<OverloadableAttr>() ||
9194  NewFD->hasAttr<OverloadableAttr>()) {
9195  if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9196  MayNeedOverloadableChecks = true;
9197  Redeclaration = false;
9198  OldDecl = nullptr;
9199  }
9200  }
9201  }
9202  }
9203 
9204  // C++11 [dcl.constexpr]p8:
9205  // A constexpr specifier for a non-static member function that is not
9206  // a constructor declares that member function to be const.
9207  //
9208  // This needs to be delayed until we know whether this is an out-of-line
9209  // definition of a static member function.
9210  //
9211  // This rule is not present in C++1y, so we produce a backwards
9212  // compatibility warning whenever it happens in C++11.
9213  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9214  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9215  !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9216  (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9217  CXXMethodDecl *OldMD = nullptr;
9218  if (OldDecl)
9219  OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9220  if (!OldMD || !OldMD->isStatic()) {
9221  const FunctionProtoType *FPT =
9222  MD->getType()->castAs<FunctionProtoType>();
9225  MD->setType(Context.getFunctionType(FPT->getReturnType(),
9226  FPT->getParamTypes(), EPI));
9227 
9228  // Warn that we did this, if we're not performing template instantiation.
9229  // In that case, we'll have warned already when the template was defined.
9230  if (!inTemplateInstantiation()) {
9231  SourceLocation AddConstLoc;
9232  if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9234  AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9235 
9236  Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9237  << FixItHint::CreateInsertion(AddConstLoc, " const");
9238  }
9239  }
9240  }
9241 
9242  if (Redeclaration) {
9243  // NewFD and OldDecl represent declarations that need to be
9244  // merged.
9245  if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9246  NewFD->setInvalidDecl();
9247  return Redeclaration;
9248  }
9249 
9250  Previous.clear();
9251  Previous.addDecl(OldDecl);
9252 
9253  if (FunctionTemplateDecl *OldTemplateDecl
9254  = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9255  NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9256  FunctionTemplateDecl *NewTemplateDecl
9257  = NewFD->getDescribedFunctionTemplate();
9258  assert(NewTemplateDecl && "Template/non-template mismatch");
9259  if (CXXMethodDecl *Method
9260  = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9261  Method->setAccess(OldTemplateDecl->getAccess());
9262  NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9263  }
9264 
9265  // If this is an explicit specialization of a member that is a function
9266  // template, mark it as a member specialization.
9267  if (IsMemberSpecialization &&
9268  NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9269  NewTemplateDecl->setMemberSpecialization();
9270  assert(OldTemplateDecl->isMemberSpecialization());
9271  // Explicit specializations of a member template do not inherit deleted
9272  // status from the parent member template that they are specializing.
9273  if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9274  FunctionDecl *const OldTemplatedDecl =
9275  OldTemplateDecl->getTemplatedDecl();
9276  // FIXME: This assert will not hold in the presence of modules.
9277  assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9278  // FIXME: We need an update record for this AST mutation.
9279  OldTemplatedDecl->setDeletedAsWritten(false);
9280  }
9281  }
9282 
9283  } else {
9284  if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9285  // This needs to happen first so that 'inline' propagates.
9286  NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9287  if (isa<CXXMethodDecl>(NewFD))
9288  NewFD->setAccess(OldDecl->getAccess());
9289  }
9290  }
9291  } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9292  !NewFD->getAttr<OverloadableAttr>()) {
9293  assert((Previous.empty() ||
9294  llvm::any_of(Previous,
9295  [](const NamedDecl *ND) {
9296  return ND->hasAttr<OverloadableAttr>();
9297  })) &&
9298  "Non-redecls shouldn't happen without overloadable present");
9299 
9300  auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9301  const auto *FD = dyn_cast<FunctionDecl>(ND);
9302  return FD && !FD->hasAttr<OverloadableAttr>();
9303  });
9304 
9305  if (OtherUnmarkedIter != Previous.end()) {
9306  Diag(NewFD->getLocation(),
9307  diag::err_attribute_overloadable_multiple_unmarked_overloads);
9308  Diag((*OtherUnmarkedIter)->getLocation(),
9309  diag::note_attribute_overloadable_prev_overload)
9310  << false;
9311 
9312  NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9313  }
9314  }
9315 
9316  // Semantic checking for this function declaration (in isolation).
9317 
9318  if (getLangOpts().CPlusPlus) {
9319  // C++-specific checks.
9320  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9321  CheckConstructor(Constructor);
9322  } else if (CXXDestructorDecl *Destructor =
9323  dyn_cast<CXXDestructorDecl>(NewFD)) {
9324  CXXRecordDecl *Record = Destructor->getParent();
9325  QualType ClassType = Context.getTypeDeclType(Record);
9326 
9327  // FIXME: Shouldn't we be able to perform this check even when the class
9328  // type is dependent? Both gcc and edg can handle that.
9329  if (!ClassType->isDependentType()) {
9330  DeclarationName Name
9332  Context.getCanonicalType(ClassType));
9333  if (NewFD->getDeclName() != Name) {
9334  Diag(NewFD->getLocation(), diag::err_destructor_name);
9335  NewFD->setInvalidDecl();
9336  return Redeclaration;
9337  }
9338  }
9339  } else if (CXXConversionDecl *Conversion
9340  = dyn_cast<CXXConversionDecl>(NewFD)) {
9341  ActOnConversionDeclarator(Conversion);
9342  } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9343  if (auto *TD = Guide->getDescribedFunctionTemplate())
9344  CheckDeductionGuideTemplate(TD);
9345 
9346  // A deduction guide is not on the list of entities that can be
9347  // explicitly specialized.
9348  if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9349  Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9350  << /*explicit specialization*/ 1;
9351  }
9352 
9353  // Find any virtual functions that this function overrides.
9354  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9355  if (!Method->isFunctionTemplateSpecialization() &&
9356  !Method->getDescribedFunctionTemplate() &&
9357  Method->isCanonicalDecl()) {
9358  if (AddOverriddenMethods(Method->getParent(), Method)) {
9359  // If the function was marked as "static", we have a problem.
9360  if (NewFD->getStorageClass() == SC_Static) {
9361  ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9362  }
9363  }
9364  }
9365 
9366  if (Method->isStatic())
9367  checkThisInStaticMemberFunctionType(Method);
9368  }
9369 
9370  // Extra checking for C++ overloaded operators (C++ [over.oper]).
9371  if (NewFD->isOverloadedOperator() &&
9372  CheckOverloadedOperatorDeclaration(NewFD)) {
9373  NewFD->setInvalidDecl();
9374  return Redeclaration;
9375  }
9376 
9377  // Extra checking for C++0x literal operators (C++0x [over.literal]).
9378  if (NewFD->getLiteralIdentifier() &&
9379  CheckLiteralOperatorDeclaration(NewFD)) {
9380  NewFD->setInvalidDecl();
9381  return Redeclaration;
9382  }
9383 
9384  // In C++, check default arguments now that we have merged decls. Unless
9385  // the lexical context is the class, because in this case this is done
9386  // during delayed parsing anyway.
9387  if (!CurContext->isRecord())
9388  CheckCXXDefaultArguments(NewFD);
9389 
9390  // If this function declares a builtin function, check the type of this
9391  // declaration against the expected type for the builtin.
9392  if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9394  LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9395  QualType T = Context.GetBuiltinType(BuiltinID, Error);
9396  // If the type of the builtin differs only in its exception
9397  // specification, that's OK.
9398  // FIXME: If the types do differ in this way, it would be better to
9399  // retain the 'noexcept' form of the type.
9400  if (!T.isNull() &&
9402  NewFD->getType()))
9403  // The type of this function differs from the type of the builtin,
9404  // so forget about the builtin entirely.
9405  Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9406  }
9407 
9408  // If this function is declared as being extern "C", then check to see if
9409  // the function returns a UDT (class, struct, or union type) that is not C
9410  // compatible, and if it does, warn the user.
9411  // But, issue any diagnostic on the first declaration only.
9412  if (Previous.empty() && NewFD->isExternC()) {
9413  QualType R = NewFD->getReturnType();
9414  if (R->isIncompleteType() && !R->isVoidType())
9415  Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9416  << NewFD << R;
9417  else if (!R.isPODType(Context) && !R->isVoidType() &&
9419  Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9420  }
9421 
9422  // C++1z [dcl.fct]p6:
9423  // [...] whether the function has a non-throwing exception-specification
9424  // [is] part of the function type
9425  //
9426  // This results in an ABI break between C++14 and C++17 for functions whose
9427  // declared type includes an exception-specification in a parameter or
9428  // return type. (Exception specifications on the function itself are OK in
9429  // most cases, and exception specifications are not permitted in most other
9430  // contexts where they could make it into a mangling.)
9431  if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
9432  auto HasNoexcept = [&](QualType T) -> bool {
9433  // Strip off declarator chunks that could be between us and a function
9434  // type. We don't need to look far, exception specifications are very
9435  // restricted prior to C++17.
9436  if (auto *RT = T->getAs<ReferenceType>())
9437  T = RT->getPointeeType();
9438  else if (T->isAnyPointerType())
9439  T = T->getPointeeType();
9440  else if (auto *MPT = T->getAs<MemberPointerType>())
9441  T = MPT->getPointeeType();
9442  if (auto *FPT = T->getAs<FunctionProtoType>())
9443  if (FPT->isNothrow(Context))
9444  return true;
9445  return false;
9446  };
9447 
9448  auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9449  bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9450  for (QualType T : FPT->param_types())
9451  AnyNoexcept |= HasNoexcept(T);
9452  if (AnyNoexcept)
9453  Diag(NewFD->getLocation(),
9454  diag::warn_cxx17_compat_exception_spec_in_signature)
9455  << NewFD;
9456  }
9457 
9458  if (!Redeclaration && LangOpts.CUDA)
9459  checkCUDATargetOverload(NewFD, Previous);
9460  }
9461  return Redeclaration;
9462 }
9463 
9464 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9465  // C++11 [basic.start.main]p3:
9466  // A program that [...] declares main to be inline, static or
9467  // constexpr is ill-formed.
9468  // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
9469  // appear in a declaration of main.
9470  // static main is not an error under C99, but we should warn about it.
9471  // We accept _Noreturn main as an extension.
9472  if (FD->getStorageClass() == SC_Static)
9473  Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9474  ? diag::err_static_main : diag::warn_static_main)
9476  if (FD->isInlineSpecified())
9477  Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9479  if (DS.isNoreturnSpecified()) {
9480  SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9481  SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9482  Diag(NoreturnLoc, diag::ext_noreturn_main);
9483  Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9484  << FixItHint::CreateRemoval(NoreturnRange);
9485  }
9486  if (FD->isConstexpr()) {
9487  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9489  FD->setConstexpr(false);
9490  }
9491 
9492  if (getLangOpts().OpenCL) {
9493  Diag(FD->getLocation(), diag::err_opencl_no_main)
9494  << FD->hasAttr<OpenCLKernelAttr>();
9495  FD->setInvalidDecl();
9496  return;
9497  }
9498 
9499  QualType T = FD->getType();
9500  assert(T->isFunctionType() && "function decl is not of function type");
9501  const FunctionType* FT = T->castAs<FunctionType>();
9502 
9503  // Set default calling convention for main()
9504  if (FT->getCallConv() != CC_C) {
9505  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
9506  FD->setType(QualType(FT, 0));
9507  T = Context.getCanonicalType(FD->getType());
9508  }
9509 
9510  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9511  // In C with GNU extensions we allow main() to have non-integer return
9512  // type, but we should warn about the extension, and we disable the
9513  // implicit-return-zero rule.
9514 
9515  // GCC in C mode accepts qualified 'int'.
9516  if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9517  FD->setHasImplicitReturnZero(true);
9518  else {
9519  Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9520  SourceRange RTRange = FD->getReturnTypeSourceRange();
9521  if (RTRange.isValid())
9522  Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9523  << FixItHint::CreateReplacement(RTRange, "int");
9524  }
9525  } else {
9526  // In C and C++, main magically returns 0 if you fall off the end;
9527  // set the flag which tells us that.
9528  // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9529 
9530  // All the standards say that main() should return 'int'.
9531  if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9532  FD->setHasImplicitReturnZero(true);
9533  else {
9534  // Otherwise, this is just a flat-out error.
9535  SourceRange RTRange = FD->getReturnTypeSourceRange();
9536  Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9537  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9538  : FixItHint());
9539  FD->setInvalidDecl(true);
9540  }
9541  }
9542 
9543  // Treat protoless main() as nullary.
9544  if (isa<FunctionNoProtoType>(FT)) return;
9545 
9546  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9547  unsigned nparams = FTP->getNumParams();
9548  assert(FD->getNumParams() == nparams);
9549 
9550  bool HasExtraParameters = (nparams > 3);
9551 
9552  if (FTP->isVariadic()) {
9553  Diag(FD->getLocation(), diag::ext_variadic_main);
9554  // FIXME: if we had information about the location of the ellipsis, we
9555  // could add a FixIt hint to remove it as a parameter.
9556  }
9557 
9558  // Darwin passes an undocumented fourth argument of type char**. If
9559  // other platforms start sprouting these, the logic below will start
9560  // getting shifty.
9561  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9562  HasExtraParameters = false;
9563 
9564  if (HasExtraParameters) {
9565  Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9566  FD->setInvalidDecl(true);
9567  nparams = 3;
9568  }
9569 
9570  // FIXME: a lot of the following diagnostics would be improved
9571  // if we had some location information about types.
9572 
9573  QualType CharPP =
9574  Context.getPointerType(Context.getPointerType(Context.CharTy));
9575  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9576 
9577  for (unsigned i = 0; i < nparams; ++i) {
9578  QualType AT = FTP->getParamType(i);
9579 
9580  bool mismatch = true;
9581 
9582  if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9583  mismatch = false;
9584  else if (Expected[i] == CharPP) {
9585  // As an extension, the following forms are okay:
9586  // char const **
9587  // char const * const *
9588  // char * const *
9589 
9590  QualifierCollector qs;
9591  const PointerType* PT;
9592  if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9593  (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9594  Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9595  Context.CharTy)) {
9596  qs.removeConst();
9597  mismatch = !qs.empty();
9598  }
9599  }
9600 
9601  if (mismatch) {
9602  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9603  // TODO: suggest replacing given type with expected type
9604  FD->setInvalidDecl(true);
9605  }
9606  }
9607 
9608  if (nparams == 1 && !FD->isInvalidDecl()) {
9609  Diag(FD->getLocation(), diag::warn_main_one_arg);
9610  }
9611 
9612  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9613  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9614  FD->setInvalidDecl();
9615  }
9616 }
9617 
9619  QualType T = FD->getType();
9620  assert(T->isFunctionType() && "function decl is not of function type");
9621  const FunctionType *FT = T->castAs<FunctionType>();
9622 
9623  // Set an implicit return of 'zero' if the function can return some integral,
9624  // enumeration, pointer or nullptr type.
9625  if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9626  FT->getReturnType()->isAnyPointerType() ||
9627  FT->getReturnType()->isNullPtrType())
9628  // DllMain is exempt because a return value of zero means it failed.
9629  if (FD->getName() != "DllMain")
9630  FD->setHasImplicitReturnZero(true);
9631 
9632  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9633  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9634  FD->setInvalidDecl();
9635  }
9636 }
9637 
9639  // FIXME: Need strict checking. In C89, we need to check for
9640  // any assignment, increment, decrement, function-calls, or
9641  // commas outside of a sizeof. In C99, it's the same list,
9642  // except that the aforementioned are allowed in unevaluated
9643  // expressions. Everything else falls under the
9644  // "may accept other forms of constant expressions" exception.
9645  // (We never end up here for C++, so the constant expression
9646  // rules there don't matter.)
9647  const Expr *Culprit;
9648  if (Init->isConstantInitializer(Context, false, &Culprit))
9649  return false;
9650  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9651  << Culprit->getSourceRange();
9652  return true;
9653 }
9654 
9655 namespace {
9656  // Visits an initialization expression to see if OrigDecl is evaluated in
9657  // its own initialization and throws a warning if it does.
9658  class SelfReferenceChecker
9659  : public EvaluatedExprVisitor<SelfReferenceChecker> {
9660  Sema &S;
9661  Decl *OrigDecl;
9662  bool isRecordType;
9663  bool isPODType;
9664  bool isReferenceType;
9665 
9666  bool isInitList;
9667  llvm::SmallVector<unsigned, 4> InitFieldIndex;
9668 
9669  public:
9671 
9672  SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9673  S(S), OrigDecl(OrigDecl) {
9674  isPODType = false;
9675  isRecordType = false;
9676  isReferenceType = false;
9677  isInitList = false;
9678  if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9679  isPODType = VD->getType().isPODType(S.Context);
9680  isRecordType = VD->getType()->isRecordType();
9681  isReferenceType = VD->getType()->isReferenceType();
9682  }
9683  }
9684 
9685  // For most expressions, just call the visitor. For initializer lists,
9686  // track the index of the field being initialized since fields are
9687  // initialized in order allowing use of previously initialized fields.
9688  void CheckExpr(Expr *E) {
9689  InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9690  if (!InitList) {
9691  Visit(E);
9692  return;
9693  }
9694 
9695  // Track and increment the index here.
9696  isInitList = true;
9697  InitFieldIndex.push_back(0);
9698  for (auto Child : InitList->children()) {
9699  CheckExpr(cast<Expr>(Child));
9700  ++InitFieldIndex.back();
9701  }
9702  InitFieldIndex.pop_back();
9703  }
9704 
9705  // Returns true if MemberExpr is checked and no further checking is needed.
9706  // Returns false if additional checking is required.
9707  bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9709  Expr *Base = E;
9710  bool ReferenceField = false;
9711 
9712  // Get the field memebers used.
9713  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9714  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9715  if (!FD)
9716  return false;
9717  Fields.push_back(FD);
9718  if (FD->getType()->isReferenceType())
9719  ReferenceField = true;
9720  Base = ME->getBase()->IgnoreParenImpCasts();
9721  }
9722 
9723  // Keep checking only if the base Decl is the same.
9724  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9725  if (!DRE || DRE->getDecl() != OrigDecl)
9726  return false;
9727 
9728  // A reference field can be bound to an unininitialized field.
9729  if (CheckReference && !ReferenceField)
9730  return true;
9731 
9732  // Convert FieldDecls to their index number.
9733  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9734  for (const FieldDecl *I : llvm::reverse(Fields))
9735  UsedFieldIndex.push_back(I->getFieldIndex());
9736 
9737  // See if a warning is needed by checking the first difference in index
9738  // numbers. If field being used has index less than the field being
9739  // initialized, then the use is safe.
9740  for (auto UsedIter = UsedFieldIndex.begin(),
9741  UsedEnd = UsedFieldIndex.end(),
9742  OrigIter = InitFieldIndex.begin(),
9743  OrigEnd = InitFieldIndex.end();
9744  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9745  if (*UsedIter < *OrigIter)
9746  return true;
9747  if (*UsedIter > *OrigIter)
9748  break;
9749  }
9750 
9751  // TODO: Add a different warning which will print the field names.
9752  HandleDeclRefExpr(DRE);
9753  return true;
9754  }
9755 
9756  // For most expressions, the cast is directly above the DeclRefExpr.
9757  // For conditional operators, the cast can be outside the conditional
9758  // operator if both expressions are DeclRefExpr's.
9759  void HandleValue(Expr *E) {
9760  E = E->IgnoreParens();
9761  if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9762  HandleDeclRefExpr(DRE);
9763  return;
9764  }
9765 
9766  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9767  Visit(CO->getCond());
9768  HandleValue(CO->getTrueExpr());
9769  HandleValue(CO->getFalseExpr());
9770  return;
9771  }
9772 
9773  if (BinaryConditionalOperator *BCO =
9774  dyn_cast<BinaryConditionalOperator>(E)) {
9775  Visit(BCO->getCond());
9776  HandleValue(BCO->getFalseExpr());
9777  return;
9778  }
9779 
9780  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9781  HandleValue(OVE->getSourceExpr());
9782  return;
9783  }
9784 
9785  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9786  if (BO->getOpcode() == BO_Comma) {
9787  Visit(BO->getLHS());
9788  HandleValue(BO->getRHS());
9789  return;
9790  }
9791  }
9792 
9793  if (isa<MemberExpr>(E)) {
9794  if (isInitList) {
9795  if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9796  false /*CheckReference*/))
9797  return;
9798  }
9799 
9800  Expr *Base = E->IgnoreParenImpCasts();
9801  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9802  // Check for static member variables and don't warn on them.
9803  if (!isa<FieldDecl>(ME->getMemberDecl()))
9804  return;
9805  Base = ME->getBase()->IgnoreParenImpCasts();
9806  }
9807  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9808  HandleDeclRefExpr(DRE);
9809  return;
9810  }
9811 
9812  Visit(E);
9813  }
9814 
9815  // Reference types not handled in HandleValue are handled here since all
9816  // uses of references are bad, not just r-value uses.
9817  void VisitDeclRefExpr(DeclRefExpr *E) {
9818  if (isReferenceType)
9819  HandleDeclRefExpr(E);
9820  }
9821 
9822  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9823  if (E->getCastKind() == CK_LValueToRValue) {
9824  HandleValue(E->getSubExpr());
9825  return;
9826  }
9827 
9828  Inherited::VisitImplicitCastExpr(E);
9829  }
9830 
9831  void VisitMemberExpr(MemberExpr *E) {
9832  if (isInitList) {
9833  if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9834  return;
9835  }
9836 
9837  // Don't warn on arrays since they can be treated as pointers.
9838  if (E->getType()->canDecayToPointerType()) return;
9839 
9840  // Warn when a non-static method call is followed by non-static member
9841  // field accesses, which is followed by a DeclRefExpr.
9842  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9843  bool Warn = (MD && !MD->isStatic());
9844  Expr *Base = E->getBase()->IgnoreParenImpCasts();
9845  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9846  if (!isa<FieldDecl>(ME->getMemberDecl()))
9847  Warn = false;
9848  Base = ME->getBase()->IgnoreParenImpCasts();
9849  }
9850 
9851  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9852  if (Warn)
9853  HandleDeclRefExpr(DRE);
9854  return;
9855  }
9856 
9857  // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9858  // Visit that expression.
9859  Visit(Base);
9860  }
9861 
9862  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9863  Expr *Callee = E->getCallee();
9864 
9865  if (isa<UnresolvedLookupExpr>(Callee))
9866  return Inherited::VisitCXXOperatorCallExpr(E);
9867 
9868  Visit(Callee);
9869  for (auto Arg: E->arguments())
9870  HandleValue(Arg->IgnoreParenImpCasts());
9871  }
9872 
9873  void VisitUnaryOperator(UnaryOperator *E) {
9874  // For POD record types, addresses of its own members are well-defined.
9875  if (E->getOpcode() == UO_AddrOf && isRecordType &&
9876  isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9877  if (!isPODType)
9878  HandleValue(E->getSubExpr());
9879  return;
9880  }
9881 
9882  if (E->isIncrementDecrementOp()) {
9883  HandleValue(E->getSubExpr());
9884  return;
9885  }
9886 
9887  Inherited::VisitUnaryOperator(E);
9888  }
9889 
9890  void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9891 
9892  void VisitCXXConstructExpr(CXXConstructExpr *E) {
9893  if (E->getConstructor()->isCopyConstructor()) {
9894  Expr *ArgExpr = E->getArg(0);
9895  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9896  if (ILE->getNumInits() == 1)
9897  ArgExpr = ILE->getInit(0);
9898  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9899  if (ICE->getCastKind() == CK_NoOp)
9900  ArgExpr = ICE->getSubExpr();
9901  HandleValue(ArgExpr);
9902  return;
9903  }
9904  Inherited::VisitCXXConstructExpr(E);
9905  }
9906 
9907  void VisitCallExpr(CallExpr *E) {
9908  // Treat std::move as a use.
9909  if (E->isCallToStdMove()) {
9910  HandleValue(E->getArg(0));
9911  return;
9912  }
9913 
9914  Inherited::VisitCallExpr(E);
9915  }
9916 
9917  void VisitBinaryOperator(BinaryOperator *E) {
9918  if (E->isCompoundAssignmentOp()) {
9919  HandleValue(E->getLHS());
9920  Visit(E->getRHS());
9921  return;
9922  }
9923 
9924  Inherited::VisitBinaryOperator(E);
9925  }
9926 
9927  // A custom visitor for BinaryConditionalOperator is needed because the
9928  // regular visitor would check the condition and true expression separately
9929  // but both point to the same place giving duplicate diagnostics.
9930  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9931  Visit(E->getCond());
9932  Visit(E->getFalseExpr());
9933  }
9934 
9935  void HandleDeclRefExpr(DeclRefExpr *DRE) {
9936  Decl* ReferenceDecl = DRE->getDecl();
9937  if (OrigDecl != ReferenceDecl) return;
9938  unsigned diag;
9939  if (isReferenceType) {
9940  diag = diag::warn_uninit_self_reference_in_reference_init;
9941  } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9942  diag = diag::warn_static_self_reference_in_init;
9943  } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9944  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9945  DRE->getDecl()->getType()->isRecordType()) {
9946  diag = diag::warn_uninit_self_reference_in_init;
9947  } else {
9948  // Local variables will be handled by the CFG analysis.
9949  return;
9950  }
9951 
9952  S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9953  S.PDiag(diag)
9954  << DRE->getNameInfo().getName()
9955  << OrigDecl->getLocation()
9956  << DRE->getSourceRange());
9957  }
9958  };
9959 
9960  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9961  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9962  bool DirectInit) {
9963  // Parameters arguments are occassionially constructed with itself,
9964  // for instance, in recursive functions. Skip them.
9965  if (isa<ParmVarDecl>(OrigDecl))
9966  return;
9967 
9968  E = E->IgnoreParens();
9969 
9970  // Skip checking T a = a where T is not a record or reference type.
9971  // Doing so is a way to silence uninitialized warnings.
9972  if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9973  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9974  if (ICE->getCastKind() == CK_LValueToRValue)
9975  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9976  if (DRE->getDecl() == OrigDecl)
9977  return;
9978 
9979  SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9980  }
9981 } // end anonymous namespace
9982 
9983 namespace {
9984  // Simple wrapper to add the name of a variable or (if no variable is
9985  // available) a DeclarationName into a diagnostic.
9986  struct VarDeclOrName {
9987  VarDecl *VDecl;
9988  DeclarationName Name;
9989 
9990  friend const Sema::SemaDiagnosticBuilder &
9991  operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9992  return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9993  }
9994  };
9995 } // end anonymous namespace
9996 
9999  TypeSourceInfo *TSI,
10000  SourceRange Range, bool DirectInit,
10001  Expr *Init) {
10002  bool IsInitCapture = !VDecl;
10003  assert((!VDecl || !VDecl->isInitCapture()) &&
10004  "init captures are expected to be deduced prior to initialization");
10005 
10006  VarDeclOrName VN{VDecl, Name};
10007 
10008  DeducedType *Deduced = Type->getContainedDeducedType();
10009  assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10010 
10011  // C++11 [dcl.spec.auto]p3
10012  if (!Init) {
10013  assert(VDecl && "no init for init capture deduction?");
10014  Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10015  << VDecl->getDeclName() << Type;
10016  return QualType();
10017  }
10018 
10019  ArrayRef<Expr*> DeduceInits = Init;
10020  if (DirectInit) {
10021  if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10022  DeduceInits = PL->exprs();
10023  }
10024 
10025  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10026  assert(VDecl && "non-auto type for init capture deduction?");
10029  VDecl->getLocation(), DirectInit, Init);
10030  // FIXME: Initialization should not be taking a mutable list of inits.
10031  SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10032  return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10033  InitsCopy);
10034  }
10035 
10036  if (DirectInit) {
10037  if (auto *IL = dyn_cast<InitListExpr>(Init))
10038  DeduceInits = IL->inits();
10039  }
10040 
10041  // Deduction only works if we have exactly one source expression.
10042  if (DeduceInits.empty()) {
10043  // It isn't possible to write this directly, but it is possible to
10044  // end up in this situation with "auto x(some_pack...);"
10045  Diag(Init->getLocStart(), IsInitCapture
10046  ? diag::err_init_capture_no_expression
10047  : diag::err_auto_var_init_no_expression)
10048  << VN << Type << Range;
10049  return QualType();
10050  }
10051 
10052  if (DeduceInits.size() > 1) {
10053  Diag(DeduceInits[1]->getLocStart(),
10054  IsInitCapture ? diag::err_init_capture_multiple_expressions
10055  : diag::err_auto_var_init_multiple_expressions)
10056  << VN << Type << Range;
10057  return QualType();
10058  }
10059 
10060  Expr *DeduceInit = DeduceInits[0];
10061  if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10062  Diag(Init->getLocStart(), IsInitCapture
10063  ? diag::err_init_capture_paren_braces
10064  : diag::err_auto_var_init_paren_braces)
10065  << isa<InitListExpr>(Init) << VN << Type << Range;
10066  return QualType();
10067  }
10068 
10069  // Expressions default to 'id' when we're in a debugger.
10070  bool DefaultedAnyToId = false;
10071  if (getLangOpts().DebuggerCastResultToId &&
10072  Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10073  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10074  if (Result.isInvalid()) {
10075  return QualType();
10076  }
10077  Init = Result.get();
10078  DefaultedAnyToId = true;
10079  }
10080 
10081  // C++ [dcl.decomp]p1:
10082  // If the assignment-expression [...] has array type A and no ref-qualifier
10083  // is present, e has type cv A
10084  if (VDecl && isa<DecompositionDecl>(VDecl) &&
10085  Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10086  DeduceInit->getType()->isConstantArrayType())
10087  return Context.getQualifiedType(DeduceInit->getType(),
10088  Type.getQualifiers());
10089 
10091  if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10092  if (!IsInitCapture)
10093  DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10094  else if (isa<InitListExpr>(Init))
10095  Diag(Range.getBegin(),
10096  diag::err_init_capture_deduction_failure_from_init_list)
10097  << VN
10098  << (DeduceInit->getType().isNull() ? TSI->getType()
10099  : DeduceInit->getType())
10100  << DeduceInit->getSourceRange();
10101  else
10102  Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10103  << VN << TSI->getType()
10104  << (DeduceInit->getType().isNull() ? TSI->getType()
10105  : DeduceInit->getType())
10106  << DeduceInit->getSourceRange();
10107  }
10108 
10109  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10110  // 'id' instead of a specific object type prevents most of our usual
10111  // checks.
10112  // We only want to warn outside of template instantiations, though:
10113  // inside a template, the 'id' could have come from a parameter.
10114  if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10115  !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10116  SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10117  Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10118  }
10119 
10120  return DeducedType;
10121 }
10122 
10123 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10124  Expr *Init) {
10125  QualType DeducedType = deduceVarTypeFromInitializer(
10126  VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10127  VDecl->getSourceRange(), DirectInit, Init);
10128  if (DeducedType.isNull()) {
10129  VDecl->setInvalidDecl();
10130  return true;
10131  }
10132 
10133  VDecl->setType(DeducedType);
10134  assert(VDecl->isLinkageValid());
10135 
10136  // In ARC, infer lifetime.
10137  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10138  VDecl->setInvalidDecl();
10139 
10140  // If this is a redeclaration, check that the type we just deduced matches
10141  // the previously declared type.
10142  if (VarDecl *Old = VDecl->getPreviousDecl()) {
10143  // We never need to merge the type, because we cannot form an incomplete
10144  // array of auto, nor deduce such a type.
10145  MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10146  }
10147 
10148  // Check the deduced type is valid for a variable declaration.
10149  CheckVariableDeclarationType(VDecl);
10150  return VDecl->isInvalidDecl();
10151 }
10152 
10153 /// AddInitializerToDecl - Adds the initializer Init to the
10154 /// declaration dcl. If DirectInit is true, this is C++ direct
10155 /// initialization rather than copy initialization.
10156 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10157  // If there is no declaration, there was an error parsing it. Just ignore
10158  // the initializer.
10159  if (!RealDecl || RealDecl->isInvalidDecl()) {
10160  CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10161  return;
10162  }
10163 
10164  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10165  // Pure-specifiers are handled in ActOnPureSpecifier.
10166  Diag(Method->getLocation(), diag::err_member_function_initialization)
10167  << Method->getDeclName() << Init->getSourceRange();
10168  Method->setInvalidDecl();
10169  return;
10170  }
10171 
10172  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10173  if (!VDecl) {
10174  assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10175  Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10176  RealDecl->setInvalidDecl();
10177  return;
10178  }
10179 
10180  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10181  if (VDecl->getType()->isUndeducedType()) {
10182  // Attempt typo correction early so that the type of the init expression can
10183  // be deduced based on the chosen correction if the original init contains a
10184  // TypoExpr.
10185  ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10186  if (!Res.isUsable()) {
10187  RealDecl->setInvalidDecl();
10188  return;
10189  }
10190  Init = Res.get();
10191 
10192  if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10193  return;
10194  }
10195 
10196  // dllimport cannot be used on variable definitions.
10197  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10198  Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10199  VDecl->setInvalidDecl();
10200  return;
10201  }
10202 
10203  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10204  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10205  Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10206  VDecl->setInvalidDecl();
10207  return;
10208  }
10209 
10210  if (!VDecl->getType()->isDependentType()) {
10211  // A definition must end up with a complete type, which means it must be
10212  // complete with the restriction that an array type might be completed by
10213  // the initializer; note that later code assumes this restriction.
10214  QualType BaseDeclType = VDecl->getType();
10215  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10216  BaseDeclType = Array->getElementType();
10217  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10218  diag::err_typecheck_decl_incomplete_type)) {
10219  RealDecl->setInvalidDecl();
10220  return;
10221  }
10222 
10223  // The variable can not have an abstract class type.
10224  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10225  diag::err_abstract_type_in_decl,
10226  AbstractVariableType))
10227  VDecl->setInvalidDecl();
10228  }
10229 
10230  // If adding the initializer will turn this declaration into a definition,
10231  // and we already have a definition for this variable, diagnose or otherwise
10232  // handle the situation.
10233  VarDecl *Def;
10234  if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10235  (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10237  checkVarDeclRedefinition(Def, VDecl))
10238  return;
10239 
10240  if (getLangOpts().CPlusPlus) {
10241  // C++ [class.static.data]p4
10242  // If a static data member is of const integral or const
10243  // enumeration type, its declaration in the class definition can
10244  // specify a constant-initializer which shall be an integral
10245  // constant expression (5.19). In that case, the member can appear
10246  // in integral constant expressions. The member shall still be
10247  // defined in a namespace scope if it is used in the program and the
10248  // namespace scope definition shall not contain an initializer.
10249  //
10250  // We already performed a redefinition check above, but for static
10251  // data members we also need to check whether there was an in-class
10252  // declaration with an initializer.
10253  if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10254  Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10255  << VDecl->getDeclName();
10256  Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10257  diag::note_previous_initializer)
10258  << 0;
10259  return;
10260  }
10261 
10262  if (VDecl->hasLocalStorage())
10263  getCurFunction()->setHasBranchProtectedScope();
10264 
10265  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10266  VDecl->setInvalidDecl();
10267  return;
10268  }
10269  }
10270 
10271  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10272  // a kernel function cannot be initialized."
10273  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10274  Diag(VDecl->getLocation(), diag::err_local_cant_init);
10275  VDecl->setInvalidDecl();
10276  return;
10277  }
10278 
10279  // Get the decls type and save a reference for later, since
10280  // CheckInitializerTypes may change it.
10281  QualType DclT = VDecl->getType(), SavT = DclT;
10282 
10283  // Expressions default to 'id' when we're in a debugger
10284  // and we are assigning it to a variable of Objective-C pointer type.
10285  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10286  Init->getType() == Context.UnknownAnyTy) {
10287  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10288  if (Result.isInvalid()) {
10289  VDecl->setInvalidDecl();
10290  return;
10291  }
10292  Init = Result.get();
10293  }
10294 
10295  // Perform the initialization.
10296  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10297  if (!VDecl->isInvalidDecl()) {
10300  VDecl->getLocation(), DirectInit, Init);
10301 
10302  MultiExprArg Args = Init;
10303  if (CXXDirectInit)
10304  Args = MultiExprArg(CXXDirectInit->getExprs(),
10305  CXXDirectInit->getNumExprs());
10306 
10307  // Try to correct any TypoExprs in the initialization arguments.
10308  for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10309  ExprResult Res = CorrectDelayedTyposInExpr(
10310  Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10311  InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10312  return Init.Failed() ? ExprError() : E;
10313  });
10314  if (Res.isInvalid()) {
10315  VDecl->setInvalidDecl();
10316  } else if (Res.get() != Args[Idx]) {
10317  Args[Idx] = Res.get();
10318  }
10319  }
10320  if (VDecl->isInvalidDecl())
10321  return;
10322 
10323  InitializationSequence InitSeq(*this, Entity, Kind, Args,
10324  /*TopLevelOfInitList=*/false,
10325  /*TreatUnavailableAsInvalid=*/false);
10326  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10327  if (Result.isInvalid()) {
10328  VDecl->setInvalidDecl();
10329  return;
10330  }
10331 
10332  Init = Result.getAs<Expr>();
10333  }
10334 
10335  // Check for self-references within variable initializers.
10336  // Variables declared within a function/method body (except for references)
10337  // are handled by a dataflow analysis.
10338  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10339  VDecl->getType()->isReferenceType()) {
10340  CheckSelfReference(*this, RealDecl, Init, DirectInit);
10341  }
10342 
10343  // If the type changed, it means we had an incomplete type that was
10344  // completed by the initializer. For example:
10345  // int ary[] = { 1, 3, 5 };
10346  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10347  if (!VDecl->isInvalidDecl() && (DclT != SavT))
10348  VDecl->setType(DclT);
10349 
10350  if (!VDecl->isInvalidDecl()) {
10351  checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10352 
10353  if (VDecl->hasAttr<BlocksAttr>())
10354  checkRetainCycles(VDecl, Init);
10355 
10356  // It is safe to assign a weak reference into a strong variable.
10357  // Although this code can still have problems:
10358  // id x = self.weakProp;
10359  // id y = self.weakProp;
10360  // we do not warn to warn spuriously when 'x' and 'y' are on separate
10361  // paths through the function. This should be revisited if
10362  // -Wrepeated-use-of-weak is made flow-sensitive.
10363  if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10364  VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10365  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10366  Init->getLocStart()))
10367  getCurFunction()->markSafeWeakUse(Init);
10368  }
10369 
10370  // The initialization is usually a full-expression.
10371  //
10372  // FIXME: If this is a braced initialization of an aggregate, it is not
10373  // an expression, and each individual field initializer is a separate
10374  // full-expression. For instance, in:
10375  //
10376  // struct Temp { ~Temp(); };
10377  // struct S { S(Temp); };
10378  // struct T { S a, b; } t = { Temp(), Temp() }
10379  //
10380  // we should destroy the first Temp before constructing the second.
10381  ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10382  false,
10383  VDecl->isConstexpr());
10384  if (Result.isInvalid()) {
10385  VDecl->setInvalidDecl();
10386  return;
10387  }
10388  Init = Result.get();
10389 
10390  // Attach the initializer to the decl.
10391  VDecl->setInit(Init);
10392 
10393  if (VDecl->isLocalVarDecl()) {
10394  // Don't check the initializer if the declaration is malformed.
10395  if (VDecl->isInvalidDecl()) {
10396  // do nothing
10397 
10398  // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10399  // This is true even in OpenCL C++.
10400  } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10401  CheckForConstantInitializer(Init, DclT);
10402 
10403  // Otherwise, C++ does not restrict the initializer.
10404  } else if (getLangOpts().CPlusPlus) {
10405  // do nothing
10406 
10407  // C99 6.7.8p4: All the expressions in an initializer for an object that has
10408  // static storage duration shall be constant expressions or string literals.
10409  } else if (VDecl->getStorageClass() == SC_Static) {
10410  CheckForConstantInitializer(Init, DclT);
10411 
10412  // C89 is stricter than C99 for aggregate initializers.
10413  // C89 6.5.7p3: All the expressions [...] in an initializer list
10414  // for an object that has aggregate or union type shall be
10415  // constant expressions.
10416  } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10417  isa<InitListExpr>(Init)) {
10418  const Expr *Culprit;
10419  if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10420  Diag(Culprit->getExprLoc(),
10421  diag::ext_aggregate_init_not_constant)
10422  << Culprit->getSourceRange();
10423  }
10424  }
10425  } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10426  VDecl->getLexicalDeclContext()->isRecord()) {
10427  // This is an in-class initialization for a static data member, e.g.,
10428  //
10429  // struct S {
10430  // static const int value = 17;
10431  // };
10432 
10433  // C++ [class.mem]p4:
10434  // A member-declarator can contain a constant-initializer only
10435  // if it declares a static member (9.4) of const integral or
10436  // const enumeration type, see 9.4.2.
10437  //
10438  // C++11 [class.static.data]p3:
10439  // If a non-volatile non-inline const static data member is of integral
10440  // or enumeration type, its declaration in the class definition can
10441  // specify a brace-or-equal-initializer in which every initializer-clause
10442  // that is an assignment-expression is a constant expression. A static
10443  // data member of literal type can be declared in the class definition
10444  // with the constexpr specifier; if so, its declaration shall specify a
10445  // brace-or-equal-initializer in which every initializer-clause that is
10446  // an assignment-expression is a constant expression.
10447 
10448  // Do nothing on dependent types.
10449  if (DclT->isDependentType()) {
10450 
10451  // Allow any 'static constexpr' members, whether or not they are of literal
10452  // type. We separately check that every constexpr variable is of literal
10453  // type.
10454  } else if (VDecl->isConstexpr()) {
10455 
10456  // Require constness.
10457  } else if (!DclT.isConstQualified()) {
10458  Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10459  << Init->getSourceRange();
10460  VDecl->setInvalidDecl();
10461 
10462  // We allow integer constant expressions in all cases.
10463  } else if (DclT->isIntegralOrEnumerationType()) {
10464  // Check whether the expression is a constant expression.
10465  SourceLocation Loc;
10466  if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10467  // In C++11, a non-constexpr const static data member with an
10468  // in-class initializer cannot be volatile.
10469  Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10470  else if (Init->isValueDependent())
10471  ; // Nothing to check.
10472  else if (Init->isIntegerConstantExpr(Context, &Loc))
10473  ; // Ok, it's an ICE!
10474  else if (Init->isEvaluatable(Context)) {
10475  // If we can constant fold the initializer through heroics, accept it,
10476  // but report this as a use of an extension for -pedantic.
10477  Diag(Loc, diag::ext_in_class_initializer_non_constant)
10478  << Init->getSourceRange();
10479  } else {
10480  // Otherwise, this is some crazy unknown case. Report the issue at the
10481  // location provided by the isIntegerConstantExpr failed check.
10482  Diag(Loc, diag::err_in_class_initializer_non_constant)
10483  << Init->getSourceRange();
10484  VDecl->setInvalidDecl();
10485  }
10486 
10487  // We allow foldable floating-point constants as an extension.
10488  } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10489  // In C++98, this is a GNU extension. In C++11, it is not, but we support
10490  // it anyway and provide a fixit to add the 'constexpr'.
10491  if (getLangOpts().CPlusPlus11) {
10492  Diag(VDecl->getLocation(),
10493  diag::ext_in_class_initializer_float_type_cxx11)
10494  << DclT << Init->getSourceRange();
10495  Diag(VDecl->getLocStart(),
10496  diag::note_in_class_initializer_float_type_cxx11)
10497  << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10498  } else {
10499  Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10500  << DclT << Init->getSourceRange();
10501 
10502  if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10503  Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10504  << Init->getSourceRange();
10505  VDecl->setInvalidDecl();
10506  }
10507  }
10508 
10509  // Suggest adding 'constexpr' in C++11 for literal types.
10510  } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10511  Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10512  << DclT << Init->getSourceRange()
10513  << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10514  VDecl->setConstexpr(true);
10515 
10516  } else {
10517  Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10518  << DclT << Init->getSourceRange();
10519  VDecl->setInvalidDecl();
10520  }
10521  } else if (VDecl->isFileVarDecl()) {
10522  // In C, extern is typically used to avoid tentative definitions when
10523  // declaring variables in headers, but adding an intializer makes it a
10524  // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10525  // In C++, extern is often used to give implictly static const variables
10526  // external linkage, so don't warn in that case. If selectany is present,
10527  // this might be header code intended for C and C++ inclusion, so apply the
10528  // C++ rules.
10529  if (VDecl->getStorageClass() == SC_Extern &&
10530  ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10531  !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10532  !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10534  Diag(VDecl->getLocation(), diag::warn_extern_init);
10535 
10536  // C99 6.7.8p4. All file scoped initializers need to be constant.
10537  if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10538  CheckForConstantInitializer(Init, DclT);
10539  }
10540 
10541  // We will represent direct-initialization similarly to copy-initialization:
10542  // int x(1); -as-> int x = 1;
10543  // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10544  //
10545  // Clients that want to distinguish between the two forms, can check for
10546  // direct initializer using VarDecl::getInitStyle().
10547  // A major benefit is that clients that don't particularly care about which
10548  // exactly form was it (like the CodeGen) can handle both cases without
10549  // special case code.
10550 
10551  // C++ 8.5p11:
10552  // The form of initialization (using parentheses or '=') is generally
10553  // insignificant, but does matter when the entity being initialized has a
10554  // class type.
10555  if (CXXDirectInit) {
10556  assert(DirectInit && "Call-style initializer must be direct init.");
10558  } else if (DirectInit) {
10559  // This must be list-initialization. No other way is direct-initialization.
10561  }
10562 
10563  CheckCompleteVariableDeclaration(VDecl);
10564 }
10565 
10566 /// ActOnInitializerError - Given that there was an error parsing an
10567 /// initializer for the given declaration, try to return to some form
10568 /// of sanity.
10570  // Our main concern here is re-establishing invariants like "a
10571  // variable's type is either dependent or complete".
10572  if (!D || D->isInvalidDecl()) return;
10573 
10574  VarDecl *VD = dyn_cast<VarDecl>(D);
10575  if (!VD) return;
10576 
10577  // Bindings are not usable if we can't make sense of the initializer.
10578  if (auto *DD = dyn_cast<DecompositionDecl>(D))
10579  for (auto *BD : DD->bindings())
10580  BD->setInvalidDecl();
10581 
10582  // Auto types are meaningless if we can't make sense of the initializer.
10583  if (ParsingInitForAutoVars.count(D)) {
10584  D->setInvalidDecl();
10585  return;
10586  }
10587 
10588  QualType Ty = VD->getType();
10589  if (Ty->isDependentType()) return;
10590 
10591  // Require a complete type.
10592  if (RequireCompleteType(VD->getLocation(),
10593  Context.getBaseElementType(Ty),
10594  diag::err_typecheck_decl_incomplete_type)) {
10595  VD->setInvalidDecl();
10596  return;
10597  }
10598 
10599  // Require a non-abstract type.
10600  if (RequireNonAbstractType(VD->getLocation(), Ty,
10601  diag::err_abstract_type_in_decl,
10602  AbstractVariableType)) {
10603  VD->setInvalidDecl();
10604  return;
10605  }
10606 
10607  // Don't bother complaining about constructors or destructors,
10608  // though.
10609 }
10610 
10612  // If there is no declaration, there was an error parsing it. Just ignore it.
10613  if (!RealDecl)
10614  return;
10615 
10616  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10617  QualType Type = Var->getType();
10618 
10619  // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10620  if (isa<DecompositionDecl>(RealDecl)) {
10621  Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10622  Var->setInvalidDecl();
10623  return;
10624  }
10625 
10626  if (Type->isUndeducedType() &&
10627  DeduceVariableDeclarationType(Var, false, nullptr))
10628  return;
10629 
10630  // C++11 [class.static.data]p3: A static data member can be declared with
10631  // the constexpr specifier; if so, its declaration shall specify
10632  // a brace-or-equal-initializer.
10633  // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10634  // the definition of a variable [...] or the declaration of a static data
10635  // member.
10636  if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10637  !Var->isThisDeclarationADemotedDefinition()) {
10638  if (Var->isStaticDataMember()) {
10639  // C++1z removes the relevant rule; the in-class declaration is always
10640  // a definition there.
10641  if (!getLangOpts().CPlusPlus17) {
10642  Diag(Var->getLocation(),
10643  diag::err_constexpr_static_mem_var_requires_init)
10644  << Var->getDeclName();
10645  Var->setInvalidDecl();
10646  return;
10647  }
10648  } else {
10649  Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10650  Var->setInvalidDecl();
10651  return;
10652  }
10653  }
10654 
10655  // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10656  // be initialized.
10657  if (!Var->isInvalidDecl() &&
10658  Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10659  Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10660  Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10661  Var->setInvalidDecl();
10662  return;
10663  }
10664 
10665  switch (Var->isThisDeclarationADefinition()) {
10666  case VarDecl::Definition:
10667  if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10668  break;
10669 
10670  // We have an out-of-line definition of a static data member
10671  // that has an in-class initializer, so we type-check this like
10672  // a declaration.
10673  //
10674  LLVM_FALLTHROUGH;
10675 
10677  // It's only a declaration.
10678 
10679  // Block scope. C99 6.7p7: If an identifier for an object is
10680  // declared with no linkage (C99 6.2.2p6), the type for the
10681  // object shall be complete.
10682  if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10683  !Var->hasLinkage() && !Var->isInvalidDecl() &&
10684  RequireCompleteType(Var->getLocation(), Type,
10685  diag::err_typecheck_decl_incomplete_type))
10686  Var->setInvalidDecl();
10687 
10688  // Make sure that the type is not abstract.
10689  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10690  RequireNonAbstractType(Var->getLocation(), Type,
10691  diag::err_abstract_type_in_decl,
10692  AbstractVariableType))
10693  Var->setInvalidDecl();
10694  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10695  Var->getStorageClass() == SC_PrivateExtern) {
10696  Diag(Var->getLocation(), diag::warn_private_extern);
10697  Diag(Var->getLocation(), diag::note_private_extern);
10698  }
10699 
10700  return;
10701 
10703  // File scope. C99 6.9.2p2: A declaration of an identifier for an
10704  // object that has file scope without an initializer, and without a
10705  // storage-class specifier or with the storage-class specifier "static",
10706  // constitutes a tentative definition. Note: A tentative definition with
10707  // external linkage is valid (C99 6.2.2p5).
10708  if (!Var->isInvalidDecl()) {
10709  if (const IncompleteArrayType *ArrayT
10710  = Context.getAsIncompleteArrayType(Type)) {
10711  if (RequireCompleteType(Var->getLocation(),
10712  ArrayT->getElementType(),
10713  diag::err_illegal_decl_array_incomplete_type))
10714  Var->setInvalidDecl();
10715  } else if (Var->getStorageClass() == SC_Static) {
10716  // C99 6.9.2p3: If the declaration of an identifier for an object is
10717  // a tentative definition and has internal linkage (C99 6.2.2p3), the
10718  // declared type shall not be an incomplete type.
10719  // NOTE: code such as the following
10720  // static struct s;
10721  // struct s { int a; };
10722  // is accepted by gcc. Hence here we issue a warning instead of
10723  // an error and we do not invalidate the static declaration.
10724  // NOTE: to avoid multiple warnings, only check the first declaration.
10725  if (Var->isFirstDecl())
10726  RequireCompleteType(Var->getLocation(), Type,
10727  diag::ext_typecheck_decl_incomplete_type);
10728  }
10729  }
10730 
10731  // Record the tentative definition; we're done.
10732  if (!Var->isInvalidDecl())
10733  TentativeDefinitions.push_back(Var);
10734  return;
10735  }
10736 
10737  // Provide a specific diagnostic for uninitialized variable
10738  // definitions with incomplete array type.
10739  if (Type->isIncompleteArrayType()) {
10740  Diag(Var->getLocation(),
10741  diag::err_typecheck_incomplete_array_needs_initializer);
10742  Var->setInvalidDecl();
10743  return;
10744  }
10745 
10746  // Provide a specific diagnostic for uninitialized variable
10747  // definitions with reference type.
10748  if (Type->isReferenceType()) {
10749  Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10750  << Var->getDeclName()
10751  << SourceRange(Var->getLocation(), Var->getLocation());
10752  Var->setInvalidDecl();
10753  return;
10754  }
10755 
10756  // Do not attempt to type-check the default initializer for a
10757  // variable with dependent type.
10758  if (Type->isDependentType())
10759  return;
10760 
10761  if (Var->isInvalidDecl())
10762  return;
10763 
10764  if (!Var->hasAttr<AliasAttr>()) {
10765  if (RequireCompleteType(Var->getLocation(),
10766  Context.getBaseElementType(Type),
10767  diag::err_typecheck_decl_incomplete_type)) {
10768  Var->setInvalidDecl();
10769  return;
10770  }
10771  } else {
10772  return;
10773  }
10774 
10775  // The variable can not have an abstract class type.
10776  if (RequireNonAbstractType(Var->getLocation(), Type,
10777  diag::err_abstract_type_in_decl,
10778  AbstractVariableType)) {
10779  Var->setInvalidDecl();
10780  return;
10781  }
10782 
10783  // Check for jumps past the implicit initializer. C++0x
10784  // clarifies that this applies to a "variable with automatic
10785  // storage duration", not a "local variable".
10786  // C++11 [stmt.dcl]p3
10787  // A program that jumps from a point where a variable with automatic
10788  // storage duration is not in scope to a point where it is in scope is
10789  // ill-formed unless the variable has scalar type, class type with a
10790  // trivial default constructor and a trivial destructor, a cv-qualified
10791  // version of one of these types, or an array of one of the preceding
10792  // types and is declared without an initializer.
10793  if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10794  if (const RecordType *Record
10795  = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10796  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10797  // Mark the function for further checking even if the looser rules of
10798  // C++11 do not require such checks, so that we can diagnose
10799  // incompatibilities with C++98.
10800  if (!CXXRecord->isPOD())
10801  getCurFunction()->setHasBranchProtectedScope();
10802  }
10803  }
10804 
10805  // C++03 [dcl.init]p9:
10806  // If no initializer is specified for an object, and the
10807  // object is of (possibly cv-qualified) non-POD class type (or
10808  // array thereof), the object shall be default-initialized; if
10809  // the object is of const-qualified type, the underlying class
10810  // type shall have a user-declared default
10811  // constructor. Otherwise, if no initializer is specified for
10812  // a non- static object, the object and its subobjects, if
10813  // any, have an indeterminate initial value); if the object
10814  // or any of its subobjects are of const-qualified type, the
10815  // program is ill-formed.
10816  // C++0x [dcl.init]p11:
10817  // If no initializer is specified for an object, the object is
10818  // default-initialized; [...].
10821  = InitializationKind::CreateDefault(Var->getLocation());
10822 
10823  InitializationSequence InitSeq(*this, Entity, Kind, None);
10824  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10825  if (Init.isInvalid())
10826  Var->setInvalidDecl();
10827  else if (Init.get()) {
10828  Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10829  // This is important for template substitution.
10830  Var->setInitStyle(VarDecl::CallInit);
10831  }
10832 
10833  CheckCompleteVariableDeclaration(Var);
10834  }
10835 }
10836 
10838  // If there is no declaration, there was an error parsing it. Ignore it.
10839  if (!D)
10840  return;
10841 
10842  VarDecl *VD = dyn_cast<VarDecl>(D);
10843  if (!VD) {
10844  Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10845  D->setInvalidDecl();
10846  return;
10847  }
10848 
10849  VD->setCXXForRangeDecl(true);
10850 
10851  // for-range-declaration cannot be given a storage class specifier.
10852  int Error = -1;
10853  switch (VD->getStorageClass()) {
10854  case SC_None:
10855  break;
10856  case SC_Extern:
10857  Error = 0;
10858  break;
10859  case SC_Static:
10860  Error = 1;
10861  break;
10862  case SC_PrivateExtern:
10863  Error = 2;
10864  break;
10865  case SC_Auto:
10866  Error = 3;
10867  break;
10868  case SC_Register:
10869  Error = 4;
10870  break;
10871  }
10872  if (Error != -1) {
10873  Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10874  << VD->getDeclName() << Error;
10875  D->setInvalidDecl();
10876  }
10877 }
10878 
10879 StmtResult
10881  IdentifierInfo *Ident,
10882  ParsedAttributes &Attrs,
10883  SourceLocation AttrEnd) {
10884  // C++1y [stmt.iter]p1:
10885  // A range-based for statement of the form
10886  // for ( for-range-identifier : for-range-initializer ) statement
10887  // is equivalent to
10888  // for ( auto&& for-range-identifier : for-range-initializer ) statement
10889  DeclSpec DS(Attrs.getPool().getFactory());
10890 
10891  const char *PrevSpec;
10892  unsigned DiagID;
10893  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10894  getPrintingPolicy());
10895 
10897  D.SetIdentifier(Ident, IdentLoc);
10898  D.takeAttributes(Attrs, AttrEnd);
10899 
10900  ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10901  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10902  EmptyAttrs, IdentLoc);
10903  Decl *Var = ActOnDeclarator(S, D);
10904  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10905  FinalizeDeclaration(Var);
10906  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10907  AttrEnd.isValid() ? AttrEnd : IdentLoc);
10908 }
10909 
10911  if (var->isInvalidDecl()) return;
10912 
10913  if (getLangOpts().OpenCL) {
10914  // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10915  // initialiser
10916  if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10917  !var->hasInit()) {
10918  Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10919  << 1 /*Init*/;
10920  var->setInvalidDecl();
10921  return;
10922  }
10923  }
10924 
10925  // In Objective-C, don't allow jumps past the implicit initialization of a
10926  // local retaining variable.
10927  if (getLangOpts().ObjC1 &&
10928  var->hasLocalStorage()) {
10929  switch (var->getType().getObjCLifetime()) {
10930  case Qualifiers::OCL_None:
10933  break;
10934 
10935  case Qualifiers::OCL_Weak:
10937  getCurFunction()->setHasBranchProtectedScope();
10938  break;
10939  }
10940  }
10941 
10942  // Warn about externally-visible variables being defined without a
10943  // prior declaration. We only want to do this for global
10944  // declarations, but we also specifically need to avoid doing it for
10945  // class members because the linkage of an anonymous class can
10946  // change if it's later given a typedef name.
10947  if (var->isThisDeclarationADefinition() &&
10949  var->isExternallyVisible() && var->hasLinkage() &&
10950  !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10951  var->getLocation())) {
10952  // Find a previous declaration that's not a definition.
10953  VarDecl *prev = var->getPreviousDecl();
10954  while (prev && prev->isThisDeclarationADefinition())
10955  prev = prev->getPreviousDecl();
10956 
10957  if (!prev)
10958  Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10959  }
10960 
10961  // Cache the result of checking for constant initialization.
10962  Optional<bool> CacheHasConstInit;
10963  const Expr *CacheCulprit;
10964  auto checkConstInit = [&]() mutable {
10965  if (!CacheHasConstInit)
10966  CacheHasConstInit = var->getInit()->isConstantInitializer(
10967  Context, var->getType()->isReferenceType(), &CacheCulprit);
10968  return *CacheHasConstInit;
10969  };
10970 
10971  if (var->getTLSKind() == VarDecl::TLS_Static) {
10972  if (var->getType().isDestructedType()) {
10973  // GNU C++98 edits for __thread, [basic.start.term]p3:
10974  // The type of an object with thread storage duration shall not
10975  // have a non-trivial destructor.
10976  Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10977  if (getLangOpts().CPlusPlus11)
10978  Diag(var->getLocation(), diag::note_use_thread_local);
10979  } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10980  if (!checkConstInit()) {
10981  // GNU C++98 edits for __thread, [basic.start.init]p4:
10982  // An object of thread storage duration shall not require dynamic
10983  // initialization.
10984  // FIXME: Need strict checking here.
10985  Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10986  << CacheCulprit->getSourceRange();
10987  if (getLangOpts().CPlusPlus11)
10988  Diag(var->getLocation(), diag::note_use_thread_local);
10989  }
10990  }
10991  }
10992 
10993  // Apply section attributes and pragmas to global variables.
10994  bool GlobalStorage = var->hasGlobalStorage();
10995  if (GlobalStorage && var->isThisDeclarationADefinition() &&
10996  !inTemplateInstantiation()) {
10997  PragmaStack<StringLiteral *> *Stack = nullptr;
10998  int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10999  if (var->getType().isConstQualified())
11000  Stack = &ConstSegStack;
11001  else if (!var->getInit()) {
11002  Stack = &BSSSegStack;
11003  SectionFlags |= ASTContext::PSF_Write;
11004  } else {
11005  Stack = &DataSegStack;
11006  SectionFlags |= ASTContext::PSF_Write;
11007  }
11008  if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11009  var->addAttr(SectionAttr::CreateImplicit(
11010  Context, SectionAttr::Declspec_allocate,
11011  Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11012  }
11013  if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11014  if (UnifySection(SA->getName(), SectionFlags, var))
11015  var->dropAttr<SectionAttr>();
11016 
11017  // Apply the init_seg attribute if this has an initializer. If the
11018  // initializer turns out to not be dynamic, we'll end up ignoring this
11019  // attribute.
11020  if (CurInitSeg && var->getInit())
11021  var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11022  CurInitSegLoc));
11023  }
11024 
11025  // All the following checks are C++ only.
11026  if (!getLangOpts().CPlusPlus) {
11027  // If this variable must be emitted, add it as an initializer for the
11028  // current module.
11029  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11030  Context.addModuleInitializer(ModuleScopes.back().Module, var);
11031  return;
11032  }
11033 
11034  if (auto *DD = dyn_cast<DecompositionDecl>(var))
11035  CheckCompleteDecompositionDeclaration(DD);
11036 
11037  QualType type = var->getType();
11038  if (type->isDependentType()) return;
11039 
11040  // __block variables might require us to capture a copy-initializer.
11041  if (var->hasAttr<BlocksAttr>()) {
11042  // It's currently invalid to ever have a __block variable with an
11043  // array type; should we diagnose that here?
11044 
11045  // Regardless, we don't want to ignore array nesting when
11046  // constructing this copy.
11047  if (type->isStructureOrClassType()) {
11049  *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11050  SourceLocation poi = var->getLocation();
11051  Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11052  ExprResult result
11053  = PerformMoveOrCopyInitialization(
11054  InitializedEntity::InitializeBlock(poi, type, false),
11055  var, var->getType(), varRef, /*AllowNRVO=*/true);
11056  if (!result.isInvalid()) {
11057  result = MaybeCreateExprWithCleanups(result);
11058  Expr *init = result.getAs<Expr>();
11059  Context.setBlockVarCopyInits(var, init);
11060  }
11061  }
11062  }
11063 
11064  Expr *Init = var->getInit();
11065  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11066  QualType baseType = Context.getBaseElementType(type);
11067 
11068  if (Init && !Init->isValueDependent()) {
11069  if (var->isConstexpr()) {
11071  if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11072  SourceLocation DiagLoc = var->getLocation();
11073  // If the note doesn't add any useful information other than a source
11074  // location, fold it into the primary diagnostic.
11075  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11076  diag::note_invalid_subexpr_in_const_expr) {
11077  DiagLoc = Notes[0].first;
11078  Notes.clear();
11079  }
11080  Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11081  << var << Init->getSourceRange();
11082  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11083  Diag(Notes[I].first, Notes[I].second);
11084  }
11085  } else if (var->isUsableInConstantExpressions(Context)) {
11086  // Check whether the initializer of a const variable of integral or
11087  // enumeration type is an ICE now, since we can't tell whether it was
11088  // initialized by a constant expression if we check later.
11089  var->checkInitIsICE();
11090  }
11091 
11092  // Don't emit further diagnostics about constexpr globals since they
11093  // were just diagnosed.
11094  if (!var->isConstexpr() && GlobalStorage &&
11095  var->hasAttr<RequireConstantInitAttr>()) {
11096  // FIXME: Need strict checking in C++03 here.
11097  bool DiagErr = getLangOpts().CPlusPlus11
11098  ? !var->checkInitIsICE() : !checkConstInit();
11099  if (DiagErr) {
11100  auto attr = var->getAttr<RequireConstantInitAttr>();
11101  Diag(var->getLocation(), diag::err_require_constant_init_failed)
11102  << Init->getSourceRange();
11103  Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11104  << attr->getRange();
11105  if (getLangOpts().CPlusPlus11) {
11106  APValue Value;
11108  Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11109  for (auto &it : Notes)
11110  Diag(it.first, it.second);
11111  } else {
11112  Diag(CacheCulprit->getExprLoc(),
11113  diag::note_invalid_subexpr_in_const_expr)
11114  << CacheCulprit->getSourceRange();
11115  }
11116  }
11117  }
11118  else if (!var->isConstexpr() && IsGlobal &&
11119  !getDiagnostics().isIgnored(diag::warn_global_constructor,
11120  var->getLocation())) {
11121  // Warn about globals which don't have a constant initializer. Don't
11122  // warn about globals with a non-trivial destructor because we already
11123  // warned about them.
11124  CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11125  if (!(RD && !RD->hasTrivialDestructor())) {
11126  if (!checkConstInit())
11127  Diag(var->getLocation(), diag::warn_global_constructor)
11128  << Init->getSourceRange();
11129  }
11130  }
11131  }
11132 
11133  // Require the destructor.
11134  if (const RecordType *recordType = baseType->getAs<RecordType>())
11135  FinalizeVarWithDestructor(var, recordType);
11136 
11137  // If this variable must be emitted, add it as an initializer for the current
11138  // module.
11139  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11140  Context.addModuleInitializer(ModuleScopes.back().Module, var);
11141 }
11142 
11143 /// \brief Determines if a variable's alignment is dependent.
11144 static bool hasDependentAlignment(VarDecl *VD) {
11145  if (VD->getType()->isDependentType())
11146  return true;
11147  for (auto *I : VD->specific_attrs<AlignedAttr>())
11148  if (I->isAlignmentDependent())
11149  return true;
11150  return false;
11151 }
11152 
11153 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11154 /// any semantic actions necessary after any initializer has been attached.
11156  // Note that we are no longer parsing the initializer for this declaration.
11157  ParsingInitForAutoVars.erase(ThisDecl);
11158 
11159  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11160  if (!VD)
11161  return;
11162 
11163  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11164  if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11165  !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11166  if (PragmaClangBSSSection.Valid)
11167  VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11168  PragmaClangBSSSection.SectionName,
11169  PragmaClangBSSSection.PragmaLocation));
11170  if (PragmaClangDataSection.Valid)
11171  VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11172  PragmaClangDataSection.SectionName,
11173  PragmaClangDataSection.PragmaLocation));
11174  if (PragmaClangRodataSection.Valid)
11175  VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11176  PragmaClangRodataSection.SectionName,
11177  PragmaClangRodataSection.PragmaLocation));
11178  }
11179 
11180  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11181  for (auto *BD : DD->bindings()) {
11182  FinalizeDeclaration(BD);
11183  }
11184  }
11185 
11186  checkAttributesAfterMerging(*this, *VD);
11187 
11188  // Perform TLS alignment check here after attributes attached to the variable
11189  // which may affect the alignment have been processed. Only perform the check
11190  // if the target has a maximum TLS alignment (zero means no constraints).
11191  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11192  // Protect the check so that it's not performed on dependent types and
11193  // dependent alignments (we can't determine the alignment in that case).
11194  if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11195  !VD->isInvalidDecl()) {
11196  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11197  if (Context.getDeclAlign(VD) > MaxAlignChars) {
11198  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11199  << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11200  << (unsigned)MaxAlignChars.getQuantity();
11201  }
11202  }
11203  }
11204 
11205  if (VD->isStaticLocal()) {
11206  if (FunctionDecl *FD =
11207  dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11208  // Static locals inherit dll attributes from their function.
11209  if (Attr *A = getDLLAttr(FD)) {
11210  auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11211  NewAttr->setInherited(true);
11212  VD->addAttr(NewAttr);
11213  }
11214  // CUDA E.2.9.4: Within the body of a __device__ or __global__
11215  // function, only __shared__ variables may be declared with
11216  // static storage class.
11217  if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11218  CUDADiagIfDeviceCode(VD->getLocation(),
11219  diag::err_device_static_local_var)
11220  << CurrentCUDATarget())
11221  VD->setInvalidDecl();
11222  }
11223  }
11224 
11225  // Perform check for initializers of device-side global variables.
11226  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11227  // 7.5). We must also apply the same checks to all __shared__
11228  // variables whether they are local or not. CUDA also allows
11229  // constant initializers for __constant__ and __device__ variables.
11230  if (getLangOpts().CUDA) {
11231  const Expr *Init = VD->getInit();
11232  if (Init && VD->hasGlobalStorage()) {
11233  if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11234  VD->hasAttr<CUDASharedAttr>()) {
11235  assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11236  bool AllowedInit = false;
11237  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11238  AllowedInit =
11239  isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11240  // We'll allow constant initializers even if it's a non-empty
11241  // constructor according to CUDA rules. This deviates from NVCC,
11242  // but allows us to handle things like constexpr constructors.
11243  if (!AllowedInit &&
11244  (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11245  AllowedInit = VD->getInit()->isConstantInitializer(
11246  Context, VD->getType()->isReferenceType());
11247 
11248  // Also make sure that destructor, if there is one, is empty.
11249  if (AllowedInit)
11250  if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11251  AllowedInit =
11252  isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11253 
11254  if (!AllowedInit) {
11255  Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11256  ? diag::err_shared_var_init
11257  : diag::err_dynamic_var_init)
11258  << Init->getSourceRange();
11259  VD->setInvalidDecl();
11260  }
11261  } else {
11262  // This is a host-side global variable. Check that the initializer is
11263  // callable from the host side.
11264  const FunctionDecl *InitFn = nullptr;
11265  if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11266  InitFn = CE->getConstructor();
11267  } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11268  InitFn = CE->getDirectCallee();
11269  }
11270  if (InitFn) {
11271  CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11272  if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11273  Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11274  << InitFnTarget << InitFn;
11275  Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11276  VD->setInvalidDecl();
11277  }
11278  }
11279  }
11280  }
11281  }
11282 
11283  // Grab the dllimport or dllexport attribute off of the VarDecl.
11284  const InheritableAttr *DLLAttr = getDLLAttr(VD);
11285 
11286  // Imported static data members cannot be defined out-of-line.
11287  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11288  if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11290  // We allow definitions of dllimport class template static data members
11291  // with a warning.
11292  CXXRecordDecl *Context =
11293  cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11294  bool IsClassTemplateMember =
11295  isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11296  Context->getDescribedClassTemplate();
11297 
11298  Diag(VD->getLocation(),
11299  IsClassTemplateMember
11300  ? diag::warn_attribute_dllimport_static_field_definition
11301  : diag::err_attribute_dllimport_static_field_definition);
11302  Diag(IA->getLocation(), diag::note_attribute);
11303  if (!IsClassTemplateMember)
11304  VD->setInvalidDecl();
11305  }
11306  }
11307 
11308  // dllimport/dllexport variables cannot be thread local, their TLS index
11309  // isn't exported with the variable.
11310  if (DLLAttr && VD->getTLSKind()) {
11311  auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11312  if (F && getDLLAttr(F)) {
11313  assert(VD->isStaticLocal());
11314  // But if this is a static local in a dlimport/dllexport function, the
11315  // function will never be inlined, which means the var would never be
11316  // imported, so having it marked import/export is safe.
11317  } else {
11318  Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11319  << DLLAttr;
11320  VD->setInvalidDecl();
11321  }
11322  }
11323 
11324  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11325  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11326  Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11327  VD->dropAttr<UsedAttr>();
11328  }
11329  }
11330 
11331  const DeclContext *DC = VD->getDeclContext();
11332  // If there's a #pragma GCC visibility in scope, and this isn't a class
11333  // member, set the visibility of this variable.
11334  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11335  AddPushedVisibilityAttribute(VD);
11336 
11337  // FIXME: Warn on unused var template partial specializations.
11338  if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11339  MarkUnusedFileScopedDecl(VD);
11340 
11341  // Now we have parsed the initializer and can update the table of magic
11342  // tag values.
11343  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11345  return;
11346 
11347  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11348  const Expr *MagicValueExpr = VD->getInit();
11349  if (!MagicValueExpr) {
11350  continue;
11351  }
11352  llvm::APSInt MagicValueInt;
11353  if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11354  Diag(I->getRange().getBegin(),
11355  diag::err_type_tag_for_datatype_not_ice)
11356  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11357  continue;
11358  }
11359  if (MagicValueInt.getActiveBits() > 64) {
11360  Diag(I->getRange().getBegin(),
11361  diag::err_type_tag_for_datatype_too_large)
11362  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11363  continue;
11364  }
11365  uint64_t MagicValue = MagicValueInt.getZExtValue();
11366  RegisterTypeTagForDatatype(I->getArgumentKind(),
11367  MagicValue,
11368  I->getMatchingCType(),
11369  I->getLayoutCompatible(),
11370  I->getMustBeNull());
11371  }
11372 }
11373 
11374 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11375  auto *VD = dyn_cast<VarDecl>(DD);
11376  return VD && !VD->getType()->hasAutoForTrailingReturnType();
11377 }
11378 
11380  ArrayRef<Decl *> Group) {
11381  SmallVector<Decl*, 8> Decls;
11382 
11383  if (DS.isTypeSpecOwned())
11384  Decls.push_back(DS.getRepAsDecl());
11385 
11386  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11387  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11388  bool DiagnosedMultipleDecomps = false;
11389  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11390  bool DiagnosedNonDeducedAuto = false;
11391 
11392  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11393  if (Decl *D = Group[i]) {
11394  // For declarators, there are some additional syntactic-ish checks we need
11395  // to perform.
11396  if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11397  if (!FirstDeclaratorInGroup)
11398  FirstDeclaratorInGroup = DD;
11399  if (!FirstDecompDeclaratorInGroup)
11400  FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11401  if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11402  !hasDeducedAuto(DD))
11403  FirstNonDeducedAutoInGroup = DD;
11404 
11405  if (FirstDeclaratorInGroup != DD) {
11406  // A decomposition declaration cannot be combined with any other
11407  // declaration in the same group.
11408  if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11409  Diag(FirstDecompDeclaratorInGroup->getLocation(),
11410  diag::err_decomp_decl_not_alone)
11411  << FirstDeclaratorInGroup->getSourceRange()
11412  << DD->getSourceRange();
11413  DiagnosedMultipleDecomps = true;
11414  }
11415 
11416  // A declarator that uses 'auto' in any way other than to declare a
11417  // variable with a deduced type cannot be combined with any other
11418  // declarator in the same group.
11419  if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11420  Diag(FirstNonDeducedAutoInGroup->getLocation(),
11421  diag::err_auto_non_deduced_not_alone)
11422  << FirstNonDeducedAutoInGroup->getType()
11424  << FirstDeclaratorInGroup->getSourceRange()
11425  << DD->getSourceRange();
11426  DiagnosedNonDeducedAuto = true;
11427  }
11428  }
11429  }
11430 
11431  Decls.push_back(D);
11432  }
11433  }
11434 
11436  if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11437  handleTagNumbering(Tag, S);
11438  if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11439  getLangOpts().CPlusPlus)
11440  Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11441  }
11442  }
11443 
11444  return BuildDeclaratorGroup(Decls);
11445 }
11446 
11447 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11448 /// group, performing any necessary semantic checking.
11451  // C++14 [dcl.spec.auto]p7: (DR1347)
11452  // If the type that replaces the placeholder type is not the same in each
11453  // deduction, the program is ill-formed.
11454  if (Group.size() > 1) {
11455  QualType Deduced;
11456  VarDecl *DeducedDecl = nullptr;
11457  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11458  VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11459  if (!D || D->isInvalidDecl())
11460  break;
11462  if (!DT || DT->getDeducedType().isNull())
11463  continue;
11464  if (Deduced.isNull()) {
11465  Deduced = DT->getDeducedType();
11466  DeducedDecl = D;
11467  } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11468  auto *AT = dyn_cast<AutoType>(DT);
11470  diag::err_auto_different_deductions)
11471  << (AT ? (unsigned)AT->getKeyword() : 3)
11472  << Deduced << DeducedDecl->getDeclName()
11473  << DT->getDeducedType() << D->getDeclName()
11474  << DeducedDecl->getInit()->getSourceRange()
11475  << D->getInit()->getSourceRange();
11476  D->setInvalidDecl();
11477  break;
11478  }
11479  }
11480  }
11481 
11482  ActOnDocumentableDecls(Group);
11483 
11484  return DeclGroupPtrTy::make(
11485  DeclGroupRef::Create(Context, Group.data(), Group.size()));
11486 }
11487 
11489  ActOnDocumentableDecls(D);
11490 }
11491 
11493  // Don't parse the comment if Doxygen diagnostics are ignored.
11494  if (Group.empty() || !Group[0])
11495  return;
11496 
11497  if (Diags.isIgnored(diag::warn_doc_param_not_found,
11498  Group[0]->getLocation()) &&
11499  Diags.isIgnored(diag::warn_unknown_comment_command_name,
11500  Group[0]->getLocation()))
11501  return;
11502 
11503  if (Group.size() >= 2) {
11504  // This is a decl group. Normally it will contain only declarations
11505  // produced from declarator list. But in case we have any definitions or
11506  // additional declaration references:
11507  // 'typedef struct S {} S;'
11508  // 'typedef struct S *S;'
11509  // 'struct S *pS;'
11510  // FinalizeDeclaratorGroup adds these as separate declarations.
11511  Decl *MaybeTagDecl = Group[0];
11512  if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11513  Group = Group.slice(1);
11514  }
11515  }
11516 
11517  // See if there are any new comments that are not attached to a decl.
11518  ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11519  if (!Comments.empty() &&
11520  !Comments.back()->isAttached()) {
11521  // There is at least one comment that not attached to a decl.
11522  // Maybe it should be attached to one of these decls?
11523  //
11524  // Note that this way we pick up not only comments that precede the
11525  // declaration, but also comments that *follow* the declaration -- thanks to
11526  // the lookahead in the lexer: we've consumed the semicolon and looked
11527  // ahead through comments.
11528  for (unsigned i = 0, e = Group.size(); i != e; ++i)
11529  Context.getCommentForDecl(Group[i], &PP);
11530  }
11531 }
11532 
11533 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11534 /// to introduce parameters into function prototype scope.
11536  const DeclSpec &DS = D.getDeclSpec();
11537 
11538  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11539 
11540  // C++03 [dcl.stc]p2 also permits 'auto'.
11541  StorageClass SC = SC_None;
11543  SC = SC_Register;
11544  // In C++11, the 'register' storage class specifier is deprecated.
11545  // In C++17, it is not allowed, but we tolerate it as an extension.
11546  if (getLangOpts().CPlusPlus11) {
11548  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11549  : diag::warn_deprecated_register)
11551  }
11552  } else if (getLangOpts().CPlusPlus &&
11554  SC = SC_Auto;
11555  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11557  diag::err_invalid_storage_class_in_func_decl);
11559  }
11560 
11561  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11562  Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11563  << DeclSpec::getSpecifierName(TSCS);
11564  if (DS.isInlineSpecified())
11565  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11566  << getLangOpts().CPlusPlus17;
11567  if (DS.isConstexprSpecified())
11568  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11569  << 0;
11570 
11571  DiagnoseFunctionSpecifiers(DS);
11572 
11573  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11574  QualType parmDeclType = TInfo->getType();
11575 
11576  if (getLangOpts().CPlusPlus) {
11577  // Check that there are no default arguments inside the type of this
11578  // parameter.
11579  CheckExtraCXXDefaultArguments(D);
11580 
11581  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11582  if (D.getCXXScopeSpec().isSet()) {
11583  Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11584  << D.getCXXScopeSpec().getRange();
11585  D.getCXXScopeSpec().clear();
11586  }
11587  }
11588 
11589  // Ensure we have a valid name
11590  IdentifierInfo *II = nullptr;
11591  if (D.hasName()) {
11592  II = D.getIdentifier();
11593  if (!II) {
11594  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11595  << GetNameForDeclarator(D).getName();
11596  D.setInvalidType(true);
11597  }
11598  }
11599 
11600  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11601  if (II) {
11602  LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11603  ForVisibleRedeclaration);
11604  LookupName(R, S);
11605  if (R.isSingleResult()) {
11606  NamedDecl *PrevDecl = R.getFoundDecl();
11607  if (PrevDecl->isTemplateParameter()) {
11608  // Maybe we will complain about the shadowed template parameter.
11609  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11610  // Just pretend that we didn't see the previous declaration.
11611  PrevDecl = nullptr;
11612  } else if (S->isDeclScope(PrevDecl)) {
11613  Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11614  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11615 
11616  // Recover by removing the name
11617  II = nullptr;
11618  D.SetIdentifier(nullptr, D.getIdentifierLoc());
11619  D.setInvalidType(true);
11620  }
11621  }
11622  }
11623 
11624  // Temporarily put parameter variables in the translation unit, not
11625  // the enclosing context. This prevents them from accidentally
11626  // looking like class members in C++.
11627  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11628  D.getLocStart(),
11629  D.getIdentifierLoc(), II,
11630  parmDeclType, TInfo,
11631  SC);
11632 
11633  if (D.isInvalidType())
11634  New->setInvalidDecl();
11635 
11636  assert(S->isFunctionPrototypeScope());
11637  assert(S->getFunctionPrototypeDepth() >= 1);
11640 
11641  // Add the parameter declaration into this scope.
11642  S->AddDecl(New);
11643  if (II)
11644  IdResolver.AddDecl(New);
11645 
11646  ProcessDeclAttributes(S, New, D);
11647 
11649  Diag(New->getLocation(), diag::err_module_private_local)
11650  << 1 << New->getDeclName()
11653 
11654  if (New->hasAttr<BlocksAttr>()) {
11655  Diag(New->getLocation(), diag::err_block_on_nonlocal);
11656  }
11657  return New;
11658 }
11659 
11660 /// \brief Synthesizes a variable for a parameter arising from a
11661 /// typedef.
11663  SourceLocation Loc,
11664  QualType T) {
11665  /* FIXME: setting StartLoc == Loc.
11666  Would it be worth to modify callers so as to provide proper source
11667  location for the unnamed parameters, embedding the parameter's type? */
11668  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11669  T, Context.getTrivialTypeSourceInfo(T, Loc),
11670  SC_None, nullptr);
11671  Param->setImplicit();
11672  return Param;
11673 }
11674 
11676  // Don't diagnose unused-parameter errors in template instantiations; we
11677  // will already have done so in the template itself.
11678  if (inTemplateInstantiation())
11679  return;
11680 
11681  for (const ParmVarDecl *Parameter : Parameters) {
11682  if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11683  !Parameter->hasAttr<UnusedAttr>()) {
11684  Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11685  << Parameter->getDeclName();
11686  }
11687  }
11688 }
11689 
11691  ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11692  if (LangOpts.NumLargeByValueCopy == 0) // No check.
11693  return;
11694 
11695  // Warn if the return value is pass-by-value and larger than the specified
11696  // threshold.
11697  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11698  unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11699  if (Size > LangOpts.NumLargeByValueCopy)
11700  Diag(D->getLocation(), diag::warn_return_value_size)
11701  << D->getDeclName() << Size;
11702  }
11703 
11704  // Warn if any parameter is pass-by-value and larger than the specified
11705  // threshold.
11706  for (const ParmVarDecl *Parameter : Parameters) {
11707  QualType T = Parameter->getType();
11708  if (T->isDependentType() || !T.isPODType(Context))
11709  continue;
11710  unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11711  if (Size > LangOpts.NumLargeByValueCopy)
11712  Diag(Parameter->getLocation(), diag::warn_parameter_size)
11713  << Parameter->getDeclName() << Size;
11714  }
11715 }
11716 
11718  SourceLocation NameLoc, IdentifierInfo *Name,
11719  QualType T, TypeSourceInfo *TSInfo,
11720  StorageClass SC) {
11721  // In ARC, infer a lifetime qualifier for appropriate parameter types.
11722  if (getLangOpts().ObjCAutoRefCount &&
11724  T->isObjCLifetimeType()) {
11725 
11726  Qualifiers::ObjCLifetime lifetime;
11727 
11728  // Special cases for arrays:
11729  // - if it's const, use __unsafe_unretained
11730  // - otherwise, it's an error
11731  if (T->isArrayType()) {
11732  if (!T.isConstQualified()) {
11735  NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11736  }
11737  lifetime = Qualifiers::OCL_ExplicitNone;
11738  } else {
11739  lifetime = T->getObjCARCImplicitLifetime();
11740  }
11741  T = Context.getLifetimeQualifiedType(T, lifetime);
11742  }
11743 
11744  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11745  Context.getAdjustedParameterType(T),
11746  TSInfo, SC, nullptr);
11747 
11748  // Parameters can not be abstract class types.
11749  // For record types, this is done by the AbstractClassUsageDiagnoser once
11750  // the class has been completely parsed.
11751  if (!CurContext->isRecord() &&
11752  RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11753  AbstractParamType))
11754  New->setInvalidDecl();
11755 
11756  // Parameter declarators cannot be interface types. All ObjC objects are
11757  // passed by reference.
11758  if (T->isObjCObjectType()) {
11759  SourceLocation TypeEndLoc =
11760  getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11761  Diag(NameLoc,
11762  diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11763  << FixItHint::CreateInsertion(TypeEndLoc, "*");
11764  T = Context.getObjCObjectPointerType(T);
11765  New->setType(T);
11766  }
11767 
11768  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11769  // duration shall not be qualified by an address-space qualifier."
11770  // Since all parameters have automatic store duration, they can not have
11771  // an address space.
11772  if (T.getAddressSpace() != LangAS::Default &&
11773  // OpenCL allows function arguments declared to be an array of a type
11774  // to be qualified with an address space.
11775  !(getLangOpts().OpenCL &&
11777  Diag(NameLoc, diag::err_arg_with_address_space);
11778  New->setInvalidDecl();
11779  }
11780 
11781  return New;
11782 }
11783 
11785  SourceLocation LocAfterDecls) {
11787 
11788  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11789  // for a K&R function.
11790  if (!FTI.hasPrototype) {
11791  for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11792  --i;
11793  if (FTI.Params[i].Param == nullptr) {
11794  SmallString<256> Code;
11795  llvm::raw_svector_ostream(Code)
11796  << " int " << FTI.Params[i].Ident->getName() << ";\n";
11797  Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11798  << FTI.Params[i].Ident
11799  << FixItHint::CreateInsertion(LocAfterDecls, Code);
11800 
11801  // Implicitly declare the argument as type 'int' for lack of a better
11802  // type.
11803  AttributeFactory attrs;
11804  DeclSpec DS(attrs);
11805  const char* PrevSpec; // unused
11806  unsigned DiagID; // unused
11807  DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11808  DiagID, Context.getPrintingPolicy());
11809  // Use the identifier location for the type source range.
11810  DS.SetRangeStart(FTI.Params[i].IdentLoc);
11811  DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11813  ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11814  FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11815  }
11816  }
11817  }
11818 }
11819 
11820 Decl *
11822  MultiTemplateParamsArg TemplateParameterLists,
11823  SkipBodyInfo *SkipBody) {
11824  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11825  assert(D.isFunctionDeclarator() && "Not a function declarator!");
11826  Scope *ParentScope = FnBodyScope->getParent();
11827 
11829  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11830  return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11831 }
11832 
11834  Consumer.HandleInlineFunctionDefinition(D);
11835 }
11836 
11838  const FunctionDecl*& PossibleZeroParamPrototype) {
11839  // Don't warn about invalid declarations.
11840  if (FD->isInvalidDecl())
11841  return false;
11842 
11843  // Or declarations that aren't global.
11844  if (!FD->isGlobal())
11845  return false;
11846 
11847  // Don't warn about C++ member functions.
11848  if (isa<CXXMethodDecl>(FD))
11849  return false;
11850 
11851  // Don't warn about 'main'.
11852  if (FD->isMain())
11853  return false;
11854 
11855  // Don't warn about inline functions.
11856  if (FD->isInlined())
11857  return false;
11858 
11859  // Don't warn about function templates.
11860  if (FD->getDescribedFunctionTemplate())
11861  return false;
11862 
11863  // Don't warn about function template specializations.
11865  return false;
11866 
11867  // Don't warn for OpenCL kernels.
11868  if (FD->hasAttr<OpenCLKernelAttr>())
11869  return false;
11870 
11871  // Don't warn on explicitly deleted functions.
11872  if (FD->isDeleted())
11873  return false;
11874 
11875  bool MissingPrototype = true;
11876  for (const FunctionDecl *Prev = FD->getPreviousDecl();
11877  Prev; Prev = Prev->getPreviousDecl()) {
11878  // Ignore any declarations that occur in function or method
11879  // scope, because they aren't visible from the header.
11880  if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11881  continue;
11882 
11883  MissingPrototype = !Prev->getType()->isFunctionProtoType();
11884  if (FD->getNumParams() == 0)
11885  PossibleZeroParamPrototype = Prev;
11886  break;
11887  }
11888 
11889  return MissingPrototype;
11890 }
11891 
11892 void
11894  const FunctionDecl *EffectiveDefinition,
11895  SkipBodyInfo *SkipBody) {
11896  const FunctionDecl *Definition = EffectiveDefinition;
11897  if (!Definition)
11898  if (!FD->isDefined(Definition))
11899  return;
11900 
11901  if (canRedefineFunction(Definition, getLangOpts()))
11902  return;
11903 
11904  // Don't emit an error when this is redefinition of a typo-corrected
11905  // definition.
11906  if (TypoCorrectedFunctionDefinitions.count(Definition))
11907  return;
11908 
11909  // If we don't have a visible definition of the function, and it's inline or
11910  // a template, skip the new definition.
11911  if (SkipBody && !hasVisibleDefinition(Definition) &&
11912  (Definition->getFormalLinkage() == InternalLinkage ||
11913  Definition->isInlined() ||
11914  Definition->getDescribedFunctionTemplate() ||
11915  Definition->getNumTemplateParameterLists())) {
11916  SkipBody->ShouldSkip = true;
11917  if (auto *TD = Definition->getDescribedFunctionTemplate())
11918  makeMergedDefinitionVisible(TD);
11919  makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
11920  return;
11921  }
11922 
11923  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11924  Definition->getStorageClass() == SC_Extern)
11925  Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11926  << FD->getDeclName() << getLangOpts().CPlusPlus;
11927  else
11928  Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11929 
11930  Diag(Definition->getLocation(), diag::note_previous_definition);
11931  FD->setInvalidDecl();
11932 }
11933 
11934 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11935  Sema &S) {
11936  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11937 
11938  LambdaScopeInfo *LSI = S.PushLambdaScope();
11939  LSI->CallOperator = CallOperator;
11940  LSI->Lambda = LambdaClass;
11941  LSI->ReturnType = CallOperator->getReturnType();
11942  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11943 
11944  if (LCD == LCD_None)
11946  else if (LCD == LCD_ByCopy)
11948  else if (LCD == LCD_ByRef)
11950  DeclarationNameInfo DNI = CallOperator->getNameInfo();
11951 
11953  LSI->Mutable = !CallOperator->isConst();
11954 
11955  // Add the captures to the LSI so they can be noted as already
11956  // captured within tryCaptureVar.
11957  auto I = LambdaClass->field_begin();
11958  for (const auto &C : LambdaClass->captures()) {
11959  if (C.capturesVariable()) {
11960  VarDecl *VD = C.getCapturedVar();
11961  if (VD->isInitCapture())
11963  QualType CaptureType = VD->getType();
11964  const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11965  LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11966  /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11967  /*EllipsisLoc*/C.isPackExpansion()
11968  ? C.getEllipsisLoc() : SourceLocation(),
11969  CaptureType, /*Expr*/ nullptr);
11970 
11971  } else if (C.capturesThis()) {
11972  LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11973  /*Expr*/ nullptr,
11974  C.getCaptureKind() == LCK_StarThis);
11975  } else {
11976  LSI->addVLATypeCapture(C.getLocation(), I->getType());
11977  }
11978  ++I;
11979  }
11980 }
11981 
11983  SkipBodyInfo *SkipBody) {
11984  if (!D)
11985  return D;
11986  FunctionDecl *FD = nullptr;
11987 
11988  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11989  FD = FunTmpl->getTemplatedDecl();
11990  else
11991  FD = cast<FunctionDecl>(D);
11992 
11993  // Check for defining attributes before the check for redefinition.
11994  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11995  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11996  FD->dropAttr<AliasAttr>();
11997  FD->setInvalidDecl();
11998  }
11999  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12000  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12001  FD->dropAttr<IFuncAttr>();
12002  FD->setInvalidDecl();
12003  }
12004 
12005  // See if this is a redefinition. If 'will have body' is already set, then
12006  // these checks were already performed when it was set.
12007  if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12008  CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12009 
12010  // If we're skipping the body, we're done. Don't enter the scope.
12011  if (SkipBody && SkipBody->ShouldSkip)
12012  return D;
12013  }
12014 
12015  // Mark this function as "will have a body eventually". This lets users to
12016  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12017  // this function.
12018  FD->setWillHaveBody();
12019 
12020  // If we are instantiating a generic lambda call operator, push
12021  // a LambdaScopeInfo onto the function stack. But use the information
12022  // that's already been calculated (ActOnLambdaExpr) to prime the current
12023  // LambdaScopeInfo.
12024  // When the template operator is being specialized, the LambdaScopeInfo,
12025  // has to be properly restored so that tryCaptureVariable doesn't try
12026  // and capture any new variables. In addition when calculating potential
12027  // captures during transformation of nested lambdas, it is necessary to
12028  // have the LSI properly restored.
12030  assert(inTemplateInstantiation() &&
12031  "There should be an active template instantiation on the stack "
12032  "when instantiating a generic lambda!");
12033  RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12034  } else {
12035  // Enter a new function scope
12036  PushFunctionScope();
12037  }
12038 
12039  // Builtin functions cannot be defined.
12040  if (unsigned BuiltinID = FD->getBuiltinID()) {
12041  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12042  !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12043  Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12044  FD->setInvalidDecl();
12045  }
12046  }
12047 
12048  // The return type of a function definition must be complete
12049  // (C99 6.9.1p3, C++ [dcl.fct]p6).
12050  QualType ResultType = FD->getReturnType();
12051  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12052  !FD->isInvalidDecl() &&
12053  RequireCompleteType(FD->getLocation(), ResultType,
12054  diag::err_func_def_incomplete_result))
12055  FD->setInvalidDecl();
12056 
12057  if (FnBodyScope)
12058  PushDeclContext(FnBodyScope, FD);
12059 
12060  // Check the validity of our function parameters
12061  CheckParmsForFunctionDef(FD->parameters(),
12062  /*CheckParameterNames=*/true);
12063 
12064  // Add non-parameter declarations already in the function to the current
12065  // scope.
12066  if (FnBodyScope) {
12067  for (Decl *NPD : FD->decls()) {
12068  auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12069  if (!NonParmDecl)
12070  continue;
12071  assert(!isa<ParmVarDecl>(NonParmDecl) &&
12072  "parameters should not be in newly created FD yet");
12073 
12074  // If the decl has a name, make it accessible in the current scope.
12075  if (NonParmDecl->getDeclName())
12076  PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12077 
12078  // Similarly, dive into enums and fish their constants out, making them
12079  // accessible in this scope.
12080  if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12081  for (auto *EI : ED->enumerators())
12082  PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12083  }
12084  }
12085  }
12086 
12087  // Introduce our parameters into the function scope
12088  for (auto Param : FD->parameters()) {
12089  Param->setOwningFunction(FD);
12090 
12091  // If this has an identifier, add it to the scope stack.
12092  if (Param->getIdentifier() && FnBodyScope) {
12093  CheckShadow(FnBodyScope, Param);
12094 
12095  PushOnScopeChains(Param, FnBodyScope);
12096  }
12097  }
12098 
12099  // Ensure that the function's exception specification is instantiated.
12100  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12101  ResolveExceptionSpec(D->getLocation(), FPT);
12102 
12103  // dllimport cannot be applied to non-inline function definitions.
12104  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12105  !FD->isTemplateInstantiation()) {
12106  assert(!FD->hasAttr<DLLExportAttr>());
12107  Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12108  FD->setInvalidDecl();
12109  return D;
12110  }
12111  // We want to attach documentation to original Decl (which might be
12112  // a function template).
12113  ActOnDocumentableDecl(D);
12114  if (getCurLexicalContext()->isObjCContainer() &&
12115  getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12116  getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12117  Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12118 
12119  return D;
12120 }
12121 
12122 /// \brief Given the set of return statements within a function body,
12123 /// compute the variables that are subject to the named return value
12124 /// optimization.
12125 ///
12126 /// Each of the variables that is subject to the named return value
12127 /// optimization will be marked as NRVO variables in the AST, and any
12128 /// return statement that has a marked NRVO variable as its NRVO candidate can
12129 /// use the named return value optimization.
12130 ///
12131 /// This function applies a very simplistic algorithm for NRVO: if every return
12132 /// statement in the scope of a variable has the same NRVO candidate, that
12133 /// candidate is an NRVO variable.
12135  ReturnStmt **Returns = Scope->Returns.data();
12136 
12137  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12138  if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12139  if (!NRVOCandidate->isNRVOVariable())
12140  Returns[I]->setNRVOCandidate(nullptr);
12141  }
12142  }
12143 }
12144 
12146  // We can't delay parsing the body of a constexpr function template (yet).
12148  return false;
12149 
12150  // We can't delay parsing the body of a function template with a deduced
12151  // return type (yet).
12152  if (D.getDeclSpec().hasAutoTypeSpec()) {
12153  // If the placeholder introduces a non-deduced trailing return type,
12154  // we can still delay parsing it.
12155  if (D.getNumTypeObjects()) {
12156  const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12157  if (Outer.Kind == DeclaratorChunk::Function &&
12158  Outer.Fun.hasTrailingReturnType()) {
12159  QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12160  return Ty.isNull() || !Ty->isUndeducedType();
12161  }
12162  }
12163  return false;
12164  }
12165 
12166  return true;
12167 }
12168 
12170  // We cannot skip the body of a function (or function template) which is
12171  // constexpr, since we may need to evaluate its body in order to parse the
12172  // rest of the file.
12173  // We cannot skip the body of a function with an undeduced return type,
12174  // because any callers of that function need to know the type.
12175  if (const FunctionDecl *FD = D->getAsFunction())
12176  if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12177  return false;
12178  return Consumer.shouldSkipFunctionBody(D);
12179 }
12180 
12182  if (!Decl)
12183  return nullptr;
12184  if (FunctionDecl *FD = Decl->getAsFunction())
12185  FD->setHasSkippedBody();
12186  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12187  MD->setHasSkippedBody();
12188  return Decl;
12189 }
12190 
12192  return ActOnFinishFunctionBody(D, BodyArg, false);
12193 }
12194 
12196  bool IsInstantiation) {
12197  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12198 
12199  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12200  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12201 
12202  if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12203  CheckCompletedCoroutineBody(FD, Body);
12204 
12205  if (FD) {
12206  FD->setBody(Body);
12207  FD->setWillHaveBody(false);
12208 
12209  if (getLangOpts().CPlusPlus14) {
12210  if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12211  FD->getReturnType()->isUndeducedType()) {
12212  // If the function has a deduced result type but contains no 'return'
12213  // statements, the result type as written must be exactly 'auto', and
12214  // the deduced result type is 'void'.
12215  if (!FD->getReturnType()->getAs<AutoType>()) {
12216  Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12217  << FD->getReturnType();
12218  FD->setInvalidDecl();
12219  } else {
12220  // Substitute 'void' for the 'auto' in the type.
12221  TypeLoc ResultType = getReturnTypeLoc(FD);
12223  FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12224  }
12225  }
12226  } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12227  // In C++11, we don't use 'auto' deduction rules for lambda call
12228  // operators because we don't support return type deduction.
12229  auto *LSI = getCurLambda();
12230  if (LSI->HasImplicitReturnType) {
12231  deduceClosureReturnType(*LSI);
12232 
12233  // C++11 [expr.prim.lambda]p4:
12234  // [...] if there are no return statements in the compound-statement
12235  // [the deduced type is] the type void
12236  QualType RetType =
12237  LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12238 
12239  // Update the return type to the deduced type.
12240  const FunctionProtoType *Proto =
12241  FD->getType()->getAs<FunctionProtoType>();
12242  FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12243  Proto->getExtProtoInfo()));
12244  }
12245  }
12246 
12247  // If the function implicitly returns zero (like 'main') or is naked,
12248  // don't complain about missing return statements.
12249  if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12251 
12252  // MSVC permits the use of pure specifier (=0) on function definition,
12253  // defined at class scope, warn about this non-standard construct.
12254  if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12255  Diag(FD->getLocation(), diag::ext_pure_function_definition);
12256 
12257  if (!FD->isInvalidDecl()) {
12258  // Don't diagnose unused parameters of defaulted or deleted functions.
12259  if (!FD->isDeleted() && !FD->isDefaulted())
12260  DiagnoseUnusedParameters(FD->parameters());
12261  DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12262  FD->getReturnType(), FD);
12263 
12264  // If this is a structor, we need a vtable.
12265  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12266  MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12267  else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12268  MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12269 
12270  // Try to apply the named return value optimization. We have to check
12271  // if we can do this here because lambdas keep return statements around
12272  // to deduce an implicit return type.
12273  if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12274  !FD->isDependentContext())
12275  computeNRVO(Body, getCurFunction());
12276  }
12277 
12278  // GNU warning -Wmissing-prototypes:
12279  // Warn if a global function is defined without a previous
12280  // prototype declaration. This warning is issued even if the
12281  // definition itself provides a prototype. The aim is to detect
12282  // global functions that fail to be declared in header files.
12283  const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12284  if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12285  Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12286 
12287  if (PossibleZeroParamPrototype) {
12288  // We found a declaration that is not a prototype,
12289  // but that could be a zero-parameter prototype
12290  if (TypeSourceInfo *TI =
12291  PossibleZeroParamPrototype->getTypeSourceInfo()) {
12292  TypeLoc TL = TI->getTypeLoc();
12294  Diag(PossibleZeroParamPrototype->getLocation(),
12295  diag::note_declaration_not_a_prototype)
12296  << PossibleZeroParamPrototype
12297  << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12298  }
12299  }
12300 
12301  // GNU warning -Wstrict-prototypes
12302  // Warn if K&R function is defined without a previous declaration.
12303  // This warning is issued only if the definition itself does not provide
12304  // a prototype. Only K&R definitions do not provide a prototype.
12305  // An empty list in a function declarator that is part of a definition
12306  // of that function specifies that the function has no parameters
12307  // (C99 6.7.5.3p14)
12308  if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12309  !LangOpts.CPlusPlus) {
12310  TypeSourceInfo *TI = FD->getTypeSourceInfo();
12311  TypeLoc TL = TI->getTypeLoc();
12313  Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12314  }
12315  }
12316 
12317  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12318  const CXXMethodDecl *KeyFunction;
12319  if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12320  MD->isVirtual() &&
12321  (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12322  MD == KeyFunction->getCanonicalDecl()) {
12323  // Update the key-function state if necessary for this ABI.
12324  if (FD->isInlined() &&
12326  Context.setNonKeyFunction(MD);
12327 
12328  // If the newly-chosen key function is already defined, then we
12329  // need to mark the vtable as used retroactively.
12330  KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12331  const FunctionDecl *Definition;
12332  if (KeyFunction && KeyFunction->isDefined(Definition))
12333  MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12334  } else {
12335  // We just defined they key function; mark the vtable as used.
12336  MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12337  }
12338  }
12339  }
12340 
12341  assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12342  "Function parsing confused");
12343  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12344  assert(MD == getCurMethodDecl() && "Method parsing confused");
12345  MD->setBody(Body);
12346  if (!MD->isInvalidDecl()) {
12347  DiagnoseUnusedParameters(MD->parameters());
12348  DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12349  MD->getReturnType(), MD);
12350 
12351  if (Body)
12352  computeNRVO(Body, getCurFunction());
12353  }
12354  if (getCurFunction()->ObjCShouldCallSuper) {
12355  Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12356  << MD->getSelector().getAsString();
12357  getCurFunction()->ObjCShouldCallSuper = false;
12358  }
12359  if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12360  const ObjCMethodDecl *InitMethod = nullptr;
12361  bool isDesignated =
12362  MD->isDesignatedInitializerForTheInterface(&InitMethod);
12363  assert(isDesignated && InitMethod);
12364  (void)isDesignated;
12365 
12366  auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12367  auto IFace = MD->getClassInterface();
12368  if (!IFace)
12369  return false;
12370  auto SuperD = IFace->getSuperClass();
12371  if (!SuperD)
12372  return false;
12373  return SuperD->getIdentifier() ==
12374  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12375  };
12376  // Don't issue this warning for unavailable inits or direct subclasses
12377  // of NSObject.
12378  if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12379  Diag(MD->getLocation(),
12380  diag::warn_objc_designated_init_missing_super_call);
12381  Diag(InitMethod->getLocation(),
12382  diag::note_objc_designated_init_marked_here);
12383  }
12384  getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12385  }
12386  if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12387  // Don't issue this warning for unavaialable inits.
12388  if (!MD->isUnavailable())
12389  Diag(MD->getLocation(),
12390  diag::warn_objc_secondary_init_missing_init_call);
12391  getCurFunction()->ObjCWarnForNoInitDelegation = false;
12392  }
12393  } else {
12394  return nullptr;
12395  }
12396 
12397  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12398  DiagnoseUnguardedAvailabilityViolations(dcl);
12399 
12400  assert(!getCurFunction()->ObjCShouldCallSuper &&
12401  "This should only be set for ObjC methods, which should have been "
12402  "handled in the block above.");
12403 
12404  // Verify and clean out per-function state.
12405  if (Body && (!FD || !FD->isDefaulted())) {
12406  // C++ constructors that have function-try-blocks can't have return
12407  // statements in the handlers of that block. (C++ [except.handle]p14)
12408  // Verify this.
12409  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12410  DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12411 
12412  // Verify that gotos and switch cases don't jump into scopes illegally.
12413  if (getCurFunction()->NeedsScopeChecking() &&
12414  !PP.isCodeCompletionEnabled())
12415  DiagnoseInvalidJumps(Body);
12416 
12417  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12418  if (!Destructor->getParent()->isDependentType())
12419  CheckDestructor(Destructor);
12420 
12421  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12422  Destructor->getParent());
12423  }
12424 
12425  // If any errors have occurred, clear out any temporaries that may have
12426  // been leftover. This ensures that these temporaries won't be picked up for
12427  // deletion in some later function.
12428  if (getDiagnostics().hasErrorOccurred() ||
12429  getDiagnostics().getSuppressAllDiagnostics()) {
12430  DiscardCleanupsInEvaluationContext();
12431  }
12432  if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12433  !isa<FunctionTemplateDecl>(dcl)) {
12434  // Since the body is valid, issue any analysis-based warnings that are
12435  // enabled.
12436  ActivePolicy = &WP;
12437  }
12438 
12439  if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12440  (!CheckConstexprFunctionDecl(FD) ||
12441  !CheckConstexprFunctionBody(FD, Body)))
12442  FD->setInvalidDecl();
12443 
12444  if (FD && FD->hasAttr<NakedAttr>()) {
12445  for (const Stmt *S : Body->children()) {
12446  // Allow local register variables without initializer as they don't
12447  // require prologue.
12448  bool RegisterVariables = false;
12449  if (auto *DS = dyn_cast<DeclStmt>(S)) {
12450  for (const auto *Decl : DS->decls()) {
12451  if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12452  RegisterVariables =
12453  Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12454  if (!RegisterVariables)
12455  break;
12456  }
12457  }
12458  }
12459  if (RegisterVariables)
12460  continue;
12461  if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12462  Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12463  Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12464  FD->setInvalidDecl();
12465  break;
12466  }
12467  }
12468  }
12469 
12470  assert(ExprCleanupObjects.size() ==
12471  ExprEvalContexts.back().NumCleanupObjects &&
12472  "Leftover temporaries in function");
12473  assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12474  assert(MaybeODRUseExprs.empty() &&
12475  "Leftover expressions for odr-use checking");
12476  }
12477 
12478  if (!IsInstantiation)
12479  PopDeclContext();
12480 
12481  PopFunctionScopeInfo(ActivePolicy, dcl);
12482  // If any errors have occurred, clear out any temporaries that may have
12483  // been leftover. This ensures that these temporaries won't be picked up for
12484  // deletion in some later function.
12485  if (getDiagnostics().hasErrorOccurred()) {
12486  DiscardCleanupsInEvaluationContext();
12487  }
12488 
12489  return dcl;
12490 }
12491 
12492 /// When we finish delayed parsing of an attribute, we must attach it to the
12493 /// relevant Decl.
12495  ParsedAttributes &Attrs) {
12496  // Always attach attributes to the underlying decl.
12497  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12498  D = TD->getTemplatedDecl();
12499  ProcessDeclAttributeList(S, D, Attrs.getList());
12500 
12501  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12502  if (Method->isStatic())
12503  checkThisInStaticMemberFunctionAttributes(Method);
12504 }
12505 
12506 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12507 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12509  IdentifierInfo &II, Scope *S) {
12510  Scope *BlockScope = S;
12511  while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12512  BlockScope = BlockScope->getParent();
12513 
12514  // Before we produce a declaration for an implicitly defined
12515  // function, see whether there was a locally-scoped declaration of
12516  // this name as a function or variable. If so, use that
12517  // (non-visible) declaration, and complain about it.
12518  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12519  if (ExternCPrev) {
12520  // We still need to inject the function into the enclosing block scope so
12521  // that later (non-call) uses can see it.
12522  PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12523 
12524  // C89 footnote 38:
12525  // If in fact it is not defined as having type "function returning int",
12526  // the behavior is undefined.
12527  if (!isa<FunctionDecl>(ExternCPrev) ||
12528  !Context.typesAreCompatible(
12529  cast<FunctionDecl>(ExternCPrev)->getType(),
12530  Context.getFunctionNoProtoType(Context.IntTy))) {
12531  Diag(Loc, diag::ext_use_out_of_scope_declaration)
12532  << ExternCPrev << !getLangOpts().C99;
12533  Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12534  return ExternCPrev;
12535  }
12536  }
12537 
12538  // Extension in C99. Legal in C90, but warn about it.
12539  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12540  unsigned diag_id;
12541  if (II.getName().startswith("__builtin_"))
12542  diag_id = diag::warn_builtin_unknown;
12543  else if (getLangOpts().C99 || getLangOpts().OpenCL)
12544  diag_id = diag::ext_implicit_function_decl;
12545  else
12546  diag_id = diag::warn_implicit_function_decl;
12547  Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
12548 
12549  // If we found a prior declaration of this function, don't bother building
12550  // another one. We've already pushed that one into scope, so there's nothing
12551  // more to do.
12552  if (ExternCPrev)
12553  return ExternCPrev;
12554 
12555  // Because typo correction is expensive, only do it if the implicit
12556  // function declaration is going to be treated as an error.
12557  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12558  TypoCorrection Corrected;
12559  if (S &&
12560  (Corrected = CorrectTypo(
12561  DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12562  llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12563  diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12564  /*ErrorRecovery*/false);
12565  }
12566 
12567  // Set a Declarator for the implicit definition: int foo();
12568  const char *Dummy;
12569  AttributeFactory attrFactory;
12570  DeclSpec DS(attrFactory);
12571  unsigned DiagID;
12572  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12573  Context.getPrintingPolicy());
12574  (void)Error; // Silence warning.
12575  assert(!Error && "Error setting up implicit decl!");
12576  SourceLocation NoLoc;
12578  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12579  /*IsAmbiguous=*/false,
12580  /*LParenLoc=*/NoLoc,
12581  /*Params=*/nullptr,
12582  /*NumParams=*/0,
12583  /*EllipsisLoc=*/NoLoc,
12584  /*RParenLoc=*/NoLoc,
12585  /*TypeQuals=*/0,
12586  /*RefQualifierIsLvalueRef=*/true,
12587  /*RefQualifierLoc=*/NoLoc,
12588  /*ConstQualifierLoc=*/NoLoc,
12589  /*VolatileQualifierLoc=*/NoLoc,
12590  /*RestrictQualifierLoc=*/NoLoc,
12591  /*MutableLoc=*/NoLoc,
12592  EST_None,
12593  /*ESpecRange=*/SourceRange(),
12594  /*Exceptions=*/nullptr,
12595  /*ExceptionRanges=*/nullptr,
12596  /*NumExceptions=*/0,
12597  /*NoexceptExpr=*/nullptr,
12598  /*ExceptionSpecTokens=*/nullptr,
12599  /*DeclsInPrototype=*/None,
12600  Loc, Loc, D),
12601  DS.getAttributes(),
12602  SourceLocation());
12603  D.SetIdentifier(&II, Loc);
12604 
12605  // Insert this function into the enclosing block scope.
12606  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
12607  FD->setImplicit();
12608 
12609  AddKnownFunctionAttributes(FD);
12610 
12611  return FD;
12612 }
12613 
12614 /// \brief Adds any function attributes that we know a priori based on
12615 /// the declaration of this function.
12616 ///
12617 /// These attributes can apply both to implicitly-declared builtins
12618 /// (like __builtin___printf_chk) or to library-declared functions
12619 /// like NSLog or printf.
12620 ///
12621 /// We need to check for duplicate attributes both here and where user-written
12622 /// attributes are applied to declarations.
12624  if (FD->isInvalidDecl())
12625  return;
12626 
12627  // If this is a built-in function, map its builtin attributes to
12628  // actual attributes.
12629  if (unsigned BuiltinID = FD->getBuiltinID()) {
12630  // Handle printf-formatting attributes.
12631  unsigned FormatIdx;
12632  bool HasVAListArg;
12633  if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12634  if (!FD->hasAttr<FormatAttr>()) {
12635  const char *fmt = "printf";
12636  unsigned int NumParams = FD->getNumParams();
12637  if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12638  FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12639  fmt = "NSString";
12640  FD->addAttr(FormatAttr::CreateImplicit(Context,
12641  &Context.Idents.get(fmt),
12642  FormatIdx+1,
12643  HasVAListArg ? 0 : FormatIdx+2,
12644  FD->getLocation()));
12645  }
12646  }
12647  if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12648  HasVAListArg)) {
12649  if (!FD->hasAttr<FormatAttr>())
12650  FD->addAttr(FormatAttr::CreateImplicit(Context,
12651  &Context.Idents.get("scanf"),
12652  FormatIdx+1,
12653  HasVAListArg ? 0 : FormatIdx+2,
12654  FD->getLocation()));
12655  }
12656 
12657  // Mark const if we don't care about errno and that is the only thing
12658  // preventing the function from being const. This allows IRgen to use LLVM
12659  // intrinsics for such functions.
12660  if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
12661  Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
12662  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12663 
12664  // We make "fma" on GNU or Windows const because we know it does not set
12665  // errno in those environments even though it could set errno based on the
12666  // C standard.
12667  const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
12668  if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
12669  !FD->hasAttr<ConstAttr>()) {
12670  switch (BuiltinID) {
12671  case Builtin::BI__builtin_fma:
12672  case Builtin::BI__builtin_fmaf:
12673  case Builtin::BI__builtin_fmal:
12674  case Builtin::BIfma:
12675  case Builtin::BIfmaf:
12676  case Builtin::BIfmal:
12677  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12678  break;
12679  default:
12680  break;
12681  }
12682  }
12683 
12684  if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12685  !FD->hasAttr<ReturnsTwiceAttr>())
12686  FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12687  FD->getLocation()));
12688  if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12689  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12690  if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12691  FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12692  if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12693  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12694  if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12695  !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12696  // Add the appropriate attribute, depending on the CUDA compilation mode
12697  // and which target the builtin belongs to. For example, during host
12698  // compilation, aux builtins are __device__, while the rest are __host__.
12699  if (getLangOpts().CUDAIsDevice !=
12700  Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12701  FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12702  else
12703  FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12704  }
12705  }
12706 
12707  // If C++ exceptions are enabled but we are told extern "C" functions cannot
12708  // throw, add an implicit nothrow attribute to any extern "C" function we come
12709  // across.
12710  if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12711  FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12712  const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12713  if (!FPT || FPT->getExceptionSpecType() == EST_None)
12714  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12715  }
12716 
12717  IdentifierInfo *Name = FD->getIdentifier();
12718  if (!Name)
12719  return;
12720  if ((!getLangOpts().CPlusPlus &&
12721  FD->getDeclContext()->isTranslationUnit()) ||
12722  (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12723  cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12725  // Okay: this could be a libc/libm/Objective-C function we know
12726  // about.
12727  } else
12728  return;
12729 
12730  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12731  // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12732  // target-specific builtins, perhaps?
12733  if (!FD->hasAttr<FormatAttr>())
12734  FD->addAttr(FormatAttr::CreateImplicit(Context,
12735  &Context.Idents.get("printf"), 2,
12736  Name->isStr("vasprintf") ? 0 : 3,
12737  FD->getLocation()));
12738  }
12739 
12740  if (Name->isStr("__CFStringMakeConstantString")) {
12741  // We already have a __builtin___CFStringMakeConstantString,
12742  // but builds that use -fno-constant-cfstrings don't go through that.
12743  if (!FD->hasAttr<FormatArgAttr>())
12744  FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12745  FD->getLocation()));
12746  }
12747 }
12748 
12750  TypeSourceInfo *TInfo) {
12751  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12752  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12753 
12754  if (!TInfo) {
12755  assert(D.isInvalidType() && "no declarator info for valid type");
12756  TInfo = Context.getTrivialTypeSourceInfo(T);
12757  }
12758 
12759  // Scope manipulation handled by caller.
12760  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12761  D.getLocStart(),
12762  D.getIdentifierLoc(),
12763  D.getIdentifier(),
12764  TInfo);
12765 
12766  // Bail out immediately if we have an invalid declaration.
12767  if (D.isInvalidType()) {
12768  NewTD->setInvalidDecl();
12769  return NewTD;
12770  }
12771 
12773  if (CurContext->isFunctionOrMethod())
12774  Diag(NewTD->getLocation(), diag::err_module_private_local)
12775  << 2 << NewTD->getDeclName()
12778  else
12779  NewTD->setModulePrivate();
12780  }
12781 
12782  // C++ [dcl.typedef]p8:
12783  // If the typedef declaration defines an unnamed class (or
12784  // enum), the first typedef-name declared by the declaration
12785  // to be that class type (or enum type) is used to denote the
12786  // class type (or enum type) for linkage purposes only.
12787  // We need to check whether the type was declared in the declaration.
12788  switch (D.getDeclSpec().getTypeSpecType()) {
12789  case TST_enum:
12790  case TST_struct:
12791  case TST_interface:
12792  case TST_union:
12793  case TST_class: {
12794  TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12795  setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12796  break;
12797  }
12798 
12799  default:
12800  break;
12801  }
12802 
12803  return NewTD;
12804 }
12805 
12806 /// \brief Check that this is a valid underlying type for an enum declaration.
12808  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12809  QualType T = TI->getType();
12810 
12811  if (T->isDependentType())
12812  return false;
12813 
12814  if (const BuiltinType *BT = T->getAs<BuiltinType>())
12815  if (BT->isInteger())
12816  return false;
12817 
12818  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12819  return true;
12820 }
12821 
12822 /// Check whether this is a valid redeclaration of a previous enumeration.
12823 /// \return true if the redeclaration was invalid.
12825  SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12826  bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12827  bool IsFixed = !EnumUnderlyingTy.isNull();
12828 
12829  if (IsScoped != Prev->isScoped()) {
12830  Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12831  << Prev->isScoped();
12832  Diag(Prev->getLocation(), diag::note_previous_declaration);
12833  return true;
12834  }
12835 
12836  if (IsFixed && Prev->isFixed()) {
12837  if (!EnumUnderlyingTy->isDependentType() &&
12838  !Prev->getIntegerType()->isDependentType() &&
12839  !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12840  Prev->getIntegerType())) {
12841  // TODO: Highlight the underlying type of the redeclaration.
12842  Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12843  << EnumUnderlyingTy << Prev->getIntegerType();
12844  Diag(Prev->getLocation(), diag::note_previous_declaration)
12845  << Prev->getIntegerTypeRange();
12846  return true;
12847  }
12848  } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12849  ;
12850  } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12851  ;
12852  } else if (IsFixed != Prev->isFixed()) {
12853  Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12854  << Prev->isFixed();
12855  Diag(Prev->getLocation(), diag::note_previous_declaration);
12856  return true;
12857  }
12858 
12859  return false;
12860 }
12861 
12862 /// \brief Get diagnostic %select index for tag kind for
12863 /// redeclaration diagnostic message.
12864 /// WARNING: Indexes apply to particular diagnostics only!
12865 ///
12866 /// \returns diagnostic %select index.
12868  switch (Tag) {
12869  case TTK_Struct: return 0;
12870  case TTK_Interface: return 1;
12871  case TTK_Class: return 2;
12872  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12873  }
12874 }
12875 
12876 /// \brief Determine if tag kind is a class-key compatible with
12877 /// class for redeclaration (class, struct, or __interface).
12878 ///
12879 /// \returns true iff the tag kind is compatible.
12881 {
12882  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12883 }
12884 
12886  TagTypeKind TTK) {
12887  if (isa<TypedefDecl>(PrevDecl))
12888  return NTK_Typedef;
12889  else if (isa<TypeAliasDecl>(PrevDecl))
12890  return NTK_TypeAlias;
12891  else if (isa<ClassTemplateDecl>(PrevDecl))
12892  return NTK_Template;
12893  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12894  return NTK_TypeAliasTemplate;
12895  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12896  return NTK_TemplateTemplateArgument;
12897  switch (TTK) {
12898  case TTK_Struct:
12899  case TTK_Interface:
12900  case TTK_Class:
12901  return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12902  case TTK_Union:
12903  return NTK_NonUnion;
12904  case TTK_Enum:
12905  return NTK_NonEnum;
12906  }
12907  llvm_unreachable("invalid TTK");
12908 }
12909 
12910 /// \brief Determine whether a tag with a given kind is acceptable
12911 /// as a redeclaration of the given tag declaration.
12912 ///
12913 /// \returns true if the new tag kind is acceptable, false otherwise.
12915  TagTypeKind NewTag, bool isDefinition,
12916  SourceLocation NewTagLoc,
12917  const IdentifierInfo *Name) {
12918  // C++ [dcl.type.elab]p3:
12919  // The class-key or enum keyword present in the
12920  // elaborated-type-specifier shall agree in kind with the
12921  // declaration to which the name in the elaborated-type-specifier
12922  // refers. This rule also applies to the form of
12923  // elaborated-type-specifier that declares a class-name or
12924  // friend class since it can be construed as referring to the
12925  // definition of the class. Thus, in any
12926  // elaborated-type-specifier, the enum keyword shall be used to
12927  // refer to an enumeration (7.2), the union class-key shall be
12928  // used to refer to a union (clause 9), and either the class or
12929  // struct class-key shall be used to refer to a class (clause 9)
12930  // declared using the class or struct class-key.
12931  TagTypeKind OldTag = Previous->getTagKind();
12932  if (!isDefinition || !isClassCompatTagKind(NewTag))
12933  if (OldTag == NewTag)
12934  return true;
12935 
12936  if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12937  // Warn about the struct/class tag mismatch.
12938  bool isTemplate = false;
12939  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12940  isTemplate = Record->getDescribedClassTemplate();
12941 
12942  if (inTemplateInstantiation()) {
12943  // In a template instantiation, do not offer fix-its for tag mismatches
12944  // since they usually mess up the template instead of fixing the problem.
12945  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12946  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12947  << getRedeclDiagFromTagKind(OldTag);
12948  return true;
12949  }
12950 
12951  if (isDefinition) {
12952  // On definitions, check previous tags and issue a fix-it for each
12953  // one that doesn't match the current tag.
12954  if (Previous->getDefinition()) {
12955  // Don't suggest fix-its for redefinitions.
12956  return true;
12957  }
12958 
12959  bool previousMismatch = false;
12960  for (auto I : Previous->redecls()) {
12961  if (I->getTagKind() != NewTag) {
12962  if (!previousMismatch) {
12963  previousMismatch = true;
12964  Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12965  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12966  << getRedeclDiagFromTagKind(I->getTagKind());
12967  }
12968  Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12969  << getRedeclDiagFromTagKind(NewTag)
12970  << FixItHint::CreateReplacement(I->getInnerLocStart(),
12972  }
12973  }
12974  return true;
12975  }
12976 
12977  // Check for a previous definition. If current tag and definition
12978  // are same type, do nothing. If no definition, but disagree with
12979  // with previous tag type, give a warning, but no fix-it.
12980  const TagDecl *Redecl = Previous->getDefinition() ?
12981  Previous->getDefinition() : Previous;
12982  if (Redecl->getTagKind() == NewTag) {
12983  return true;
12984  }
12985 
12986  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12987  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12988  << getRedeclDiagFromTagKind(OldTag);
12989  Diag(Redecl->getLocation(), diag::note_previous_use);
12990 
12991  // If there is a previous definition, suggest a fix-it.
12992  if (Previous->getDefinition()) {
12993  Diag(NewTagLoc, diag::note_struct_class_suggestion)
12994  << getRedeclDiagFromTagKind(Redecl->getTagKind())
12997  }
12998 
12999  return true;
13000  }
13001  return false;
13002 }
13003 
13004 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13005 /// from an outer enclosing namespace or file scope inside a friend declaration.
13006 /// This should provide the commented out code in the following snippet:
13007 /// namespace N {
13008 /// struct X;
13009 /// namespace M {
13010 /// struct Y { friend struct /*N::*/ X; };
13011 /// }
13012 /// }
13014  SourceLocation NameLoc) {
13015  // While the decl is in a namespace, do repeated lookup of that name and see
13016  // if we get the same namespace back. If we do not, continue until
13017  // translation unit scope, at which point we have a fully qualified NNS.
13020  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13021  // This tag should be declared in a namespace, which can only be enclosed by
13022  // other namespaces. Bail if there's an anonymous namespace in the chain.
13023  NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13024  if (!Namespace || Namespace->isAnonymousNamespace())
13025  return FixItHint();
13026  IdentifierInfo *II = Namespace->getIdentifier();
13027  Namespaces.push_back(II);
13028  NamedDecl *Lookup = SemaRef.LookupSingleName(
13029  S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13030  if (Lookup == Namespace)
13031  break;
13032  }
13033 
13034  // Once we have all the namespaces, reverse them to go outermost first, and
13035  // build an NNS.
13036  SmallString<64> Insertion;
13037  llvm::raw_svector_ostream OS(Insertion);
13038  if (DC->isTranslationUnit())
13039  OS << "::";
13040  std::reverse(Namespaces.begin(), Namespaces.end());
13041  for (auto *II : Namespaces)
13042  OS << II->getName() << "::";
13043  return FixItHint::CreateInsertion(NameLoc, Insertion);
13044 }
13045 
13046 /// \brief Determine whether a tag originally declared in context \p OldDC can
13047 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13048 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13049 /// using-declaration).
13051  DeclContext *NewDC) {
13052  OldDC = OldDC->getRedeclContext();
13053  NewDC = NewDC->getRedeclContext();
13054 
13055  if (OldDC->Equals(NewDC))
13056  return true;
13057 
13058  // In MSVC mode, we allow a redeclaration if the contexts are related (either
13059  // encloses the other).
13060  if (S.getLangOpts().MSVCCompat &&
13061  (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13062  return true;
13063 
13064  return false;
13065 }
13066 
13067 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
13068 /// former case, Name will be non-null. In the later case, Name will be null.
13069 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13070 /// reference/declaration/definition of a tag.
13071 ///
13072 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13073 /// trailing-type-specifier) other than one in an alias-declaration.
13074 ///
13075 /// \param SkipBody If non-null, will be set to indicate if the caller should
13076 /// skip the definition of this tag and treat it as if it were a declaration.
13077 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13078  SourceLocation KWLoc, CXXScopeSpec &SS,
13079  IdentifierInfo *Name, SourceLocation NameLoc,
13081  SourceLocation ModulePrivateLoc,
13082  MultiTemplateParamsArg TemplateParameterLists,
13083  bool &OwnedDecl, bool &IsDependent,
13084  SourceLocation ScopedEnumKWLoc,
13085  bool ScopedEnumUsesClassTag,
13086  TypeResult UnderlyingType,
13087  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13088  SkipBodyInfo *SkipBody) {
13089  // If this is not a definition, it must have a name.
13090  IdentifierInfo *OrigName = Name;
13091  assert((Name != nullptr || TUK == TUK_Definition) &&
13092  "Nameless record must be a definition!");
13093  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13094 
13095  OwnedDecl = false;
13097  bool ScopedEnum = ScopedEnumKWLoc.isValid();
13098 
13099  // FIXME: Check member specializations more carefully.
13100  bool isMemberSpecialization = false;
13101  bool Invalid = false;
13102 
13103  // We only need to do this matching if we have template parameters
13104  // or a scope specifier, which also conveniently avoids this work
13105  // for non-C++ cases.
13106  if (TemplateParameterLists.size() > 0 ||
13107  (SS.isNotEmpty() && TUK != TUK_Reference)) {
13108  if (TemplateParameterList *TemplateParams =
13109  MatchTemplateParametersToScopeSpecifier(
13110  KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13111  TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13112  if (Kind == TTK_Enum) {
13113  Diag(KWLoc, diag::err_enum_template);
13114  return nullptr;
13115  }
13116 
13117  if (TemplateParams->size() > 0) {
13118  // This is a declaration or definition of a class template (which may
13119  // be a member of another template).
13120 
13121  if (Invalid)
13122  return nullptr;
13123 
13124  OwnedDecl = false;
13125  DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13126  SS, Name, NameLoc, Attr,
13127  TemplateParams, AS,
13128  ModulePrivateLoc,
13129  /*FriendLoc*/SourceLocation(),
13130  TemplateParameterLists.size()-1,
13131  TemplateParameterLists.data(),
13132  SkipBody);
13133  return Result.get();
13134  } else {
13135  // The "template<>" header is extraneous.
13136  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13137  << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13138  isMemberSpecialization = true;
13139  }
13140  }
13141  }
13142 
13143  // Figure out the underlying type if this a enum declaration. We need to do
13144  // this early, because it's needed to detect if this is an incompatible
13145  // redeclaration.
13146  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13147  bool EnumUnderlyingIsImplicit = false;
13148 
13149  if (Kind == TTK_Enum) {
13150  if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13151  // No underlying type explicitly specified, or we failed to parse the
13152  // type, default to int.
13153  EnumUnderlying = Context.IntTy.getTypePtr();
13154  else if (UnderlyingType.get()) {
13155  // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13156  // integral type; any cv-qualification is ignored.
13157  TypeSourceInfo *TI = nullptr;
13158  GetTypeFromParser(UnderlyingType.get(), &TI);
13159  EnumUnderlying = TI;
13160 
13161  if (CheckEnumUnderlyingType(TI))
13162  // Recover by falling back to int.
13163  EnumUnderlying = Context.IntTy.getTypePtr();
13164 
13165  if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13166  UPPC_FixedUnderlyingType))
13167  EnumUnderlying = Context.IntTy.getTypePtr();
13168 
13169  } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13170  if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13171  // Microsoft enums are always of int type.
13172  EnumUnderlying = Context.IntTy.getTypePtr();
13173  EnumUnderlyingIsImplicit = true;
13174  }
13175  }
13176  }
13177 
13178  DeclContext *SearchDC = CurContext;
13179  DeclContext *DC = CurContext;
13180  bool isStdBadAlloc = false;
13181  bool isStdAlignValT = false;
13182 
13183  RedeclarationKind Redecl = forRedeclarationInCurContext();
13184  if (TUK == TUK_Friend || TUK == TUK_Reference)
13185  Redecl = NotForRedeclaration;
13186 
13187  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13188  /// implemented asks for structural equivalence checking, the returned decl
13189  /// here is passed back to the parser, allowing the tag body to be parsed.
13190  auto createTagFromNewDecl = [&]() -> TagDecl * {
13191  assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13192  // If there is an identifier, use the location of the identifier as the
13193  // location of the decl, otherwise use the location of the struct/union
13194  // keyword.
13195  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13196  TagDecl *New = nullptr;
13197 
13198  if (Kind == TTK_Enum) {
13199  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13200  ScopedEnum, ScopedEnumUsesClassTag,
13201  !EnumUnderlying.isNull());
13202  // If this is an undefined enum, bail.
13203  if (TUK != TUK_Definition && !Invalid)
13204  return nullptr;
13205  if (EnumUnderlying) {
13206  EnumDecl *ED = cast<EnumDecl>(New);
13207  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13208  ED->setIntegerTypeSourceInfo(TI);
13209  else
13210  ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13211  ED->setPromotionType(ED->getIntegerType());
13212  }
13213  } else { // struct/union
13214  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13215  nullptr);
13216  }
13217 
13218  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13219  // Add alignment attributes if necessary; these attributes are checked
13220  // when the ASTContext lays out the structure.
13221  //
13222  // It is important for implementing the correct semantics that this
13223  // happen here (in ActOnTag). The #pragma pack stack is
13224  // maintained as a result of parser callbacks which can occur at
13225  // many points during the parsing of a struct declaration (because
13226  // the #pragma tokens are effectively skipped over during the
13227  // parsing of the struct).
13228  if (TUK == TUK_Definition) {
13229  AddAlignmentAttributesForRecord(RD);
13230  AddMsStructLayoutForRecord(RD);
13231  }
13232  }
13233  New->setLexicalDeclContext(CurContext);
13234  return New;
13235  };
13236 
13237  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13238  if (Name && SS.isNotEmpty()) {
13239  // We have a nested-name tag ('struct foo::bar').
13240 
13241  // Check for invalid 'foo::'.
13242  if (SS.isInvalid()) {
13243  Name = nullptr;
13244  goto CreateNewDecl;
13245  }
13246 
13247  // If this is a friend or a reference to a class in a dependent
13248  // context, don't try to make a decl for it.
13249  if (TUK == TUK_Friend || TUK == TUK_Reference) {
13250  DC = computeDeclContext(SS, false);
13251  if (!DC) {
13252  IsDependent = true;
13253  return nullptr;
13254  }
13255  } else {
13256  DC = computeDeclContext(SS, true);
13257  if (!DC) {
13258  Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13259  << SS.getRange();
13260  return nullptr;
13261  }
13262  }
13263 
13264  if (RequireCompleteDeclContext(SS, DC))
13265  return nullptr;
13266 
13267  SearchDC = DC;
13268  // Look-up name inside 'foo::'.
13269  LookupQualifiedName(Previous, DC);
13270 
13271  if (Previous.isAmbiguous())
13272  return nullptr;
13273 
13274  if (Previous.empty()) {
13275  // Name lookup did not find anything. However, if the
13276  // nested-name-specifier refers to the current instantiation,
13277  // and that current instantiation has any dependent base
13278  // classes, we might find something at instantiation time: treat
13279  // this as a dependent elaborated-type-specifier.
13280  // But this only makes any sense for reference-like lookups.
13281  if (Previous.wasNotFoundInCurrentInstantiation() &&
13282  (TUK == TUK_Reference || TUK == TUK_Friend)) {
13283  IsDependent = true;
13284  return nullptr;
13285  }
13286 
13287  // A tag 'foo::bar' must already exist.
13288  Diag(NameLoc, diag::err_not_tag_in_scope)
13289  << Kind << Name << DC << SS.getRange();
13290  Name = nullptr;
13291  Invalid = true;
13292  goto CreateNewDecl;
13293  }
13294  } else if (Name) {
13295  // C++14 [class.mem]p14:
13296  // If T is the name of a class, then each of the following shall have a
13297  // name different from T:
13298  // -- every member of class T that is itself a type
13299  if (TUK != TUK_Reference && TUK != TUK_Friend &&
13300  DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13301  return nullptr;
13302 
13303  // If this is a named struct, check to see if there was a previous forward
13304  // declaration or definition.
13305  // FIXME: We're looking into outer scopes here, even when we
13306  // shouldn't be. Doing so can result in ambiguities that we
13307  // shouldn't be diagnosing.
13308  LookupName(Previous, S);
13309 
13310  // When declaring or defining a tag, ignore ambiguities introduced
13311  // by types using'ed into this scope.
13312  if (Previous.isAmbiguous() &&
13313  (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13314  LookupResult::Filter F = Previous.makeFilter();
13315  while (F.hasNext()) {
13316  NamedDecl *ND = F.next();
13317  if (!ND->getDeclContext()->getRedeclContext()->Equals(
13318  SearchDC->getRedeclContext()))
13319  F.erase();
13320  }
13321  F.done();
13322  }
13323 
13324  // C++11 [namespace.memdef]p3:
13325  // If the name in a friend declaration is neither qualified nor
13326  // a template-id and the declaration is a function or an
13327  // elaborated-type-specifier, the lookup to determine whether
13328  // the entity has been previously declared shall not consider
13329  // any scopes outside the innermost enclosing namespace.
13330  //
13331  // MSVC doesn't implement the above rule for types, so a friend tag
13332  // declaration may be a redeclaration of a type declared in an enclosing
13333  // scope. They do implement this rule for friend functions.
13334  //
13335  // Does it matter that this should be by scope instead of by
13336  // semantic context?
13337  if (!Previous.empty() && TUK == TUK_Friend) {
13338  DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13339  LookupResult::Filter F = Previous.makeFilter();
13340  bool FriendSawTagOutsideEnclosingNamespace = false;
13341  while (F.hasNext()) {
13342  NamedDecl *ND = F.next();
13344  if (DC->isFileContext() &&
13345  !EnclosingNS->Encloses(ND->getDeclContext())) {
13346  if (getLangOpts().MSVCCompat)
13347  FriendSawTagOutsideEnclosingNamespace = true;
13348  else
13349  F.erase();
13350  }
13351  }
13352  F.done();
13353 
13354  // Diagnose this MSVC extension in the easy case where lookup would have
13355  // unambiguously found something outside the enclosing namespace.
13356  if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13357  NamedDecl *ND = Previous.getFoundDecl();
13358  Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13359  << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13360  }
13361  }
13362 
13363  // Note: there used to be some attempt at recovery here.
13364  if (Previous.isAmbiguous())
13365  return nullptr;
13366 
13367  if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13368  // FIXME: This makes sure that we ignore the contexts associated
13369  // with C structs, unions, and enums when looking for a matching
13370  // tag declaration or definition. See the similar lookup tweak
13371  // in Sema::LookupName; is there a better way to deal with this?
13372  while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13373  SearchDC = SearchDC->getParent();
13374  }
13375  }
13376 
13377  if (Previous.isSingleResult() &&
13378  Previous.getFoundDecl()->isTemplateParameter()) {
13379  // Maybe we will complain about the shadowed template parameter.
13380  DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13381  // Just pretend that we didn't see the previous declaration.
13382  Previous.clear();
13383  }
13384 
13385  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13386  DC->Equals(getStdNamespace())) {
13387  if (Name->isStr("bad_alloc")) {
13388  // This is a declaration of or a reference to "std::bad_alloc".
13389  isStdBadAlloc = true;
13390 
13391  // If std::bad_alloc has been implicitly declared (but made invisible to
13392  // name lookup), fill in this implicit declaration as the previous
13393  // declaration, so that the declarations get chained appropriately.
13394  if (Previous.empty() && StdBadAlloc)
13395  Previous.addDecl(getStdBadAlloc());
13396  } else if (Name->isStr("align_val_t")) {
13397  isStdAlignValT = true;
13398  if (Previous.empty() && StdAlignValT)
13399  Previous.addDecl(getStdAlignValT());
13400  }
13401  }
13402 
13403  // If we didn't find a previous declaration, and this is a reference
13404  // (or friend reference), move to the correct scope. In C++, we
13405  // also need to do a redeclaration lookup there, just in case
13406  // there's a shadow friend decl.
13407  if (Name && Previous.empty() &&
13408  (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13409  if (Invalid) goto CreateNewDecl;
13410  assert(SS.isEmpty());
13411 
13412  if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13413  // C++ [basic.scope.pdecl]p5:
13414  // -- for an elaborated-type-specifier of the form
13415  //
13416  // class-key identifier
13417  //
13418  // if the elaborated-type-specifier is used in the
13419  // decl-specifier-seq or parameter-declaration-clause of a
13420  // function defined in namespace scope, the identifier is
13421  // declared as a class-name in the namespace that contains
13422  // the declaration; otherwise, except as a friend
13423  // declaration, the identifier is declared in the smallest
13424  // non-class, non-function-prototype scope that contains the
13425  // declaration.
13426  //
13427  // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13428  // C structs and unions.
13429  //
13430  // It is an error in C++ to declare (rather than define) an enum
13431  // type, including via an elaborated type specifier. We'll
13432  // diagnose that later; for now, declare the enum in the same
13433  // scope as we would have picked for any other tag type.
13434  //
13435  // GNU C also supports this behavior as part of its incomplete
13436  // enum types extension, while GNU C++ does not.
13437  //
13438  // Find the context where we'll be declaring the tag.
13439  // FIXME: We would like to maintain the current DeclContext as the
13440  // lexical context,
13441  SearchDC = getTagInjectionContext(SearchDC);
13442 
13443  // Find the scope where we'll be declaring the tag.
13444  S = getTagInjectionScope(S, getLangOpts());
13445  } else {
13446  assert(TUK == TUK_Friend);
13447  // C++ [namespace.memdef]p3:
13448  // If a friend declaration in a non-local class first declares a
13449  // class or function, the friend class or function is a member of
13450  // the innermost enclosing namespace.
13451  SearchDC = SearchDC->getEnclosingNamespaceContext();
13452  }
13453 
13454  // In C++, we need to do a redeclaration lookup to properly
13455  // diagnose some problems.
13456  // FIXME: redeclaration lookup is also used (with and without C++) to find a
13457  // hidden declaration so that we don't get ambiguity errors when using a
13458  // type declared by an elaborated-type-specifier. In C that is not correct
13459  // and we should instead merge compatible types found by lookup.
13460  if (getLangOpts().CPlusPlus) {
13461  Previous.setRedeclarationKind(forRedeclarationInCurContext());
13462  LookupQualifiedName(Previous, SearchDC);
13463  } else {
13464  Previous.setRedeclarationKind(forRedeclarationInCurContext());
13465  LookupName(Previous, S);
13466  }
13467  }
13468 
13469  // If we have a known previous declaration to use, then use it.
13470  if (Previous.empty() && SkipBody && SkipBody->Previous)
13471  Previous.addDecl(SkipBody->Previous);
13472 
13473  if (!Previous.empty()) {
13474  NamedDecl *PrevDecl = Previous.getFoundDecl();
13475  NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13476 
13477  // It's okay to have a tag decl in the same scope as a typedef
13478  // which hides a tag decl in the same scope. Finding this
13479  // insanity with a redeclaration lookup can only actually happen
13480  // in C++.
13481  //
13482  // This is also okay for elaborated-type-specifiers, which is
13483  // technically forbidden by the current standard but which is
13484  // okay according to the likely resolution of an open issue;
13485  // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13486  if (getLangOpts().CPlusPlus) {
13487  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13488  if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13489  TagDecl *Tag = TT->getDecl();
13490  if (Tag->getDeclName() == Name &&
13492  ->Equals(TD->getDeclContext()->getRedeclContext())) {
13493  PrevDecl = Tag;
13494  Previous.clear();
13495  Previous.addDecl(Tag);
13496  Previous.resolveKind();
13497  }
13498  }
13499  }
13500  }
13501 
13502  // If this is a redeclaration of a using shadow declaration, it must
13503  // declare a tag in the same context. In MSVC mode, we allow a
13504  // redefinition if either context is within the other.
13505  if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13506  auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13507  if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13508  isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13509  !(OldTag && isAcceptableTagRedeclContext(
13510  *this, OldTag->getDeclContext(), SearchDC))) {
13511  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13512  Diag(Shadow->getTargetDecl()->getLocation(),
13513  diag::note_using_decl_target);
13514  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13515  << 0;
13516  // Recover by ignoring the old declaration.
13517  Previous.clear();
13518  goto CreateNewDecl;
13519  }
13520  }
13521 
13522  if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13523  // If this is a use of a previous tag, or if the tag is already declared
13524  // in the same scope (so that the definition/declaration completes or
13525  // rementions the tag), reuse the decl.
13526  if (TUK == TUK_Reference || TUK == TUK_Friend ||
13527  isDeclInScope(DirectPrevDecl, SearchDC, S,
13528  SS.isNotEmpty() || isMemberSpecialization)) {
13529  // Make sure that this wasn't declared as an enum and now used as a
13530  // struct or something similar.
13531  if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13532  TUK == TUK_Definition, KWLoc,
13533  Name)) {
13534  bool SafeToContinue
13535  = (PrevTagDecl->getTagKind() != TTK_Enum &&
13536  Kind != TTK_Enum);
13537  if (SafeToContinue)
13538  Diag(KWLoc, diag::err_use_with_wrong_tag)
13539  << Name
13541  PrevTagDecl->getKindName());
13542  else
13543  Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13544  Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13545 
13546  if (SafeToContinue)
13547  Kind = PrevTagDecl->getTagKind();
13548  else {
13549  // Recover by making this an anonymous redefinition.
13550  Name = nullptr;
13551  Previous.clear();
13552  Invalid = true;
13553  }
13554  }
13555 
13556  if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13557  const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13558 
13559  // If this is an elaborated-type-specifier for a scoped enumeration,
13560  // the 'class' keyword is not necessary and not permitted.
13561  if (TUK == TUK_Reference || TUK == TUK_Friend) {
13562  if (ScopedEnum)
13563  Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13564  << PrevEnum->isScoped()
13565  << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13566  return PrevTagDecl;
13567  }
13568 
13569  QualType EnumUnderlyingTy;
13570  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13571  EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13572  else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13573  EnumUnderlyingTy = QualType(T, 0);
13574 
13575  // All conflicts with previous declarations are recovered by
13576  // returning the previous declaration, unless this is a definition,
13577  // in which case we want the caller to bail out.
13578  if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13579  ScopedEnum, EnumUnderlyingTy,
13580  EnumUnderlyingIsImplicit, PrevEnum))
13581  return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13582  }
13583 
13584  // C++11 [class.mem]p1:
13585  // A member shall not be declared twice in the member-specification,
13586  // except that a nested class or member class template can be declared
13587  // and then later defined.
13588  if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13589  S->isDeclScope(PrevDecl)) {
13590  Diag(NameLoc, diag::ext_member_redeclared);
13591  Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13592  }
13593 
13594  if (!Invalid) {
13595  // If this is a use, just return the declaration we found, unless
13596  // we have attributes.
13597  if (TUK == TUK_Reference || TUK == TUK_Friend) {
13598  if (Attr) {
13599  // FIXME: Diagnose these attributes. For now, we create a new
13600  // declaration to hold them.
13601  } else if (TUK == TUK_Reference &&
13602  (PrevTagDecl->getFriendObjectKind() ==
13604  PrevDecl->getOwningModule() != getCurrentModule()) &&
13605  SS.isEmpty()) {
13606  // This declaration is a reference to an existing entity, but
13607  // has different visibility from that entity: it either makes
13608  // a friend visible or it makes a type visible in a new module.
13609  // In either case, create a new declaration. We only do this if
13610  // the declaration would have meant the same thing if no prior
13611  // declaration were found, that is, if it was found in the same
13612  // scope where we would have injected a declaration.
13613  if (!getTagInjectionContext(CurContext)->getRedeclContext()
13614  ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13615  return PrevTagDecl;
13616  // This is in the injected scope, create a new declaration in
13617  // that scope.
13618  S = getTagInjectionScope(S, getLangOpts());
13619  } else {
13620  return PrevTagDecl;
13621  }
13622  }
13623 
13624  // Diagnose attempts to redefine a tag.
13625  if (TUK == TUK_Definition) {
13626  if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13627  // If we're defining a specialization and the previous definition
13628  // is from an implicit instantiation, don't emit an error
13629  // here; we'll catch this in the general case below.
13630  bool IsExplicitSpecializationAfterInstantiation = false;
13631  if (isMemberSpecialization) {
13632  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13633  IsExplicitSpecializationAfterInstantiation =
13634  RD->getTemplateSpecializationKind() !=
13636  else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13637  IsExplicitSpecializationAfterInstantiation =
13638  ED->getTemplateSpecializationKind() !=
13640  }
13641 
13642  // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13643  // not keep more that one definition around (merge them). However,
13644  // ensure the decl passes the structural compatibility check in
13645  // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13646  NamedDecl *Hidden = nullptr;
13647  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13648  // There is a definition of this tag, but it is not visible. We
13649  // explicitly make use of C++'s one definition rule here, and
13650  // assume that this definition is identical to the hidden one
13651  // we already have. Make the existing definition visible and
13652  // use it in place of this one.
13653  if (!getLangOpts().CPlusPlus) {
13654  // Postpone making the old definition visible until after we
13655  // complete parsing the new one and do the structural
13656  // comparison.
13657  SkipBody->CheckSameAsPrevious = true;
13658  SkipBody->New = createTagFromNewDecl();
13659  SkipBody->Previous = Hidden;
13660  } else {
13661  SkipBody->ShouldSkip = true;
13662  makeMergedDefinitionVisible(Hidden);
13663  }
13664  return Def;
13665  } else if (!IsExplicitSpecializationAfterInstantiation) {
13666  // A redeclaration in function prototype scope in C isn't
13667  // visible elsewhere, so merely issue a warning.
13668  if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13669  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13670  else
13671  Diag(NameLoc, diag::err_redefinition) << Name;
13672  notePreviousDefinition(Def,
13673  NameLoc.isValid() ? NameLoc : KWLoc);
13674  // If this is a redefinition, recover by making this
13675  // struct be anonymous, which will make any later
13676  // references get the previous definition.
13677  Name = nullptr;
13678  Previous.clear();
13679  Invalid = true;
13680  }
13681  } else {
13682  // If the type is currently being defined, complain
13683  // about a nested redefinition.
13684  auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13685  if (TD->isBeingDefined()) {
13686  Diag(NameLoc, diag::err_nested_redefinition) << Name;
13687  Diag(PrevTagDecl->getLocation(),
13688  diag::note_previous_definition);
13689  Name = nullptr;
13690  Previous.clear();
13691  Invalid = true;
13692  }
13693  }
13694 
13695  // Okay, this is definition of a previously declared or referenced
13696  // tag. We're going to create a new Decl for it.
13697  }
13698 
13699  // Okay, we're going to make a redeclaration. If this is some kind
13700  // of reference, make sure we build the redeclaration in the same DC
13701  // as the original, and ignore the current access specifier.
13702  if (TUK == TUK_Friend || TUK == TUK_Reference) {
13703  SearchDC = PrevTagDecl->getDeclContext();
13704  AS = AS_none;
13705  }
13706  }
13707  // If we get here we have (another) forward declaration or we
13708  // have a definition. Just create a new decl.
13709 
13710  } else {
13711  // If we get here, this is a definition of a new tag type in a nested
13712  // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13713  // new decl/type. We set PrevDecl to NULL so that the entities
13714  // have distinct types.
13715  Previous.clear();
13716  }
13717  // If we get here, we're going to create a new Decl. If PrevDecl
13718  // is non-NULL, it's a definition of the tag declared by
13719  // PrevDecl. If it's NULL, we have a new definition.
13720 
13721  // Otherwise, PrevDecl is not a tag, but was found with tag
13722  // lookup. This is only actually possible in C++, where a few
13723  // things like templates still live in the tag namespace.
13724  } else {
13725  // Use a better diagnostic if an elaborated-type-specifier
13726  // found the wrong kind of type on the first
13727  // (non-redeclaration) lookup.
13728  if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13729  !Previous.isForRedeclaration()) {
13730  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13731  Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13732  << Kind;
13733  Diag(PrevDecl->getLocation(), diag::note_declared_at);
13734  Invalid = true;
13735 
13736  // Otherwise, only diagnose if the declaration is in scope.
13737  } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13738  SS.isNotEmpty() || isMemberSpecialization)) {
13739  // do nothing
13740 
13741  // Diagnose implicit declarations introduced by elaborated types.
13742  } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13743  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13744  Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13745  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13746  Invalid = true;
13747 
13748  // Otherwise it's a declaration. Call out a particularly common
13749  // case here.
13750  } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13751  unsigned Kind = 0;
13752  if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13753  Diag(NameLoc, diag::err_tag_definition_of_typedef)
13754  << Name << Kind << TND->getUnderlyingType();
13755  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13756  Invalid = true;
13757 
13758  // Otherwise, diagnose.
13759  } else {
13760  // The tag name clashes with something else in the target scope,
13761  // issue an error and recover by making this tag be anonymous.
13762  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13763  notePreviousDefinition(PrevDecl, NameLoc);
13764  Name = nullptr;
13765  Invalid = true;
13766  }
13767 
13768  // The existing declaration isn't relevant to us; we're in a
13769  // new scope, so clear out the previous declaration.
13770  Previous.clear();
13771  }
13772  }
13773 
13774 CreateNewDecl:
13775 
13776  TagDecl *PrevDecl = nullptr;
13777  if (Previous.isSingleResult())
13778  PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13779 
13780  // If there is an identifier, use the location of the identifier as the
13781  // location of the decl, otherwise use the location of the struct/union
13782  // keyword.
13783  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13784 
13785  // Otherwise, create a new declaration. If there is a previous
13786  // declaration of the same entity, the two will be linked via
13787  // PrevDecl.
13788  TagDecl *New;
13789 
13790  bool IsForwardReference = false;
13791  if (Kind == TTK_Enum) {
13792  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13793  // enum X { A, B, C } D; D should chain to X.
13794  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13795  cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13796  ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13797 
13798  if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13799  StdAlignValT = cast<EnumDecl>(New);
13800 
13801  // If this is an undefined enum, warn.
13802  if (TUK != TUK_Definition && !Invalid) {
13803  TagDecl *Def;
13804  if (!EnumUnderlyingIsImplicit &&
13805  (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13806  cast<EnumDecl>(New)->isFixed()) {
13807  // C++0x: 7.2p2: opaque-enum-declaration.
13808  // Conflicts are diagnosed above. Do nothing.
13809  }
13810  else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13811  Diag(Loc, diag::ext_forward_ref_enum_def)
13812  << New;
13813  Diag(Def->getLocation(), diag::note_previous_definition);
13814  } else {
13815  unsigned DiagID = diag::ext_forward_ref_enum;
13816  if (getLangOpts().MSVCCompat)
13817  DiagID = diag::ext_ms_forward_ref_enum;
13818  else if (getLangOpts().CPlusPlus)
13819  DiagID = diag::err_forward_ref_enum;
13820  Diag(Loc, DiagID);
13821 
13822  // If this is a forward-declared reference to an enumeration, make a
13823  // note of it; we won't actually be introducing the declaration into
13824  // the declaration context.
13825  if (TUK == TUK_Reference)
13826  IsForwardReference = true;
13827  }
13828  }
13829 
13830  if (EnumUnderlying) {
13831  EnumDecl *ED = cast<EnumDecl>(New);
13832  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13833  ED->setIntegerTypeSourceInfo(TI);
13834  else
13835  ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13836  ED->setPromotionType(ED->getIntegerType());
13837  }
13838  } else {
13839  // struct/union/class
13840 
13841  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13842  // struct X { int A; } D; D should chain to X.
13843  if (getLangOpts().CPlusPlus) {
13844  // FIXME: Look for a way to use RecordDecl for simple structs.
13845  New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13846  cast_or_null<CXXRecordDecl>(PrevDecl));
13847 
13848  if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13849  StdBadAlloc = cast<CXXRecordDecl>(New);
13850  } else
13851  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13852  cast_or_null<RecordDecl>(PrevDecl));
13853  }
13854 
13855  // C++11 [dcl.type]p3:
13856  // A type-specifier-seq shall not define a class or enumeration [...].
13857  if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13858  TUK == TUK_Definition) {
13859  Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13860  << Context.getTagDeclType(New);
13861  Invalid = true;
13862  }
13863 
13864  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
13865  DC->getDeclKind() == Decl::Enum) {
13866  Diag(New->getLocation(), diag::err_type_defined_in_enum)
13867  << Context.getTagDeclType(New);
13868  Invalid = true;
13869  }
13870 
13871  // Maybe add qualifier info.
13872  if (SS.isNotEmpty()) {
13873  if (SS.isSet()) {
13874  // If this is either a declaration or a definition, check the
13875  // nested-name-specifier against the current context. We don't do this
13876  // for explicit specializations, because they have similar checking
13877  // (with more specific diagnostics) in the call to
13878  // CheckMemberSpecialization, below.
13879  if (!isMemberSpecialization &&
13880  (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13881  diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13882  Invalid = true;
13883 
13884  New->setQualifierInfo(SS.getWithLocInContext(Context));
13885  if (TemplateParameterLists.size() > 0) {
13886  New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13887  }
13888  }
13889  else
13890  Invalid = true;
13891  }
13892 
13893  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13894  // Add alignment attributes if necessary; these attributes are checked when
13895  // the ASTContext lays out the structure.
13896  //
13897  // It is important for implementing the correct semantics that this
13898  // happen here (in ActOnTag). The #pragma pack stack is
13899  // maintained as a result of parser callbacks which can occur at
13900  // many points during the parsing of a struct declaration (because
13901  // the #pragma tokens are effectively skipped over during the
13902  // parsing of the struct).
13903  if (TUK == TUK_Definition) {
13904  AddAlignmentAttributesForRecord(RD);
13905  AddMsStructLayoutForRecord(RD);
13906  }
13907  }
13908 
13909  if (ModulePrivateLoc.isValid()) {
13910  if (isMemberSpecialization)
13911  Diag(New->getLocation(), diag::err_module_private_specialization)
13912  << 2
13913  << FixItHint::CreateRemoval(ModulePrivateLoc);
13914  // __module_private__ does not apply to local classes. However, we only
13915  // diagnose this as an error when the declaration specifiers are
13916  // freestanding. Here, we just ignore the __module_private__.
13917  else if (!SearchDC->isFunctionOrMethod())
13918  New->setModulePrivate();
13919  }
13920 
13921  // If this is a specialization of a member class (of a class template),
13922  // check the specialization.
13923  if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13924  Invalid = true;
13925 
13926  // If we're declaring or defining a tag in function prototype scope in C,
13927  // note that this type can only be used within the function and add it to
13928  // the list of decls to inject into the function definition scope.
13929  if ((Name || Kind == TTK_Enum) &&
13930  getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13931  if (getLangOpts().CPlusPlus) {
13932  // C++ [dcl.fct]p6:
13933  // Types shall not be defined in return or parameter types.
13934  if (TUK == TUK_Definition && !IsTypeSpecifier) {
13935  Diag(Loc, diag::err_type_defined_in_param_type)
13936  << Name;
13937  Invalid = true;
13938  }
13939  } else if (!PrevDecl) {
13940  Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13941  }
13942  }
13943 
13944  if (Invalid)
13945  New->setInvalidDecl();
13946 
13947  // Set the lexical context. If the tag has a C++ scope specifier, the
13948  // lexical context will be different from the semantic context.
13949  New->setLexicalDeclContext(CurContext);
13950 
13951  // Mark this as a friend decl if applicable.
13952  // In Microsoft mode, a friend declaration also acts as a forward
13953  // declaration so we always pass true to setObjectOfFriendDecl to make
13954  // the tag name visible.
13955  if (TUK == TUK_Friend)
13956  New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13957 
13958  // Set the access specifier.
13959  if (!Invalid && SearchDC->isRecord())
13960  SetMemberAccessSpecifier(New, PrevDecl, AS);
13961 
13962  if (PrevDecl)
13963  CheckRedeclarationModuleOwnership(New, PrevDecl);
13964 
13965  if (TUK == TUK_Definition)
13966  New->startDefinition();
13967 
13968  if (Attr)
13969  ProcessDeclAttributeList(S, New, Attr);
13970  AddPragmaAttributes(S, New);
13971 
13972  // If this has an identifier, add it to the scope stack.
13973  if (TUK == TUK_Friend) {
13974  // We might be replacing an existing declaration in the lookup tables;
13975  // if so, borrow its access specifier.
13976  if (PrevDecl)
13977  New->setAccess(PrevDecl->getAccess());
13978 
13980  DC->makeDeclVisibleInContext(New);
13981  if (Name) // can be null along some error paths
13982  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13983  PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13984  } else if (Name) {
13985  S = getNonFieldDeclScope(S);
13986  PushOnScopeChains(New, S, !IsForwardReference);
13987  if (IsForwardReference)
13988  SearchDC->makeDeclVisibleInContext(New);
13989  } else {
13990  CurContext->addDecl(New);
13991  }
13992 
13993  // If this is the C FILE type, notify the AST context.
13994  if (IdentifierInfo *II = New->getIdentifier())
13995  if (!New->isInvalidDecl() &&
13997  II->isStr("FILE"))
13998  Context.setFILEDecl(New);
13999 
14000  if (PrevDecl)
14001  mergeDeclAttributes(New, PrevDecl);
14002 
14003  // If there's a #pragma GCC visibility in scope, set the visibility of this
14004  // record.
14005  AddPushedVisibilityAttribute(New);
14006 
14007  if (isMemberSpecialization && !New->isInvalidDecl())
14008  CompleteMemberSpecialization(New, Previous);
14009 
14010  OwnedDecl = true;
14011  // In C++, don't return an invalid declaration. We can't recover well from
14012  // the cases where we make the type anonymous.
14013  if (Invalid && getLangOpts().CPlusPlus) {
14014  if (New->isBeingDefined())
14015  if (auto RD = dyn_cast<RecordDecl>(New))
14016  RD->completeDefinition();
14017  return nullptr;
14018  } else {
14019  return New;
14020  }
14021 }
14022 
14024  AdjustDeclIfTemplate(TagD);
14025  TagDecl *Tag = cast<TagDecl>(TagD);
14026 
14027  // Enter the tag context.
14028  PushDeclContext(S, Tag);
14029 
14030  ActOnDocumentableDecl(TagD);
14031 
14032  // If there's a #pragma GCC visibility in scope, set the visibility of this
14033  // record.
14034  AddPushedVisibilityAttribute(Tag);
14035 }
14036 
14038  SkipBodyInfo &SkipBody) {
14039  if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14040  return false;
14041 
14042  // Make the previous decl visible.
14043  makeMergedDefinitionVisible(SkipBody.Previous);
14044  return true;
14045 }
14046 
14048  assert(isa<ObjCContainerDecl>(IDecl) &&
14049  "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14050  DeclContext *OCD = cast<DeclContext>(IDecl);
14051  assert(getContainingDC(OCD) == CurContext &&
14052  "The next DeclContext should be lexically contained in the current one.");
14053  CurContext = OCD;
14054  return IDecl;
14055 }
14056 
14058  SourceLocation FinalLoc,
14059  bool IsFinalSpelledSealed,
14060  SourceLocation LBraceLoc) {
14061  AdjustDeclIfTemplate(TagD);
14062  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14063 
14064  FieldCollector->StartClass();
14065 
14066  if (!Record->getIdentifier())
14067  return;
14068 
14069  if (FinalLoc.isValid())
14070  Record->addAttr(new (Context)
14071  FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14072 
14073  // C++ [class]p2:
14074  // [...] The class-name is also inserted into the scope of the
14075  // class itself; this is known as the injected-class-name. For
14076  // purposes of access checking, the injected-class-name is treated
14077  // as if it were a public member name.
14078  CXXRecordDecl *InjectedClassName
14079  = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14080  Record->getLocStart(), Record->getLocation(),
14081  Record->getIdentifier(),
14082  /*PrevDecl=*/nullptr,
14083  /*DelayTypeCreation=*/true);
14084  Context.getTypeDeclType(InjectedClassName, Record);
14085  InjectedClassName->setImplicit();
14086  InjectedClassName->setAccess(AS_public);
14087  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14088  InjectedClassName->setDescribedClassTemplate(Template);
14089  PushOnScopeChains(InjectedClassName, S);
14090  assert(InjectedClassName->isInjectedClassName() &&
14091  "Broken injected-class-name");
14092 }
14093 
14095  SourceRange BraceRange) {
14096  AdjustDeclIfTemplate(TagD);
14097  TagDecl *Tag = cast<TagDecl>(TagD);
14098  Tag->setBraceRange(BraceRange);
14099 
14100  // Make sure we "complete" the definition even it is invalid.
14101  if (Tag->isBeingDefined()) {
14102  assert(Tag->isInvalidDecl() && "We should already have completed it");
14103  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14104  RD->completeDefinition();
14105  }
14106 
14107  if (isa<CXXRecordDecl>(Tag)) {
14108  FieldCollector->FinishClass();
14109  }
14110 
14111  // Exit this scope of this tag's definition.
14112  PopDeclContext();
14113 
14114  if (getCurLexicalContext()->isObjCContainer() &&
14115  Tag->getDeclContext()->isFileContext())
14117 
14118  // Notify the consumer that we've defined a tag.
14119  if (!Tag->isInvalidDecl())
14120  Consumer.HandleTagDeclDefinition(Tag);
14121 }
14122 
14124  // Exit this scope of this interface definition.
14125  PopDeclContext();
14126 }
14127 
14129  assert(DC == CurContext && "Mismatch of container contexts");
14130  OriginalLexicalContext = DC;
14131  ActOnObjCContainerFinishDefinition();
14132 }
14133 
14135  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14136  OriginalLexicalContext = nullptr;
14137 }
14138 
14140  AdjustDeclIfTemplate(TagD);
14141  TagDecl *Tag = cast<TagDecl>(TagD);
14142  Tag->setInvalidDecl();
14143 
14144  // Make sure we "complete" the definition even it is invalid.
14145  if (Tag->isBeingDefined()) {
14146  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14147  RD->completeDefinition();
14148  }
14149 
14150  // We're undoing ActOnTagStartDefinition here, not
14151  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14152  // the FieldCollector.
14153 
14154  PopDeclContext();
14155 }
14156 
14157 // Note that FieldName may be null for anonymous bitfields.
14159  IdentifierInfo *FieldName,
14160  QualType FieldTy, bool IsMsStruct,
14161  Expr *BitWidth, bool *ZeroWidth) {
14162  // Default to true; that shouldn't confuse checks for emptiness
14163  if (ZeroWidth)
14164  *ZeroWidth = true;
14165 
14166  // C99 6.7.2.1p4 - verify the field type.
14167  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14168  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14169  // Handle incomplete types with specific error.
14170  if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14171  return ExprError();
14172  if (FieldName)
14173  return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14174  << FieldName << FieldTy << BitWidth->getSourceRange();
14175  return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14176  << FieldTy << BitWidth->getSourceRange();
14177  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14178  UPPC_BitFieldWidth))
14179  return ExprError();
14180 
14181  // If the bit-width is type- or value-dependent, don't try to check
14182  // it now.
14183  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14184  return BitWidth;
14185 
14186  llvm::APSInt Value;
14187  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14188  if (ICE.isInvalid())
14189  return ICE;
14190  BitWidth = ICE.get();
14191 
14192  if (Value != 0 && ZeroWidth)
14193  *ZeroWidth = false;
14194 
14195  // Zero-width bitfield is ok for anonymous field.
14196  if (Value == 0 && FieldName)
14197  return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14198 
14199  if (Value.isSigned() && Value.isNegative()) {
14200  if (FieldName)
14201  return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14202  << FieldName << Value.toString(10);
14203  return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14204  << Value.toString(10);
14205  }
14206 
14207  if (!FieldTy->isDependentType()) {
14208  uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14209  uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14210  bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14211 
14212  // Over-wide bitfields are an error in C or when using the MSVC bitfield
14213  // ABI.
14214  bool CStdConstraintViolation =
14215  BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14216  bool MSBitfieldViolation =
14217  Value.ugt(TypeStorageSize) &&
14218  (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14219  if (CStdConstraintViolation || MSBitfieldViolation) {
14220  unsigned DiagWidth =
14221  CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14222  if (FieldName)
14223  return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14224  << FieldName << (unsigned)Value.getZExtValue()
14225  << !CStdConstraintViolation << DiagWidth;
14226 
14227  return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14228  << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14229  << DiagWidth;
14230  }
14231 
14232  // Warn on types where the user might conceivably expect to get all
14233  // specified bits as value bits: that's all integral types other than
14234  // 'bool'.
14235  if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14236  if (FieldName)
14237  Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14238  << FieldName << (unsigned)Value.getZExtValue()
14239  << (unsigned)TypeWidth;
14240  else
14241  Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14242  << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14243  }
14244  }
14245 
14246  return BitWidth;
14247 }
14248 
14249 /// ActOnField - Each field of a C struct/union is passed into this in order
14250 /// to create a FieldDecl object for it.
14252  Declarator &D, Expr *BitfieldWidth) {
14253  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14254  DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14255  /*InitStyle=*/ICIS_NoInit, AS_public);
14256  return Res;
14257 }
14258 
14259 /// HandleField - Analyze a field of a C struct or a C++ data member.
14260 ///
14262  SourceLocation DeclStart,
14263  Declarator &D, Expr *BitWidth,
14264  InClassInitStyle InitStyle,
14265  AccessSpecifier AS) {
14266  if (D.isDecompositionDeclarator()) {
14268  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14269  << Decomp.getSourceRange();
14270  return nullptr;
14271  }
14272 
14273  IdentifierInfo *II = D.getIdentifier();
14274  SourceLocation Loc = DeclStart;
14275  if (II) Loc = D.getIdentifierLoc();
14276 
14277  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14278  QualType T = TInfo->getType();
14279  if (getLangOpts().CPlusPlus) {
14280  CheckExtraCXXDefaultArguments(D);
14281 
14282  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14283  UPPC_DataMemberType)) {
14284  D.setInvalidType();
14285  T = Context.IntTy;
14286  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14287  }
14288  }
14289 
14290  // TR 18037 does not allow fields to be declared with address spaces.
14291  if (T.getQualifiers().hasAddressSpace() ||
14294  Diag(Loc, diag::err_field_with_address_space);
14295  D.setInvalidType();
14296  }
14297 
14298  // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14299  // used as structure or union field: image, sampler, event or block types.
14300  if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14301  T->isSamplerT() || T->isBlockPointerType())) {
14302  Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14303  D.setInvalidType();
14304  }
14305 
14306  DiagnoseFunctionSpecifiers(D.getDeclSpec());
14307 
14308  if (D.getDeclSpec().isInlineSpecified())
14309  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14310  << getLangOpts().CPlusPlus17;
14313  diag::err_invalid_thread)
14314  << DeclSpec::getSpecifierName(TSCS);
14315 
14316  // Check to see if this name was declared as a member previously
14317  NamedDecl *PrevDecl = nullptr;
14318  LookupResult Previous(*this, II, Loc, LookupMemberName,
14319  ForVisibleRedeclaration);
14320  LookupName(Previous, S);
14321  switch (Previous.getResultKind()) {
14322  case LookupResult::Found:
14324  PrevDecl = Previous.getAsSingle<NamedDecl>();
14325  break;
14326 
14328  PrevDecl = Previous.getRepresentativeDecl();
14329  break;
14330 
14334  break;
14335  }
14336  Previous.suppressDiagnostics();
14337 
14338  if (PrevDecl && PrevDecl->isTemplateParameter()) {
14339  // Maybe we will complain about the shadowed template parameter.
14340  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14341  // Just pretend that we didn't see the previous declaration.
14342  PrevDecl = nullptr;
14343  }
14344 
14345  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14346  PrevDecl = nullptr;
14347 
14348  bool Mutable
14350  SourceLocation TSSL = D.getLocStart();
14351  FieldDecl *NewFD
14352  = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14353  TSSL, AS, PrevDecl, &D);
14354 
14355  if (NewFD->isInvalidDecl())
14356  Record->setInvalidDecl();
14357 
14359  NewFD->setModulePrivate();
14360 
14361  if (NewFD->isInvalidDecl() && PrevDecl) {
14362  // Don't introduce NewFD into scope; there's already something
14363  // with the same name in the same scope.
14364  } else if (II) {
14365  PushOnScopeChains(NewFD, S);
14366  } else
14367  Record->addDecl(NewFD);
14368 
14369  return NewFD;
14370 }
14371 
14372 /// \brief Build a new FieldDecl and check its well-formedness.
14373 ///
14374 /// This routine builds a new FieldDecl given the fields name, type,
14375 /// record, etc. \p PrevDecl should refer to any previous declaration
14376 /// with the same name and in the same scope as the field to be
14377 /// created.
14378 ///
14379 /// \returns a new FieldDecl.
14380 ///
14381 /// \todo The Declarator argument is a hack. It will be removed once
14383  TypeSourceInfo *TInfo,
14384  RecordDecl *Record, SourceLocation Loc,
14385  bool Mutable, Expr *BitWidth,
14386  InClassInitStyle InitStyle,
14387  SourceLocation TSSL,
14388  AccessSpecifier AS, NamedDecl *PrevDecl,
14389  Declarator *D) {
14390  IdentifierInfo *II = Name.getAsIdentifierInfo();
14391  bool InvalidDecl = false;
14392  if (D) InvalidDecl = D->isInvalidType();
14393 
14394  // If we receive a broken type, recover by assuming 'int' and
14395  // marking this declaration as invalid.
14396  if (T.isNull()) {
14397  InvalidDecl = true;
14398  T = Context.IntTy;
14399  }
14400 
14401  QualType EltTy = Context.getBaseElementType(T);
14402  if (!EltTy->isDependentType()) {
14403  if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14404  // Fields of incomplete type force their record to be invalid.
14405  Record->setInvalidDecl();
14406  InvalidDecl = true;
14407  } else {
14408  NamedDecl *Def;
14409  EltTy->isIncompleteType(&Def);
14410  if (Def && Def->isInvalidDecl()) {
14411  Record->setInvalidDecl();
14412  InvalidDecl = true;
14413  }
14414  }
14415  }
14416 
14417  // OpenCL v1.2 s6.9.c: bitfields are not supported.
14418  if (BitWidth && getLangOpts().OpenCL) {
14419  Diag(Loc, diag::err_opencl_bitfields);
14420  InvalidDecl = true;
14421  }
14422 
14423  // C99 6.7.2.1p8: A member of a structure or union may have any type other
14424  // than a variably modified type.
14425  if (!InvalidDecl && T->isVariablyModifiedType()) {
14426  bool SizeIsNegative;
14427  llvm::APSInt Oversized;
14428 
14429  TypeSourceInfo *FixedTInfo =
14431  SizeIsNegative,
14432  Oversized);
14433  if (FixedTInfo) {
14434  Diag(Loc, diag::warn_illegal_constant_array_size);
14435  TInfo = FixedTInfo;
14436  T = FixedTInfo->getType();
14437  } else {
14438  if (SizeIsNegative)
14439  Diag(Loc, diag::err_typecheck_negative_array_size);
14440  else if (Oversized.getBoolValue())
14441  Diag(Loc, diag::err_array_too_large)
14442  << Oversized.toString(10);
14443  else
14444  Diag(Loc, diag::err_typecheck_field_variable_size);
14445  InvalidDecl = true;
14446  }
14447  }
14448 
14449  // Fields can not have abstract class types
14450  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14451  diag::err_abstract_type_in_decl,
14452  AbstractFieldType))
14453  InvalidDecl = true;
14454 
14455  bool ZeroWidth = false;
14456  if (InvalidDecl)
14457  BitWidth = nullptr;
14458  // If this is declared as a bit-field, check the bit-field.
14459  if (BitWidth) {
14460  BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14461  &ZeroWidth).get();
14462  if (!BitWidth) {
14463  InvalidDecl = true;
14464  BitWidth = nullptr;
14465  ZeroWidth = false;
14466  }
14467  }
14468 
14469  // Check that 'mutable' is consistent with the type of the declaration.
14470  if (!InvalidDecl && Mutable) {
14471  unsigned DiagID = 0;
14472  if (T->isReferenceType())
14473  DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14474  : diag::err_mutable_reference;
14475  else if (T.isConstQualified())
14476  DiagID = diag::err_mutable_const;
14477 
14478  if (DiagID) {
14479  SourceLocation ErrLoc = Loc;
14480  if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14481  ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14482  Diag(ErrLoc, DiagID);
14483  if (DiagID != diag::ext_mutable_reference) {
14484  Mutable = false;
14485  InvalidDecl = true;
14486  }
14487  }
14488  }
14489 
14490  // C++11 [class.union]p8 (DR1460):
14491  // At most one variant member of a union may have a
14492  // brace-or-equal-initializer.
14493  if (InitStyle != ICIS_NoInit)
14494  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14495 
14496  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14497  BitWidth, Mutable, InitStyle);
14498  if (InvalidDecl)
14499  NewFD->setInvalidDecl();
14500 
14501  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14502  Diag(Loc, diag::err_duplicate_member) << II;
14503  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14504  NewFD->setInvalidDecl();
14505  }
14506 
14507  if (!InvalidDecl && getLangOpts().CPlusPlus) {
14508  if (Record->isUnion()) {
14509  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14510  CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14511  if (RDecl->getDefinition()) {
14512  // C++ [class.union]p1: An object of a class with a non-trivial
14513  // constructor, a non-trivial copy constructor, a non-trivial
14514  // destructor, or a non-trivial copy assignment operator
14515  // cannot be a member of a union, nor can an array of such
14516  // objects.
14517  if (CheckNontrivialField(NewFD))
14518  NewFD->setInvalidDecl();
14519  }
14520  }
14521 
14522  // C++ [class.union]p1: If a union contains a member of reference type,
14523  // the program is ill-formed, except when compiling with MSVC extensions
14524  // enabled.
14525  if (EltTy->isReferenceType()) {
14526  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14527  diag::ext_union_member_of_reference_type :
14528  diag::err_union_member_of_reference_type)
14529  << NewFD->getDeclName() << EltTy;
14530  if (!getLangOpts().MicrosoftExt)
14531  NewFD->setInvalidDecl();
14532  }
14533  }
14534  }
14535 
14536  // FIXME: We need to pass in the attributes given an AST
14537  // representation, not a parser representation.
14538  if (D) {
14539  // FIXME: The current scope is almost... but not entirely... correct here.
14540  ProcessDeclAttributes(getCurScope(), NewFD, *D);
14541 
14542  if (NewFD->hasAttrs())
14543  CheckAlignasUnderalignment(NewFD);
14544  }
14545 
14546  // In auto-retain/release, infer strong retension for fields of
14547  // retainable type.
14548  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14549  NewFD->setInvalidDecl();
14550 
14551  if (T.isObjCGCWeak())
14552  Diag(Loc, diag::warn_attribute_weak_on_field);
14553 
14554  NewFD->setAccess(AS);
14555  return NewFD;
14556 }
14557 
14559  assert(FD);
14560  assert(getLangOpts().CPlusPlus && "valid check only for C++");
14561 
14562  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14563  return false;
14564 
14565  QualType EltTy = Context.getBaseElementType(FD->getType());
14566  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14567  CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14568  if (RDecl->getDefinition()) {
14569  // We check for copy constructors before constructors
14570  // because otherwise we'll never get complaints about
14571  // copy constructors.
14572 
14573  CXXSpecialMember member = CXXInvalid;
14574  // We're required to check for any non-trivial constructors. Since the
14575  // implicit default constructor is suppressed if there are any
14576  // user-declared constructors, we just need to check that there is a
14577  // trivial default constructor and a trivial copy constructor. (We don't
14578  // worry about move constructors here, since this is a C++98 check.)
14579  if (RDecl->hasNonTrivialCopyConstructor())
14580  member = CXXCopyConstructor;
14581  else if (!RDecl->hasTrivialDefaultConstructor())
14582  member = CXXDefaultConstructor;
14583  else if (RDecl->hasNonTrivialCopyAssignment())
14584  member = CXXCopyAssignment;
14585  else if (RDecl->hasNonTrivialDestructor())
14586  member = CXXDestructor;
14587 
14588  if (member != CXXInvalid) {
14589  if (!getLangOpts().CPlusPlus11 &&
14590  getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14591  // Objective-C++ ARC: it is an error to have a non-trivial field of
14592  // a union. However, system headers in Objective-C programs
14593  // occasionally have Objective-C lifetime objects within unions,
14594  // and rather than cause the program to fail, we make those
14595  // members unavailable.
14596  SourceLocation Loc = FD->getLocation();
14597  if (getSourceManager().isInSystemHeader(Loc)) {
14598  if (!FD->hasAttr<UnavailableAttr>())
14599  FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14600  UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14601  return false;
14602  }
14603  }
14604 
14605  Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14606  diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14607  diag::err_illegal_union_or_anon_struct_member)
14608  << FD->getParent()->isUnion() << FD->getDeclName() << member;
14609  DiagnoseNontrivial(RDecl, member);
14610  return !getLangOpts().CPlusPlus11;
14611  }
14612  }
14613  }
14614 
14615  return false;
14616 }
14617 
14618 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14619 /// AST enum value.
14622  switch (ivarVisibility) {
14623  default: llvm_unreachable("Unknown visitibility kind");
14624  case tok::objc_private: return ObjCIvarDecl::Private;
14625  case tok::objc_public: return ObjCIvarDecl::Public;
14626  case tok::objc_protected: return ObjCIvarDecl::Protected;
14627  case tok::objc_package: return ObjCIvarDecl::Package;
14628  }
14629 }
14630 
14631 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14632 /// in order to create an IvarDecl object for it.
14634  SourceLocation DeclStart,
14635  Declarator &D, Expr *BitfieldWidth,
14637 
14638  IdentifierInfo *II = D.getIdentifier();
14639  Expr *BitWidth = (Expr*)BitfieldWidth;
14640  SourceLocation Loc = DeclStart;
14641  if (II) Loc = D.getIdentifierLoc();
14642 
14643  // FIXME: Unnamed fields can be handled in various different ways, for
14644  // example, unnamed unions inject all members into the struct namespace!
14645 
14646  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14647  QualType T = TInfo->getType();
14648 
14649  if (BitWidth) {
14650  // 6.7.2.1p3, 6.7.2.1p4
14651  BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14652  if (!BitWidth)
14653  D.setInvalidType();
14654  } else {
14655  // Not a bitfield.
14656 
14657  // validate II.
14658 
14659  }
14660  if (T->isReferenceType()) {
14661  Diag(Loc, diag::err_ivar_reference_type);
14662  D.setInvalidType();
14663  }
14664  // C99 6.7.2.1p8: A member of a structure or union may have any type other
14665  // than a variably modified type.
14666  else if (T->isVariablyModifiedType()) {
14667  Diag(Loc, diag::err_typecheck_ivar_variable_size);
14668  D.setInvalidType();
14669  }
14670 
14671  // Get the visibility (access control) for this ivar.
14673  Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14675  // Must set ivar's DeclContext to its enclosing interface.
14676  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14677  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14678  return nullptr;
14679  ObjCContainerDecl *EnclosingContext;
14680  if (ObjCImplementationDecl *IMPDecl =
14681  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14682  if (LangOpts.ObjCRuntime.isFragile()) {
14683  // Case of ivar declared in an implementation. Context is that of its class.
14684  EnclosingContext = IMPDecl->getClassInterface();
14685  assert(EnclosingContext && "Implementation has no class interface!");
14686  }
14687  else
14688  EnclosingContext = EnclosingDecl;
14689  } else {
14690  if (ObjCCategoryDecl *CDecl =
14691  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14692  if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14693  Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14694  return nullptr;
14695  }
14696  }
14697  EnclosingContext = EnclosingDecl;
14698  }
14699 
14700  // Construct the decl.
14701  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14702  DeclStart, Loc, II, T,
14703  TInfo, ac, (Expr *)BitfieldWidth);
14704 
14705  if (II) {
14706  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14707  ForVisibleRedeclaration);
14708  if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14709  && !isa<TagDecl>(PrevDecl)) {
14710  Diag(Loc, diag::err_duplicate_member) << II;
14711  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14712  NewID->setInvalidDecl();
14713  }
14714  }
14715 
14716  // Process attributes attached to the ivar.
14717  ProcessDeclAttributes(S, NewID, D);
14718 
14719  if (D.isInvalidType())
14720  NewID->setInvalidDecl();
14721 
14722  // In ARC, infer 'retaining' for ivars of retainable type.
14723  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14724  NewID->setInvalidDecl();
14725 
14727  NewID->setModulePrivate();
14728 
14729  if (II) {
14730  // FIXME: When interfaces are DeclContexts, we'll need to add
14731  // these to the interface.
14732  S->AddDecl(NewID);
14733  IdResolver.AddDecl(NewID);
14734  }
14735 
14736  if (LangOpts.ObjCRuntime.isNonFragile() &&
14737  !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14738  Diag(Loc, diag::warn_ivars_in_interface);
14739 
14740  return NewID;
14741 }
14742 
14743 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14744 /// class and class extensions. For every class \@interface and class
14745 /// extension \@interface, if the last ivar is a bitfield of any type,
14746 /// then add an implicit `char :0` ivar to the end of that interface.
14748  SmallVectorImpl<Decl *> &AllIvarDecls) {
14749  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14750  return;
14751 
14752  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14753  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14754 
14755  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14756  return;
14757  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14758  if (!ID) {
14759  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14760  if (!CD->IsClassExtension())
14761  return;
14762  }
14763  // No need to add this to end of @implementation.
14764  else
14765  return;
14766  }
14767  // All conditions are met. Add a new bitfield to the tail end of ivars.
14768  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14769  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14770 
14771  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14772  DeclLoc, DeclLoc, nullptr,
14773  Context.CharTy,
14774  Context.getTrivialTypeSourceInfo(Context.CharTy,
14775  DeclLoc),
14777  true);
14778  AllIvarDecls.push_back(Ivar);
14779 }
14780 
14781 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14782  ArrayRef<Decl *> Fields, SourceLocation LBrac,
14783  SourceLocation RBrac, AttributeList *Attr) {
14784  assert(EnclosingDecl && "missing record or interface decl");
14785 
14786  // If this is an Objective-C @implementation or category and we have
14787  // new fields here we should reset the layout of the interface since
14788  // it will now change.
14789  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14790  ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14791  switch (DC->getKind()) {
14792  default: break;
14793  case Decl::ObjCCategory:
14794  Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14795  break;
14796  case Decl::ObjCImplementation:
14797  Context.
14798  ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14799  break;
14800  }
14801  }
14802 
14803  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14804 
14805  // Start counting up the number of named members; make sure to include
14806  // members of anonymous structs and unions in the total.
14807  unsigned NumNamedMembers = 0;
14808  if (Record) {
14809  for (const auto *I : Record->decls()) {
14810  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14811  if (IFD->getDeclName())
14812  ++NumNamedMembers;
14813  }
14814  }
14815 
14816  // Verify that all the fields are okay.
14817  SmallVector<FieldDecl*, 32> RecFields;
14818 
14819  bool ObjCFieldLifetimeErrReported = false;
14820  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14821  i != end; ++i) {
14822  FieldDecl *FD = cast<FieldDecl>(*i);
14823 
14824  // Get the type for the field.
14825  const Type *FDTy = FD->getType().getTypePtr();
14826 
14827  if (!FD->isAnonymousStructOrUnion()) {
14828  // Remember all fields written by the user.
14829  RecFields.push_back(FD);
14830  }
14831 
14832  // If the field is already invalid for some reason, don't emit more
14833  // diagnostics about it.
14834  if (FD->isInvalidDecl()) {
14835  EnclosingDecl->setInvalidDecl();
14836  continue;
14837  }
14838 
14839  // C99 6.7.2.1p2:
14840  // A structure or union shall not contain a member with
14841  // incomplete or function type (hence, a structure shall not
14842  // contain an instance of itself, but may contain a pointer to
14843  // an instance of itself), except that the last member of a
14844  // structure with more than one named member may have incomplete
14845  // array type; such a structure (and any union containing,
14846  // possibly recursively, a member that is such a structure)
14847  // shall not be a member of a structure or an element of an
14848  // array.
14849  bool IsLastField = (i + 1 == Fields.end());
14850  if (FDTy->isFunctionType()) {
14851  // Field declared as a function.
14852  Diag(FD->getLocation(), diag::err_field_declared_as_function)
14853  << FD->getDeclName();
14854  FD->setInvalidDecl();
14855  EnclosingDecl->setInvalidDecl();
14856  continue;
14857  } else if (FDTy->isIncompleteArrayType() &&
14858  (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
14859  if (Record) {
14860  // Flexible array member.
14861  // Microsoft and g++ is more permissive regarding flexible array.
14862  // It will accept flexible array in union and also
14863  // as the sole element of a struct/class.
14864  unsigned DiagID = 0;
14865  if (!Record->isUnion() && !IsLastField) {
14866  Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
14867  << FD->getDeclName() << FD->getType() << Record->getTagKind();
14868  Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
14869  FD->setInvalidDecl();
14870  EnclosingDecl->setInvalidDecl();
14871  continue;
14872  } else if (Record->isUnion())
14873  DiagID = getLangOpts().MicrosoftExt
14874  ? diag::ext_flexible_array_union_ms
14875  : getLangOpts().CPlusPlus
14876  ? diag::ext_flexible_array_union_gnu
14877  : diag::err_flexible_array_union;
14878  else if (NumNamedMembers < 1)
14879  DiagID = getLangOpts().MicrosoftExt
14880  ? diag::ext_flexible_array_empty_aggregate_ms
14881  : getLangOpts().CPlusPlus
14882  ? diag::ext_flexible_array_empty_aggregate_gnu
14883  : diag::err_flexible_array_empty_aggregate;
14884 
14885  if (DiagID)
14886  Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14887  << Record->getTagKind();
14888  // While the layout of types that contain virtual bases is not specified
14889  // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14890  // virtual bases after the derived members. This would make a flexible
14891  // array member declared at the end of an object not adjacent to the end
14892  // of the type.
14893  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14894  if (RD->getNumVBases() != 0)
14895  Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14896  << FD->getDeclName() << Record->getTagKind();
14897  if (!getLangOpts().C99)
14898  Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14899  << FD->getDeclName() << Record->getTagKind();
14900 
14901  // If the element type has a non-trivial destructor, we would not
14902  // implicitly destroy the elements, so disallow it for now.
14903  //
14904  // FIXME: GCC allows this. We should probably either implicitly delete
14905  // the destructor of the containing class, or just allow this.
14906  QualType BaseElem = Context.getBaseElementType(FD->getType());
14907  if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14908  Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14909  << FD->getDeclName() << FD->getType();
14910  FD->setInvalidDecl();
14911  EnclosingDecl->setInvalidDecl();
14912  continue;
14913  }
14914  // Okay, we have a legal flexible array member at the end of the struct.
14915  Record->setHasFlexibleArrayMember(true);
14916  } else {
14917  // In ObjCContainerDecl ivars with incomplete array type are accepted,
14918  // unless they are followed by another ivar. That check is done
14919  // elsewhere, after synthesized ivars are known.
14920  }
14921  } else if (!FDTy->isDependentType() &&
14922  RequireCompleteType(FD->getLocation(), FD->getType(),
14923  diag::err_field_incomplete)) {
14924  // Incomplete type
14925  FD->setInvalidDecl();
14926  EnclosingDecl->setInvalidDecl();
14927  continue;
14928  } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14929  if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14930  // A type which contains a flexible array member is considered to be a
14931  // flexible array member.
14932  Record->setHasFlexibleArrayMember(true);
14933  if (!Record->isUnion()) {
14934  // If this is a struct/class and this is not the last element, reject
14935  // it. Note that GCC supports variable sized arrays in the middle of
14936  // structures.
14937  if (!IsLastField)
14938  Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14939  << FD->getDeclName() << FD->getType();
14940  else {
14941  // We support flexible arrays at the end of structs in
14942  // other structs as an extension.
14943  Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14944  << FD->getDeclName();
14945  }
14946  }
14947  }
14948  if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14949  RequireNonAbstractType(FD->getLocation(), FD->getType(),
14950  diag::err_abstract_type_in_decl,
14951  AbstractIvarType)) {
14952  // Ivars can not have abstract class types
14953  FD->setInvalidDecl();
14954  }
14955  if (Record && FDTTy->getDecl()->hasObjectMember())
14956  Record->setHasObjectMember(true);
14957  if (Record && FDTTy->getDecl()->hasVolatileMember())
14958  Record->setHasVolatileMember(true);
14959  } else if (FDTy->isObjCObjectType()) {
14960  /// A field cannot be an Objective-c object
14961  Diag(FD->getLocation(), diag::err_statically_allocated_object)
14962  << FixItHint::CreateInsertion(FD->getLocation(), "*");
14963  QualType T = Context.getObjCObjectPointerType(FD->getType());
14964  FD->setType(T);
14965  } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14966  Record && !ObjCFieldLifetimeErrReported &&
14967  (!getLangOpts().CPlusPlus || Record->isUnion())) {
14968  // It's an error in ARC or Weak if a field has lifetime.
14969  // We don't want to report this in a system header, though,
14970  // so we just make the field unavailable.
14971  // FIXME: that's really not sufficient; we need to make the type
14972  // itself invalid to, say, initialize or copy.
14973  QualType T = FD->getType();
14974  if (T.hasNonTrivialObjCLifetime()) {
14975  SourceLocation loc = FD->getLocation();
14976  if (getSourceManager().isInSystemHeader(loc)) {
14977  if (!FD->hasAttr<UnavailableAttr>()) {
14978  FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14979  UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14980  }
14981  } else {
14982  Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14983  << T->isBlockPointerType() << Record->getTagKind();
14984  }
14985  ObjCFieldLifetimeErrReported = true;
14986  }
14987  } else if (getLangOpts().ObjC1 &&
14988  getLangOpts().getGC() != LangOptions::NonGC &&
14989  Record && !Record->hasObjectMember()) {
14990  if (FD->getType()->isObjCObjectPointerType() ||
14991  FD->getType().isObjCGCStrong())
14992  Record->setHasObjectMember(true);
14993  else if (Context.getAsArrayType(FD->getType())) {
14994  QualType BaseType = Context.getBaseElementType(FD->getType());
14995  if (BaseType->isRecordType() &&
14996  BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14997  Record->setHasObjectMember(true);
14998  else if (BaseType->isObjCObjectPointerType() ||
14999  BaseType.isObjCGCStrong())
15000  Record->setHasObjectMember(true);
15001  }
15002  }
15003  if (Record && FD->getType().isVolatileQualified())
15004  Record->setHasVolatileMember(true);
15005  // Keep track of the number of named members.
15006  if (FD->getIdentifier())
15007  ++NumNamedMembers;
15008  }
15009 
15010  // Okay, we successfully defined 'Record'.
15011  if (Record) {
15012  bool Completed = false;
15013  if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15014  if (!CXXRecord->isInvalidDecl()) {
15015  // Set access bits correctly on the directly-declared conversions.
15017  I = CXXRecord->conversion_begin(),
15018  E = CXXRecord->conversion_end(); I != E; ++I)
15019  I.setAccess((*I)->getAccess());
15020  }
15021 
15022  if (!CXXRecord->isDependentType()) {
15023  if (CXXRecord->hasUserDeclaredDestructor()) {
15024  // Adjust user-defined destructor exception spec.
15025  if (getLangOpts().CPlusPlus11)
15026  AdjustDestructorExceptionSpec(CXXRecord,
15027  CXXRecord->getDestructor());
15028  }
15029 
15030  if (!CXXRecord->isInvalidDecl()) {
15031  // Add any implicitly-declared members to this class.
15032  AddImplicitlyDeclaredMembersToClass(CXXRecord);
15033 
15034  // If we have virtual base classes, we may end up finding multiple
15035  // final overriders for a given virtual function. Check for this
15036  // problem now.
15037  if (CXXRecord->getNumVBases()) {
15038  CXXFinalOverriderMap FinalOverriders;
15039  CXXRecord->getFinalOverriders(FinalOverriders);
15040 
15041  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15042  MEnd = FinalOverriders.end();
15043  M != MEnd; ++M) {
15044  for (OverridingMethods::iterator SO = M->second.begin(),
15045  SOEnd = M->second.end();
15046  SO != SOEnd; ++SO) {
15047  assert(SO->second.size() > 0 &&
15048  "Virtual function without overridding functions?");
15049  if (SO->second.size() == 1)
15050  continue;
15051 
15052  // C++ [class.virtual]p2:
15053  // In a derived class, if a virtual member function of a base
15054  // class subobject has more than one final overrider the
15055  // program is ill-formed.
15056  Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15057  << (const NamedDecl *)M->first << Record;
15058  Diag(M->first->getLocation(),
15059  diag::note_overridden_virtual_function);
15061  OM = SO->second.begin(),
15062  OMEnd = SO->second.end();
15063  OM != OMEnd; ++OM)
15064  Diag(OM->Method->getLocation(), diag::note_final_overrider)
15065  << (const NamedDecl *)M->first << OM->Method->getParent();
15066 
15067  Record->setInvalidDecl();
15068  }
15069  }
15070  CXXRecord->completeDefinition(&FinalOverriders);
15071  Completed = true;
15072  }
15073  }
15074  }
15075  }
15076 
15077  if (!Completed)
15078  Record->completeDefinition();
15079 
15080  // We may have deferred checking for a deleted destructor. Check now.
15081  if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15082  auto *Dtor = CXXRecord->getDestructor();
15083  if (Dtor && Dtor->isImplicit() &&
15084  ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15085  CXXRecord->setImplicitDestructorIsDeleted();
15086  SetDeclDeleted(Dtor, CXXRecord->getLocation());
15087  }
15088  }
15089 
15090  if (Record->hasAttrs()) {
15091  CheckAlignasUnderalignment(Record);
15092 
15093  if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15094  checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15095  IA->getRange(), IA->getBestCase(),
15096  IA->getSemanticSpelling());
15097  }
15098 
15099  // Check if the structure/union declaration is a type that can have zero
15100  // size in C. For C this is a language extension, for C++ it may cause
15101  // compatibility problems.
15102  bool CheckForZeroSize;
15103  if (!getLangOpts().CPlusPlus) {
15104  CheckForZeroSize = true;
15105  } else {
15106  // For C++ filter out types that cannot be referenced in C code.
15107  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15108  CheckForZeroSize =
15109  CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15110  !CXXRecord->isDependentType() &&
15111  CXXRecord->isCLike();
15112  }
15113  if (CheckForZeroSize) {
15114  bool ZeroSize = true;
15115  bool IsEmpty = true;
15116  unsigned NonBitFields = 0;
15117  for (RecordDecl::field_iterator I = Record->field_begin(),
15118  E = Record->field_end();
15119  (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15120  IsEmpty = false;
15121  if (I->isUnnamedBitfield()) {
15122  if (I->getBitWidthValue(Context) > 0)
15123  ZeroSize = false;
15124  } else {
15125  ++NonBitFields;
15126  QualType FieldType = I->getType();
15127  if (FieldType->isIncompleteType() ||
15128  !Context.getTypeSizeInChars(FieldType).isZero())
15129  ZeroSize = false;
15130  }
15131  }
15132 
15133  // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15134  // allowed in C++, but warn if its declaration is inside
15135  // extern "C" block.
15136  if (ZeroSize) {
15137  Diag(RecLoc, getLangOpts().CPlusPlus ?
15138  diag::warn_zero_size_struct_union_in_extern_c :
15139  diag::warn_zero_size_struct_union_compat)
15140  << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15141  }
15142 
15143  // Structs without named members are extension in C (C99 6.7.2.1p7),
15144  // but are accepted by GCC.
15145  if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15146  Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15147  diag::ext_no_named_members_in_struct_union)
15148  << Record->isUnion();
15149  }
15150  }
15151  } else {
15152  ObjCIvarDecl **ClsFields =
15153  reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15154  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15155  ID->setEndOfDefinitionLoc(RBrac);
15156  // Add ivar's to class's DeclContext.
15157  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15158  ClsFields[i]->setLexicalDeclContext(ID);
15159  ID->addDecl(ClsFields[i]);
15160  }
15161  // Must enforce the rule that ivars in the base classes may not be
15162  // duplicates.
15163  if (ID->getSuperClass())
15164  DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15165  } else if (ObjCImplementationDecl *IMPDecl =
15166  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15167  assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15168  for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15169  // Ivar declared in @implementation never belongs to the implementation.
15170  // Only it is in implementation's lexical context.
15171  ClsFields[I]->setLexicalDeclContext(IMPDecl);
15172  CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15173  IMPDecl->setIvarLBraceLoc(LBrac);
15174  IMPDecl->setIvarRBraceLoc(RBrac);
15175  } else if (ObjCCategoryDecl *CDecl =
15176  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15177  // case of ivars in class extension; all other cases have been
15178  // reported as errors elsewhere.
15179  // FIXME. Class extension does not have a LocEnd field.
15180  // CDecl->setLocEnd(RBrac);
15181  // Add ivar's to class extension's DeclContext.
15182  // Diagnose redeclaration of private ivars.
15183  ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15184  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15185  if (IDecl) {
15186  if (const ObjCIvarDecl *ClsIvar =
15187  IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15188  Diag(ClsFields[i]->getLocation(),
15189  diag::err_duplicate_ivar_declaration);
15190  Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15191  continue;
15192  }
15193  for (const auto *Ext : IDecl->known_extensions()) {
15194  if (const ObjCIvarDecl *ClsExtIvar
15195  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15196  Diag(ClsFields[i]->getLocation(),
15197  diag::err_duplicate_ivar_declaration);
15198  Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15199  continue;
15200  }
15201  }
15202  }
15203  ClsFields[i]->setLexicalDeclContext(CDecl);
15204  CDecl->addDecl(ClsFields[i]);
15205  }
15206  CDecl->setIvarLBraceLoc(LBrac);
15207  CDecl->setIvarRBraceLoc(RBrac);
15208  }
15209  }
15210 
15211  if (Attr)
15212  ProcessDeclAttributeList(S, Record, Attr);
15213 }
15214 
15215 /// \brief Determine whether the given integral value is representable within
15216 /// the given type T.
15218  llvm::APSInt &Value,
15219  QualType T) {
15220  assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15221  "Integral type required!");
15222  unsigned BitWidth = Context.getIntWidth(T);
15223 
15224  if (Value.isUnsigned() || Value.isNonNegative()) {
15226  --BitWidth;
15227  return Value.getActiveBits() <= BitWidth;
15228  }
15229  return Value.getMinSignedBits() <= BitWidth;
15230 }
15231 
15232 // \brief Given an integral type, return the next larger integral type
15233 // (or a NULL type of no such type exists).
15235  // FIXME: Int128/UInt128 support, which also needs to be introduced into
15236  // enum checking below.
15237  assert((T->isIntegralType(Context) ||
15238  T->isEnumeralType()) && "Integral type required!");
15239  const unsigned NumTypes = 4;
15240  QualType SignedIntegralTypes[NumTypes] = {
15241  Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15242  };
15243  QualType UnsignedIntegralTypes[NumTypes] = {
15244  Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15245  Context.UnsignedLongLongTy
15246  };
15247 
15248  unsigned BitWidth = Context.getTypeSize(T);
15249  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15250  : UnsignedIntegralTypes;
15251  for (unsigned I = 0; I != NumTypes; ++I)
15252  if (Context.getTypeSize(Types[I]) > BitWidth)
15253  return Types[I];
15254 
15255  return QualType();
15256 }
15257 
15259  EnumConstantDecl *LastEnumConst,
15260  SourceLocation IdLoc,
15261  IdentifierInfo *Id,
15262  Expr *Val) {
15263  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15264  llvm::APSInt EnumVal(IntWidth);
15265  QualType EltTy;
15266 
15267  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15268  Val = nullptr;
15269 
15270  if (Val)
15271  Val = DefaultLvalueConversion(Val).get();
15272 
15273  if (Val) {
15274  if (Enum->isDependentType() || Val->isTypeDependent())
15275  EltTy = Context.DependentTy;
15276  else {
15277  if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15278  !getLangOpts().MSVCCompat) {
15279  // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15280  // constant-expression in the enumerator-definition shall be a converted
15281  // constant expression of the underlying type.
15282  EltTy = Enum->getIntegerType();
15283  ExprResult Converted =
15284  CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15285  CCEK_Enumerator);
15286  if (Converted.isInvalid())
15287  Val = nullptr;
15288  else
15289  Val = Converted.get();
15290  } else if (!Val->isValueDependent() &&
15291  !(Val = VerifyIntegerConstantExpression(Val,
15292  &EnumVal).get())) {
15293  // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15294  } else {
15295  if (Enum->isFixed()) {
15296  EltTy = Enum->getIntegerType();
15297 
15298  // In Obj-C and Microsoft mode, require the enumeration value to be
15299  // representable in the underlying type of the enumeration. In C++11,
15300  // we perform a non-narrowing conversion as part of converted constant
15301  // expression checking.
15302  if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15303  if (getLangOpts().MSVCCompat) {
15304  Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15305  Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15306  } else
15307  Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15308  } else
15309  Val = ImpCastExprToType(Val, EltTy,
15310  EltTy->isBooleanType() ?
15311  CK_IntegralToBoolean : CK_IntegralCast)
15312  .get();
15313  } else if (getLangOpts().CPlusPlus) {
15314  // C++11 [dcl.enum]p5:
15315  // If the underlying type is not fixed, the type of each enumerator
15316  // is the type of its initializing value:
15317  // - If an initializer is specified for an enumerator, the
15318  // initializing value has the same type as the expression.
15319  EltTy = Val->getType();
15320  } else {
15321  // C99 6.7.2.2p2:
15322  // The expression that defines the value of an enumeration constant
15323  // shall be an integer constant expression that has a value
15324  // representable as an int.
15325 
15326  // Complain if the value is not representable in an int.
15327  if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15328  Diag(IdLoc, diag::ext_enum_value_not_int)
15329  << EnumVal.toString(10) << Val->getSourceRange()
15330  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15331  else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15332  // Force the type of the expression to 'int'.
15333  Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15334  }
15335  EltTy = Val->getType();
15336  }
15337  }
15338  }
15339  }
15340 
15341  if (!Val) {
15342  if (Enum->isDependentType())
15343  EltTy = Context.DependentTy;
15344  else if (!LastEnumConst) {
15345  // C++0x [dcl.enum]p5:
15346  // If the underlying type is not fixed, the type of each enumerator
15347  // is the type of its initializing value:
15348  // - If no initializer is specified for the first enumerator, the
15349  // initializing value has an unspecified integral type.
15350  //
15351  // GCC uses 'int' for its unspecified integral type, as does
15352  // C99 6.7.2.2p3.
15353  if (Enum->isFixed()) {
15354  EltTy = Enum->getIntegerType();
15355  }
15356  else {
15357  EltTy = Context.IntTy;
15358  }
15359  } else {
15360  // Assign the last value + 1.
15361  EnumVal = LastEnumConst->getInitVal();
15362  ++EnumVal;
15363  EltTy = LastEnumConst->getType();
15364 
15365  // Check for overflow on increment.
15366  if (EnumVal < LastEnumConst->getInitVal()) {
15367  // C++0x [dcl.enum]p5:
15368  // If the underlying type is not fixed, the type of each enumerator
15369  // is the type of its initializing value:
15370  //
15371  // - Otherwise the type of the initializing value is the same as
15372  // the type of the initializing value of the preceding enumerator
15373  // unless the incremented value is not representable in that type,
15374  // in which case the type is an unspecified integral type
15375  // sufficient to contain the incremented value. If no such type
15376  // exists, the program is ill-formed.
15377  QualType T = getNextLargerIntegralType(Context, EltTy);
15378  if (T.isNull() || Enum->isFixed()) {
15379  // There is no integral type larger enough to represent this
15380  // value. Complain, then allow the value to wrap around.
15381  EnumVal = LastEnumConst->getInitVal();
15382  EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15383  ++EnumVal;
15384  if (Enum->isFixed())
15385  // When the underlying type is fixed, this is ill-formed.
15386  Diag(IdLoc, diag::err_enumerator_wrapped)
15387  << EnumVal.toString(10)
15388  << EltTy;
15389  else
15390  Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15391  << EnumVal.toString(10);
15392  } else {
15393  EltTy = T;
15394  }
15395 
15396  // Retrieve the last enumerator's value, extent that type to the
15397  // type that is supposed to be large enough to represent the incremented
15398  // value, then increment.
15399  EnumVal = LastEnumConst->getInitVal();
15400  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15401  EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15402  ++EnumVal;
15403 
15404  // If we're not in C++, diagnose the overflow of enumerator values,
15405  // which in C99 means that the enumerator value is not representable in
15406  // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15407  // permits enumerator values that are representable in some larger
15408  // integral type.
15409  if (!getLangOpts().CPlusPlus && !T.isNull())
15410  Diag(IdLoc, diag::warn_enum_value_overflow);
15411  } else if (!getLangOpts().CPlusPlus &&
15412  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15413  // Enforce C99 6.7.2.2p2 even when we compute the next value.
15414  Diag(IdLoc, diag::ext_enum_value_not_int)
15415  << EnumVal.toString(10) << 1;
15416  }
15417  }
15418  }
15419 
15420  if (!EltTy->isDependentType()) {
15421  // Make the enumerator value match the signedness and size of the
15422  // enumerator's type.
15423  EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15424  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15425  }
15426 
15427  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15428  Val, EnumVal);
15429 }
15430 
15432  SourceLocation IILoc) {
15433  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15434  !getLangOpts().CPlusPlus)
15435  return SkipBodyInfo();
15436 
15437  // We have an anonymous enum definition. Look up the first enumerator to
15438  // determine if we should merge the definition with an existing one and
15439  // skip the body.
15440  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15441  forRedeclarationInCurContext());
15442  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15443  if (!PrevECD)
15444  return SkipBodyInfo();
15445 
15446  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15447  NamedDecl *Hidden;
15448  if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15449  SkipBodyInfo Skip;
15450  Skip.Previous = Hidden;
15451  return Skip;
15452  }
15453 
15454  return SkipBodyInfo();
15455 }
15456 
15457 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15460  SourceLocation EqualLoc, Expr *Val) {
15461  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15462  EnumConstantDecl *LastEnumConst =
15463  cast_or_null<EnumConstantDecl>(lastEnumConst);
15464 
15465  // The scope passed in may not be a decl scope. Zip up the scope tree until
15466  // we find one that is.
15467  S = getNonFieldDeclScope(S);
15468 
15469  // Verify that there isn't already something declared with this name in this
15470  // scope.
15471  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15472  ForVisibleRedeclaration);
15473  if (PrevDecl && PrevDecl->isTemplateParameter()) {
15474  // Maybe we will complain about the shadowed template parameter.
15475  DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15476  // Just pretend that we didn't see the previous declaration.
15477  PrevDecl = nullptr;
15478  }
15479 
15480  // C++ [class.mem]p15:
15481  // If T is the name of a class, then each of the following shall have a name
15482  // different from T:
15483  // - every enumerator of every member of class T that is an unscoped
15484  // enumerated type
15485  if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15486  DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15487  DeclarationNameInfo(Id, IdLoc));
15488 
15489  EnumConstantDecl *New =
15490  CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15491  if (!New)
15492  return nullptr;
15493 
15494  if (PrevDecl) {
15495  // When in C++, we may get a TagDecl with the same name; in this case the
15496  // enum constant will 'hide' the tag.
15497  assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15498  "Received TagDecl when not in C++!");
15499  if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15500  if (isa<EnumConstantDecl>(PrevDecl))
15501  Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15502  else
15503  Diag(IdLoc, diag::err_redefinition) << Id;
15504  notePreviousDefinition(PrevDecl, IdLoc);
15505  return nullptr;
15506  }
15507  }
15508 
15509  // Process attributes.
15510  if (Attr) ProcessDeclAttributeList(S, New, Attr);
15511  AddPragmaAttributes(S, New);
15512 
15513  // Register this decl in the current scope stack.
15514  New->setAccess(TheEnumDecl->getAccess());
15515  PushOnScopeChains(New, S);
15516 
15517  ActOnDocumentableDecl(New);
15518 
15519  return New;
15520 }
15521 
15522 // Returns true when the enum initial expression does not trigger the
15523 // duplicate enum warning. A few common cases are exempted as follows:
15524 // Element2 = Element1
15525 // Element2 = Element1 + 1
15526 // Element2 = Element1 - 1
15527 // Where Element2 and Element1 are from the same enum.
15529  Expr *InitExpr = ECD->getInitExpr();
15530  if (!InitExpr)
15531  return true;
15532  InitExpr = InitExpr->IgnoreImpCasts();
15533 
15534  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15535  if (!BO->isAdditiveOp())
15536  return true;
15537  IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15538  if (!IL)
15539  return true;
15540  if (IL->getValue() != 1)
15541  return true;
15542 
15543  InitExpr = BO->getLHS();
15544  }
15545 
15546  // This checks if the elements are from the same enum.
15547  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15548  if (!DRE)
15549  return true;
15550 
15551  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15552  if (!EnumConstant)
15553  return true;
15554 
15555  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15556  Enum)
15557  return true;
15558 
15559  return false;
15560 }
15561 
15562 namespace {
15563 struct DupKey {
15564  int64_t val;
15565  bool isTombstoneOrEmptyKey;
15566  DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15567  : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15568 };
15569 
15570 static DupKey GetDupKey(const llvm::APSInt& Val) {
15571  return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15572  false);
15573 }
15574 
15575 struct DenseMapInfoDupKey {
15576  static DupKey getEmptyKey() { return DupKey(0, true); }
15577  static DupKey getTombstoneKey() { return DupKey(1, true); }
15578  static unsigned getHashValue(const DupKey Key) {
15579  return (unsigned)(Key.val * 37);
15580  }
15581  static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15582  return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15583  LHS.val == RHS.val;
15584  }
15585 };
15586 } // end anonymous namespace
15587 
15588 // Emits a warning when an element is implicitly set a value that
15589 // a previous element has already been set to.
15591  EnumDecl *Enum,
15592  QualType EnumType) {
15593  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15594  return;
15595  // Avoid anonymous enums
15596  if (!Enum->getIdentifier())
15597  return;
15598 
15599  // Only check for small enums.
15600  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15601  return;
15602 
15603  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15604  typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15605 
15606  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15607  typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15608  ValueToVectorMap;
15609 
15610  DuplicatesVector DupVector;
15611  ValueToVectorMap EnumMap;
15612 
15613  // Populate the EnumMap with all values represented by enum constants without
15614  // an initialier.
15615  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15616  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15617 
15618  // Null EnumConstantDecl means a previous diagnostic has been emitted for
15619  // this constant. Skip this enum since it may be ill-formed.
15620  if (!ECD) {
15621  return;
15622  }
15623 
15624  if (ECD->getInitExpr())
15625  continue;
15626 
15627  DupKey Key = GetDupKey(ECD->getInitVal());
15628  DeclOrVector &Entry = EnumMap[Key];
15629 
15630  // First time encountering this value.
15631  if (Entry.isNull())
15632  Entry = ECD;
15633  }
15634 
15635  // Create vectors for any values that has duplicates.
15636  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15637  EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15638  if (!ValidDuplicateEnum(ECD, Enum))
15639  continue;
15640 
15641  DupKey Key = GetDupKey(ECD->getInitVal());
15642 
15643  DeclOrVector& Entry = EnumMap[Key];
15644  if (Entry.isNull())
15645  continue;
15646 
15647  if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15648  // Ensure constants are different.
15649  if (D == ECD)
15650  continue;
15651 
15652  // Create new vector and push values onto it.
15653  ECDVector *Vec = new ECDVector();
15654  Vec->push_back(D);
15655  Vec->push_back(ECD);
15656 
15657  // Update entry to point to the duplicates vector.
15658  Entry = Vec;
15659 
15660  // Store the vector somewhere we can consult later for quick emission of
15661  // diagnostics.
15662  DupVector.push_back(Vec);
15663  continue;
15664  }
15665 
15666  ECDVector *Vec = Entry.get<ECDVector*>();
15667  // Make sure constants are not added more than once.
15668  if (*Vec->begin() == ECD)
15669  continue;
15670 
15671  Vec->push_back(ECD);
15672  }
15673 
15674  // Emit diagnostics.
15675  for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15676  DupVectorEnd = DupVector.end();
15677  DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15678  ECDVector *Vec = *DupVectorIter;
15679  assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15680 
15681  // Emit warning for one enum constant.
15682  ECDVector::iterator I = Vec->begin();
15683  S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15684  << (*I)->getName() << (*I)->getInitVal().toString(10)
15685  << (*I)->getSourceRange();
15686  ++I;
15687 
15688  // Emit one note for each of the remaining enum constants with
15689  // the same value.
15690  for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15691  S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15692  << (*I)->getName() << (*I)->getInitVal().toString(10)
15693  << (*I)->getSourceRange();
15694  delete Vec;
15695  }
15696 }
15697 
15698 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15699  bool AllowMask) const {
15700  assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15701  assert(ED->isCompleteDefinition() && "expected enum definition");
15702 
15703  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15704  llvm::APInt &FlagBits = R.first->second;
15705 
15706  if (R.second) {
15707  for (auto *E : ED->enumerators()) {
15708  const auto &EVal = E->getInitVal();
15709  // Only single-bit enumerators introduce new flag values.
15710  if (EVal.isPowerOf2())
15711  FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15712  }
15713  }
15714 
15715  // A value is in a flag enum if either its bits are a subset of the enum's
15716  // flag bits (the first condition) or we are allowing masks and the same is
15717  // true of its complement (the second condition). When masks are allowed, we
15718  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15719  //
15720  // While it's true that any value could be used as a mask, the assumption is
15721  // that a mask will have all of the insignificant bits set. Anything else is
15722  // likely a logic error.
15723  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15724  return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15725 }
15726 
15728  Decl *EnumDeclX,
15729  ArrayRef<Decl *> Elements,
15730  Scope *S, AttributeList *Attr) {
15731  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15732  QualType EnumType = Context.getTypeDeclType(Enum);
15733 
15734  if (Attr)
15735  ProcessDeclAttributeList(S, Enum, Attr);
15736 
15737  if (Enum->isDependentType()) {
15738  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15739  EnumConstantDecl *ECD =
15740  cast_or_null<EnumConstantDecl>(Elements[i]);
15741  if (!ECD) continue;
15742 
15743  ECD->setType(EnumType);
15744  }
15745 
15746  Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15747  return;
15748  }
15749 
15750  // TODO: If the result value doesn't fit in an int, it must be a long or long
15751  // long value. ISO C does not support this, but GCC does as an extension,
15752  // emit a warning.
15753  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15754  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15755  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15756 
15757  // Verify that all the values are okay, compute the size of the values, and
15758  // reverse the list.
15759  unsigned NumNegativeBits = 0;
15760  unsigned NumPositiveBits = 0;
15761 
15762  // Keep track of whether all elements have type int.
15763  bool AllElementsInt = true;
15764 
15765  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15766  EnumConstantDecl *ECD =
15767  cast_or_null<EnumConstantDecl>(Elements[i]);
15768  if (!ECD) continue; // Already issued a diagnostic.
15769 
15770  const llvm::APSInt &InitVal = ECD->getInitVal();
15771 
15772  // Keep track of the size of positive and negative values.
15773  if (InitVal.isUnsigned() || InitVal.isNonNegative())
15774  NumPositiveBits = std::max(NumPositiveBits,
15775  (unsigned)InitVal.getActiveBits());
15776  else
15777  NumNegativeBits = std::max(NumNegativeBits,
15778  (unsigned)InitVal.getMinSignedBits());
15779 
15780  // Keep track of whether every enum element has type int (very commmon).
15781  if (AllElementsInt)
15782  AllElementsInt = ECD->getType() == Context.IntTy;
15783  }
15784 
15785  // Figure out the type that should be used for this enum.
15786  QualType BestType;
15787  unsigned BestWidth;
15788 
15789  // C++0x N3000 [conv.prom]p3:
15790  // An rvalue of an unscoped enumeration type whose underlying
15791  // type is not fixed can be converted to an rvalue of the first
15792  // of the following types that can represent all the values of
15793  // the enumeration: int, unsigned int, long int, unsigned long
15794  // int, long long int, or unsigned long long int.
15795  // C99 6.4.4.3p2:
15796  // An identifier declared as an enumeration constant has type int.
15797  // The C99 rule is modified by a gcc extension
15798  QualType BestPromotionType;
15799 
15800  bool Packed = Enum->hasAttr<PackedAttr>();
15801  // -fshort-enums is the equivalent to specifying the packed attribute on all
15802  // enum definitions.
15803  if (LangOpts.ShortEnums)
15804  Packed = true;
15805 
15806  if (Enum->isFixed()) {
15807  BestType = Enum->getIntegerType();
15808  if (BestType->isPromotableIntegerType())
15809  BestPromotionType = Context.getPromotedIntegerType(BestType);
15810  else
15811  BestPromotionType = BestType;
15812 
15813  BestWidth = Context.getIntWidth(BestType);
15814  }
15815  else if (NumNegativeBits) {
15816  // If there is a negative value, figure out the smallest integer type (of
15817  // int/long/longlong) that fits.
15818  // If it's packed, check also if it fits a char or a short.
15819  if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15820  BestType = Context.SignedCharTy;
15821  BestWidth = CharWidth;
15822  } else if (Packed && NumNegativeBits <= ShortWidth &&
15823  NumPositiveBits < ShortWidth) {
15824  BestType = Context.ShortTy;
15825  BestWidth = ShortWidth;
15826  } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15827  BestType = Context.IntTy;
15828  BestWidth = IntWidth;
15829  } else {
15830  BestWidth = Context.getTargetInfo().getLongWidth();
15831 
15832  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15833  BestType = Context.LongTy;
15834  } else {
15835  BestWidth = Context.getTargetInfo().getLongLongWidth();
15836 
15837  if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15838  Diag(Enum->getLocation(), diag::ext_enum_too_large);
15839  BestType = Context.LongLongTy;
15840  }
15841  }
15842  BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15843  } else {
15844  // If there is no negative value, figure out the smallest type that fits
15845  // all of the enumerator values.
15846  // If it's packed, check also if it fits a char or a short.
15847  if (Packed && NumPositiveBits <= CharWidth) {
15848  BestType = Context.UnsignedCharTy;
15849  BestPromotionType = Context.IntTy;
15850  BestWidth = CharWidth;
15851  } else if (Packed && NumPositiveBits <= ShortWidth) {
15852  BestType = Context.UnsignedShortTy;
15853  BestPromotionType = Context.IntTy;
15854  BestWidth = ShortWidth;
15855  } else if (NumPositiveBits <= IntWidth) {
15856  BestType = Context.UnsignedIntTy;
15857  BestWidth = IntWidth;
15858  BestPromotionType
15859  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15860  ? Context.UnsignedIntTy : Context.IntTy;
15861  } else if (NumPositiveBits <=
15862  (BestWidth = Context.getTargetInfo().getLongWidth())) {
15863  BestType = Context.UnsignedLongTy;
15864  BestPromotionType
15865  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15866  ? Context.UnsignedLongTy : Context.LongTy;
15867  } else {
15868  BestWidth = Context.getTargetInfo().getLongLongWidth();
15869  assert(NumPositiveBits <= BestWidth &&
15870  "How could an initializer get larger than ULL?");
15871  BestType = Context.UnsignedLongLongTy;
15872  BestPromotionType
15873  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15874  ? Context.UnsignedLongLongTy : Context.LongLongTy;
15875  }
15876  }
15877 
15878  // Loop over all of the enumerator constants, changing their types to match
15879  // the type of the enum if needed.
15880  for (auto *D : Elements) {
15881  auto *ECD = cast_or_null<EnumConstantDecl>(D);
15882  if (!ECD) continue; // Already issued a diagnostic.
15883 
15884  // Standard C says the enumerators have int type, but we allow, as an
15885  // extension, the enumerators to be larger than int size. If each
15886  // enumerator value fits in an int, type it as an int, otherwise type it the
15887  // same as the enumerator decl itself. This means that in "enum { X = 1U }"
15888  // that X has type 'int', not 'unsigned'.
15889 
15890  // Determine whether the value fits into an int.
15891  llvm::APSInt InitVal = ECD->getInitVal();
15892 
15893  // If it fits into an integer type, force it. Otherwise force it to match
15894  // the enum decl type.
15895  QualType NewTy;
15896  unsigned NewWidth;
15897  bool NewSign;
15898  if (!getLangOpts().CPlusPlus &&
15899  !Enum->isFixed() &&
15900  isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15901  NewTy = Context.IntTy;
15902  NewWidth = IntWidth;
15903  NewSign = true;
15904  } else if (ECD->getType() == BestType) {
15905  // Already the right type!
15906  if (getLangOpts().CPlusPlus)
15907  // C++ [dcl.enum]p4: Following the closing brace of an
15908  // enum-specifier, each enumerator has the type of its
15909  // enumeration.
15910  ECD->setType(EnumType);
15911  continue;
15912  } else {
15913  NewTy = BestType;
15914  NewWidth = BestWidth;
15915  NewSign = BestType->isSignedIntegerOrEnumerationType();
15916  }
15917 
15918  // Adjust the APSInt value.
15919  InitVal = InitVal.extOrTrunc(NewWidth);
15920  InitVal.setIsSigned(NewSign);
15921  ECD->setInitVal(InitVal);
15922 
15923  // Adjust the Expr initializer and type.
15924  if (ECD->getInitExpr() &&
15925  !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15926  ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15927  CK_IntegralCast,
15928  ECD->getInitExpr(),
15929  /*base paths*/ nullptr,
15930  VK_RValue));
15931  if (getLangOpts().CPlusPlus)
15932  // C++ [dcl.enum]p4: Following the closing brace of an
15933  // enum-specifier, each enumerator has the type of its
15934  // enumeration.
15935  ECD->setType(EnumType);
15936  else
15937  ECD->setType(NewTy);
15938  }
15939 
15940  Enum->completeDefinition(BestType, BestPromotionType,
15941  NumPositiveBits, NumNegativeBits);
15942 
15943  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15944 
15945  if (Enum->isClosedFlag()) {
15946  for (Decl *D : Elements) {
15947  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15948  if (!ECD) continue; // Already issued a diagnostic.
15949 
15950  llvm::APSInt InitVal = ECD->getInitVal();
15951  if (InitVal != 0 && !InitVal.isPowerOf2() &&
15952  !IsValueInFlagEnum(Enum, InitVal, true))
15953  Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15954  << ECD << Enum;
15955  }
15956  }
15957 
15958  // Now that the enum type is defined, ensure it's not been underaligned.
15959  if (Enum->hasAttrs())
15960  CheckAlignasUnderalignment(Enum);
15961 }
15962 
15964  SourceLocation StartLoc,
15965  SourceLocation EndLoc) {
15966  StringLiteral *AsmString = cast<StringLiteral>(expr);
15967 
15968  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15969  AsmString, StartLoc,
15970  EndLoc);
15971  CurContext->addDecl(New);
15972  return New;
15973 }
15974 
15976  SourceLocation ImportLoc, DeclContext *DC,
15977  bool FromInclude = false) {
15978  SourceLocation ExternCLoc;
15979 
15980  if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15981  switch (LSD->getLanguage()) {
15983  if (ExternCLoc.isInvalid())
15984  ExternCLoc = LSD->getLocStart();
15985  break;
15987  break;
15988  }
15989  DC = LSD->getParent();
15990  }
15991 
15992  while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
15993  DC = DC->getParent();
15994 
15995  if (!isa<TranslationUnitDecl>(DC)) {
15996  S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15997  ? diag::ext_module_import_not_at_top_level_noop
15998  : diag::err_module_import_not_at_top_level_fatal)
15999  << M->getFullModuleName() << DC;
16000  S.Diag(cast<Decl>(DC)->getLocStart(),
16001  diag::note_module_import_not_at_top_level) << DC;
16002  } else if (!M->IsExternC && ExternCLoc.isValid()) {
16003  S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16004  << M->getFullModuleName();
16005  S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16006  }
16007 }
16008 
16010  SourceLocation ModuleLoc,
16011  ModuleDeclKind MDK,
16012  ModuleIdPath Path) {
16013  assert(getLangOpts().ModulesTS &&
16014  "should only have module decl in modules TS");
16015 
16016  // A module implementation unit requires that we are not compiling a module
16017  // of any kind. A module interface unit requires that we are not compiling a
16018  // module map.
16019  switch (getLangOpts().getCompilingModule()) {
16020  case LangOptions::CMK_None:
16021  // It's OK to compile a module interface as a normal translation unit.
16022  break;
16023 
16025  if (MDK != ModuleDeclKind::Implementation)
16026  break;
16027 
16028  // We were asked to compile a module interface unit but this is a module
16029  // implementation unit. That indicates the 'export' is missing.
16030  Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16031  << FixItHint::CreateInsertion(ModuleLoc, "export ");
16032  MDK = ModuleDeclKind::Interface;
16033  break;
16034 
16036  Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16037  return nullptr;
16038  }
16039 
16040  assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16041 
16042  // FIXME: Most of this work should be done by the preprocessor rather than
16043  // here, in order to support macro import.
16044 
16045  // Only one module-declaration is permitted per source file.
16046  if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16047  Diag(ModuleLoc, diag::err_module_redeclaration);
16048  Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16049  diag::note_prev_module_declaration);
16050  return nullptr;
16051  }
16052 
16053  // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16054  // modules, the dots here are just another character that can appear in a
16055  // module name.
16056  std::string ModuleName;
16057  for (auto &Piece : Path) {
16058  if (!ModuleName.empty())
16059  ModuleName += ".";
16060  ModuleName += Piece.first->getName();
16061  }
16062 
16063  // If a module name was explicitly specified on the command line, it must be
16064  // correct.
16065  if (!getLangOpts().CurrentModule.empty() &&
16066  getLangOpts().CurrentModule != ModuleName) {
16067  Diag(Path.front().second, diag::err_current_module_name_mismatch)
16068  << SourceRange(Path.front().second, Path.back().second)
16069  << getLangOpts().CurrentModule;
16070  return nullptr;
16071  }
16072  const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16073 
16074  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16075  Module *Mod;
16076 
16077  switch (MDK) {
16078  case ModuleDeclKind::Interface: {
16079  // We can't have parsed or imported a definition of this module or parsed a
16080  // module map defining it already.
16081  if (auto *M = Map.findModule(ModuleName)) {
16082  Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16083  if (M->DefinitionLoc.isValid())
16084  Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16085  else if (const auto *FE = M->getASTFile())
16086  Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16087  << FE->getName();
16088  Mod = M;
16089  break;
16090  }
16091 
16092  // Create a Module for the module that we're defining.
16093  Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16094  ModuleScopes.front().Module);
16095  assert(Mod && "module creation should not fail");
16096  break;
16097  }
16098 
16099  case ModuleDeclKind::Partition:
16100  // FIXME: Check we are in a submodule of the named module.
16101  return nullptr;
16102 
16103  case ModuleDeclKind::Implementation:
16104  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16105  PP.getIdentifierInfo(ModuleName), Path[0].second);
16106  Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16107  /*IsIncludeDirective=*/false);
16108  if (!Mod) {
16109  Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16110  // Create an empty module interface unit for error recovery.
16111  Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16112  ModuleScopes.front().Module);
16113  }
16114  break;
16115  }
16116 
16117  // Switch from the global module to the named module.
16118  ModuleScopes.back().Module = Mod;
16119  ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16120  VisibleModules.setVisible(Mod, ModuleLoc);
16121 
16122  // From now on, we have an owning module for all declarations we see.
16123  // However, those declarations are module-private unless explicitly
16124  // exported.
16125  auto *TU = Context.getTranslationUnitDecl();
16127  TU->setLocalOwningModule(Mod);
16128 
16129  // FIXME: Create a ModuleDecl.
16130  return nullptr;
16131 }
16132 
16134  SourceLocation ImportLoc,
16135  ModuleIdPath Path) {
16136  Module *Mod =
16137  getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16138  /*IsIncludeDirective=*/false);
16139  if (!Mod)
16140  return true;
16141 
16142  VisibleModules.setVisible(Mod, ImportLoc);
16143 
16144  checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16145 
16146  // FIXME: we should support importing a submodule within a different submodule
16147  // of the same top-level module. Until we do, make it an error rather than
16148  // silently ignoring the import.
16149  // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16150  // warn on a redundant import of the current module?
16151  if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16152  (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16153  Diag(ImportLoc, getLangOpts().isCompilingModule()
16154  ? diag::err_module_self_import
16155  : diag::err_module_import_in_implementation)
16156  << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16157 
16158  SmallVector<SourceLocation, 2> IdentifierLocs;
16159  Module *ModCheck = Mod;
16160  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16161  // If we've run out of module parents, just drop the remaining identifiers.
16162  // We need the length to be consistent.
16163  if (!ModCheck)
16164  break;
16165  ModCheck = ModCheck->Parent;
16166 
16167  IdentifierLocs.push_back(Path[I].second);
16168  }
16169 
16170  ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16171  Mod, IdentifierLocs);
16172  if (!ModuleScopes.empty())
16173  Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16174  CurContext->addDecl(Import);
16175 
16176  // Re-export the module if needed.
16177  if (Import->isExported() &&
16178  !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16179  getCurrentModule()->Exports.emplace_back(Mod, false);
16180 
16181  return Import;
16182 }
16183 
16185  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16186  BuildModuleInclude(DirectiveLoc, Mod);
16187 }
16188 
16190  // Determine whether we're in the #include buffer for a module. The #includes
16191  // in that buffer do not qualify as module imports; they're just an
16192  // implementation detail of us building the module.
16193  //
16194  // FIXME: Should we even get ActOnModuleInclude calls for those?
16195  bool IsInModuleIncludes =
16196  TUKind == TU_Module &&
16197  getSourceManager().isWrittenInMainFile(DirectiveLoc);
16198 
16199  bool ShouldAddImport = !IsInModuleIncludes;
16200 
16201  // If this module import was due to an inclusion directive, create an
16202  // implicit import declaration to capture it in the AST.
16203  if (ShouldAddImport) {
16204  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16205  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16206  DirectiveLoc, Mod,
16207  DirectiveLoc);
16208  if (!ModuleScopes.empty())
16209  Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16210  TU->addDecl(ImportD);
16211  Consumer.HandleImplicitImportDecl(ImportD);
16212  }
16213 
16214  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16215  VisibleModules.setVisible(Mod, DirectiveLoc);
16216 }
16217 
16219  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16220 
16221  ModuleScopes.push_back({});
16222  ModuleScopes.back().Module = Mod;
16223  if (getLangOpts().ModulesLocalVisibility)
16224  ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16225 
16226  VisibleModules.setVisible(Mod, DirectiveLoc);
16227 
16228  // The enclosing context is now part of this module.
16229  // FIXME: Consider creating a child DeclContext to hold the entities
16230  // lexically within the module.
16231  if (getLangOpts().trackLocalOwningModule()) {
16232  for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16233  cast<Decl>(DC)->setModuleOwnershipKind(
16234  getLangOpts().ModulesLocalVisibility
16237  cast<Decl>(DC)->setLocalOwningModule(Mod);
16238  }
16239  }
16240 }
16241 
16243  if (getLangOpts().ModulesLocalVisibility) {
16244  VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16245  // Leaving a module hides namespace names, so our visible namespace cache
16246  // is now out of date.
16247  VisibleNamespaceCache.clear();
16248  }
16249 
16250  assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16251  "left the wrong module scope");
16252  ModuleScopes.pop_back();
16253 
16254  // We got to the end of processing a local module. Create an
16255  // ImportDecl as we would for an imported module.
16256  FileID File = getSourceManager().getFileID(EomLoc);
16257  SourceLocation DirectiveLoc;
16258  if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16259  // We reached the end of a #included module header. Use the #include loc.
16260  assert(File != getSourceManager().getMainFileID() &&
16261  "end of submodule in main source file");
16262  DirectiveLoc = getSourceManager().getIncludeLoc(File);
16263  } else {
16264  // We reached an EOM pragma. Use the pragma location.
16265  DirectiveLoc = EomLoc;
16266  }
16267  BuildModuleInclude(DirectiveLoc, Mod);
16268 
16269  // Any further declarations are in whatever module we returned to.
16270  if (getLangOpts().trackLocalOwningModule()) {
16271  // The parser guarantees that this is the same context that we entered
16272  // the module within.
16273  for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16274  cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16275  if (!getCurrentModule())
16276  cast<Decl>(DC)->setModuleOwnershipKind(
16278  }
16279  }
16280 }
16281 
16283  Module *Mod) {
16284  // Bail if we're not allowed to implicitly import a module here.
16285  if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16286  VisibleModules.isVisible(Mod))
16287  return;
16288 
16289  // Create the implicit import declaration.
16290  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16291  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16292  Loc, Mod, Loc);
16293  TU->addDecl(ImportD);
16294  Consumer.HandleImplicitImportDecl(ImportD);
16295 
16296  // Make the module visible.
16297  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16298  VisibleModules.setVisible(Mod, Loc);
16299 }
16300 
16301 /// We have parsed the start of an export declaration, including the '{'
16302 /// (if present).
16304  SourceLocation LBraceLoc) {
16305  ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16306 
16307  // C++ Modules TS draft:
16308  // An export-declaration shall appear in the purview of a module other than
16309  // the global module.
16310  if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16311  Diag(ExportLoc, diag::err_export_not_in_module_interface);
16312 
16313  // An export-declaration [...] shall not contain more than one
16314  // export keyword.
16315  //
16316  // The intent here is that an export-declaration cannot appear within another
16317  // export-declaration.
16318  if (D->isExported())
16319  Diag(ExportLoc, diag::err_export_within_export);
16320 
16321  CurContext->addDecl(D);
16322  PushDeclContext(S, D);
16324  return D;
16325 }
16326 
16327 /// Complete the definition of an export declaration.
16329  auto *ED = cast<ExportDecl>(D);
16330  if (RBraceLoc.isValid())
16331  ED->setRBraceLoc(RBraceLoc);
16332 
16333  // FIXME: Diagnose export of internal-linkage declaration (including
16334  // anonymous namespace).
16335 
16336  PopDeclContext();
16337  return D;
16338 }
16339 
16341  IdentifierInfo* AliasName,
16342  SourceLocation PragmaLoc,
16343  SourceLocation NameLoc,
16344  SourceLocation AliasNameLoc) {
16345  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16346  LookupOrdinaryName);
16347  AsmLabelAttr *Attr =
16348  AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16349 
16350  // If a declaration that:
16351  // 1) declares a function or a variable
16352  // 2) has external linkage
16353  // already exists, add a label attribute to it.
16354  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16355  if (isDeclExternC(PrevDecl))
16356  PrevDecl->addAttr(Attr);
16357  else
16358  Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16359  << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16360  // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16361  } else
16362  (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16363 }
16364 
16366  SourceLocation PragmaLoc,
16367  SourceLocation NameLoc) {
16368  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16369 
16370  if (PrevDecl) {
16371  PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16372  } else {
16373  (void)WeakUndeclaredIdentifiers.insert(
16374  std::pair<IdentifierInfo*,WeakInfo>
16375  (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16376  }
16377 }
16378 
16380  IdentifierInfo* AliasName,
16381  SourceLocation PragmaLoc,
16382  SourceLocation NameLoc,
16383  SourceLocation AliasNameLoc) {
16384  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16385  LookupOrdinaryName);
16386  WeakInfo W = WeakInfo(Name, NameLoc);
16387 
16388  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16389  if (!PrevDecl->hasAttr<AliasAttr>())
16390  if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16391  DeclApplyPragmaWeak(TUScope, ND, W);
16392  } else {
16393  (void)WeakUndeclaredIdentifiers.insert(
16394  std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16395  }
16396 }
16397 
16399  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16400 }
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossibleZeroParamPrototype)
Definition: SemaDecl.cpp:11837
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2397
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:265
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2327
Defines the clang::ASTContext interface.
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2204
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it&#39;s either not been deduced or was deduce...
Definition: Type.h:4387
bool isCallToStdMove() const
Definition: Expr.h:2351
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1546
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name...
Definition: Builtins.h:176
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3128
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:3045
CanQualType LongLongTy
Definition: ASTContext.h:1004
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:552
An instance of this class is created to represent a function declaration or definition.
Definition: Decl.h:1697
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:6948
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:5611
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:549
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:49
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:748
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2237
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:101
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1281
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:270
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl *> Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:15590
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc", where we know the signature a priori.
Definition: Builtins.h:141
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:14558
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1700
no exception specification
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1800
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:3557
PtrTy get() const
Definition: Ownership.h:74
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:751
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2283
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
EvaluatedExprVisitor - This class visits &#39;Expr *&#39;s.
QualType getPointeeType() const
Definition: Type.h:2296
A (possibly-)qualified type.
Definition: Type.h:653
ASTConsumer & Consumer
Definition: Sema.h:317
Keeps information about an identifier in a nested-name-spec.
Definition: Sema.h:5292
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
Definition: SemaDecl.cpp:14633
bool isBlockPointerType() const
Definition: Type.h:5950
TagDecl * getDefinition() const
getDefinition - Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:3748
Simple class containing the result of Sema::CorrectTypo.
void addThisCapture(bool isNested, SourceLocation Loc, Expr *Cpy, bool ByCopy)
Definition: ScopeInfo.h:965
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2061
void InstantiatedLocal(const Decl *D, Decl *Inst)
base_class_range bases()
Definition: DeclCXX.h:773
bool isArrayType() const
Definition: Type.h:5991
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2483
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
bool isOverloadedOperator() const
isOverloadedOperator - Whether this function declaration represents an C++ overloaded operator...
Definition: Decl.h:2267
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:16379
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2278
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition: Scope.cpp:98
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword)...
const DeclarationNameLoc & getInfo() const
AttributeList * getNext() const
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:185
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1110
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2787
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:5699
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:351
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:968
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2148
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2994
A class which encapsulates the logic for delaying diagnostics during parsing and other processing...
Definition: Sema.h:653
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
bool willHaveBody() const
True if this function will eventually have a body, once it&#39;s fully parsed.
Definition: Decl.h:2154
DeclarationName getCXXConstructorName(CanQualType Ty)
getCXXConstructorName - Returns the name of a C++ constructor for the given Type. ...
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef &#39;New&#39; which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2110
This declaration has an owning module, but is only visible to lookups that occur within that module...
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:3164
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we&#39;re shadowing.
Definition: SemaDecl.cpp:6874
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:473
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:10910
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:260
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1433
AmbiguityKind getAmbiguityKind() const
Definition: Lookup.h:329
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl *> CH)
Definition: Decl.cpp:4306
Stmt - This represents one statement.
Definition: Stmt.h:66
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:938
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1278
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:685
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4111
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3056
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program...
Definition: Decl.cpp:2645
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:2396
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function...
Definition: Decl.cpp:3486
unsigned IsExternC
Whether this is an &#39;extern "C"&#39; module (which implicitly puts all headers in it within an &#39;extern "C"...
Definition: Module.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:790
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2671
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:609
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1009
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:95
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:3716
TypedefDecl - Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier...
Definition: Decl.h:2898
Defines the SourceManager interface.
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines &#39;SEL&#39;.
Definition: ASTContext.h:1607
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:11488
Microsoft&#39;s &#39;__super&#39; specifier, stored as a CXXRecordDecl* of the class it appeared in...
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2042
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1724
static ClassScopeFunctionSpecializationDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD, bool HasExplicitTemplateArgs, TemplateArgumentListInfo TemplateArgs)
bool hasVolatileMember() const
Definition: Decl.h:3564
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6, C++11 [class.copy]p12)
Definition: DeclCXX.h:1354
bool isRecordType() const
Definition: Type.h:6015
Expr * getBase() const
Definition: Expr.h:2477
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
getCXXConversionFunctionName - Returns the name of a C++ conversion function for the given Type...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:12134
bool isSingleTagDecl() const
Asks if the result is a single tag decl.
Definition: Lookup.h:533
bool isInitICE() const
Determines whether the initializer is an integral constant expression, or in C++11, whether the initializer is a constant expression.
Definition: Decl.cpp:2275
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:657
static const TST TST_typeofExpr
Definition: DeclSpec.h:296
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1880
const Type * getTypeForDecl() const
Definition: Decl.h:2784
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void setRangeEnd(SourceLocation E)
Definition: Decl.h:1914
bool isVariadic() const
Definition: Type.h:3615
void forgetBuiltin(unsigned ID, IdentifierTable &Table)
Completely forget that the given ID was ever considered a builtin, e.g., because the user provided a ...
Definition: Builtins.cpp:106
const RecordType * getAsStructureType() const
Definition: Type.cpp:472
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:23
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2083
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs=true)
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function...
Definition: SemaDecl.cpp:5635
static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:1934
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:133
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
bool isPOD() const
Whether this class is a POD-type (C++ [class]p4)
Definition: DeclCXX.h:1264
Defines the C++ template declaration subclasses.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
StringRef P
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4401
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:2846
void setPure(bool P=true)
Definition: Decl.cpp:2632
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:2831
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
bool hasWrittenPrototype() const
Definition: Decl.h:2034
Not a friend object.
Definition: DeclBase.h:1093
void AddDecl(Decl *D)
Definition: Scope.h:281
A constructor named via a template-id.
const DiagnosticBuilder & operator<<(const DiagnosticBuilder &DB, const Attr *At)
Definition: Attr.h:195
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
Definition: Decl.h:2648
The base class of the type hierarchy.
Definition: Type.h:1351
CanQualType LongTy
Definition: ASTContext.h:1004
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:2862
bool isClkEventT() const
Definition: Type.h:6104
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:4553
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1124
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2558
Declaration of a variable template.
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:505
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Sema.h:3039
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2206
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1239
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:495
virtual void completeDefinition()
completeDefinition - Notes that the definition of this type is now complete.
Definition: Decl.cpp:3969
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
decl_iterator begin()
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:95
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1313
const NestedNameSpecifier * Specifier
A container of type source information.
Definition: Decl.h:86
Wrapper for void* pointer.
Definition: Ownership.h:45
capture_const_range captures() const
Definition: DeclCXX.h:1200
Look up of a name that precedes the &#39;::&#39; scope resolution operator in C++.
Definition: Sema.h:3010
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:519
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:3828
An overloaded operator name, e.g., operator+.
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function is defined at all, including a deleted definition.
Definition: Decl.cpp:2605
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T)
Definition: SemaDecl.cpp:4138
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:446
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2115
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclBase.h:412
void PopDeclContext()
Definition: SemaDecl.cpp:1219
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1257
bool hasNext() const
Definition: Lookup.h:642
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
unsigned getCharWidth() const
Definition: TargetInfo.h:333
param_const_iterator param_end() const
Definition: DeclObjC.h:390
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2397
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:256
size_t param_size() const
Definition: Decl.h:2183
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:7452
QualType getElementType() const
Definition: Type.h:2593
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:2854
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:3097
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:491
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2028
***static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Definition: SemaDecl.cpp:13013
ArrayRef< RawComment * > getComments() const
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:82
This file provides some common utility functions for processing Lambda related AST Constructs...
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class, then each of the following shall have a name different from T:
Definition: SemaDecl.cpp:5164
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:566
void ActOnObjCReenterContainerContext(DeclContext *DC)
Definition: SemaDecl.cpp:14134
DeclContext::lookup_result Decls
The set of declarations found inside this base class subobject.
enumerator_range enumerators() const
Definition: Decl.h:3336
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10640
Compiling a C++ modules TS module interface unit.
Definition: LangOptions.h:65
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:806
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
bool isStructureType() const
Definition: Type.cpp:403
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:1952
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isExplicit, bool isConstexpr, SourceLocation EndLocation)
Definition: DeclCXX.cpp:2229
static const TST TST_underlyingType
Definition: DeclSpec.h:299
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:255
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1752
QualType getReturnType() const
Definition: Decl.h:2207
DiagnosticsEngine & Diags
Definition: Sema.h:318
unsigned getNumParams() const
Definition: Type.h:3489
bool isEnumeralType() const
Definition: Type.h:6019
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
QualType getCXXNameType() const
getCXXNameType - If this name is one of the C++ names (of a constructor, destructor, or conversion function), return the type associated with that name.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3426
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6305
The "union" keyword.
Definition: Type.h:4694
Extra information about a function prototype.
Definition: Type.h:3387
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1580
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6377
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:45
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
The "__interface" keyword.
Definition: Type.h:4691
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1092
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1240
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:3157
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:422
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:14128
static const TST TST_interface
Definition: DeclSpec.h:292
bool isAmbiguous() const
Definition: Lookup.h:304
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
reference front() const
Definition: DeclBase.h:1230
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1311
bool isInvalidDecl() const
Definition: DeclBase.h:546
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so, check that it&#39;s a valid override and remember it.
Definition: SemaDecl.cpp:7533
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:1822
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:68
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:4768
bool isCallingConv() const
Definition: Type.cpp:3117
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:8173
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:11535
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:815
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:274
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don&#39;t care about...
Definition: SemaDecl.cpp:12169
bool isStatic() const
Definition: DeclCXX.cpp:1633
bool hasDefinition() const
Definition: DeclCXX.h:738
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5021
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3000
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2512
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1513
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1194
Defines the clang::Expr interface and subclasses for C++ expressions.
AttributeList * getList() const
FormatAttr * mergeFormatAttr(Decl *D, SourceRange Range, IdentifierInfo *Format, int FormatIdx, int FirstArg, unsigned AttrSpellingListIndex)
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1353
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2014
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4094
static const TemplateDecl * isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs)
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:5597
bool isVariableArrayType() const
Definition: Type.h:6003
Information about a template-id annotation token.
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Determines whether this field is a representative for an anonymous struct ...
Definition: Decl.cpp:3646
UuidAttr * mergeUuidAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex, StringRef Uuid)
PipeType - OpenCL20.
Definition: Type.h:5648
ModuleKind Kind
The kind of this module.
Definition: Module.h:87
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:14261
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. ...
Definition: Decl.cpp:3057
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:37
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:10611
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2865
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:11821
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:1880
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
bool isRedeclaration() const
Definition: DeclSpec.h:2454
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3488
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
Definition: SemaDecl.cpp:11690
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:962
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists...
Definition: Decl.h:3380
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1111
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:361
One of these records is kept for each identifier that is lexed.
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3373
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:859
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:7489
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:59
SourceLocation getOuterLocStart() const
getOuterLocStart - Return SourceLocation representing start of source range taking into account any o...
Definition: Decl.cpp:1768
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it&#39;s a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1623
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99&#39;s...
Definition: SemaDecl.cpp:6085
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:4894
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:5617
static bool isDeclExternC(const Decl *D)
Returns true if given declaration has external C language linkage.
Definition: SemaDecl.cpp:6201
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:232
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable &#39;New&#39; which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:3609
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:11374
bool isConst() const
Definition: DeclCXX.h:2006
unsigned getRegParm() const
Definition: Type.h:3131
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:946
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:3922
void setManglingNumber(const NamedDecl *ND, unsigned Number)
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:2764
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
A C++ nested-name-specifier augmented with source location information.
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2127
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3496
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1182
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:508
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:381
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3844
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1187
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag&#39;s definition (e...
Definition: SemaDecl.cpp:14023
Missing a type from <ucontext.h>
Definition: ASTContext.h:1954
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:12807
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition: Scope.h:264
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3609
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3200
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
field_range fields() const
Definition: Decl.h:3619
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:1903
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
static const TST TST_class
Definition: DeclSpec.h:293
bool isObjCIdType() const
Definition: Type.h:6068
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:12914
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl *> Bindings)
Definition: DeclCXX.cpp:2599
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition: DeclSpec.h:957
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2467
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
const llvm::APSInt & getInitVal() const
Definition: Decl.h:2692
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:54
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:921
void removeConst()
Definition: Type.h:273
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1566
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:1778
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:245
bool isFunctionDefinition() const
Definition: DeclSpec.h:2431
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3725
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:942
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:519
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2046
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
bool isReferenceType() const
Definition: Type.h:5954
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2064
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
static const TST TST_error
Definition: DeclSpec.h:307
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:795
DeclarationName getCXXDestructorName(CanQualType Ty)
getCXXDestructorName - Returns the name of a C++ destructor for the given Type.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:15431
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:7972
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
unsigned getTypeQualifiers() const
Definition: DeclCXX.h:2104
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1020
This declaration is definitely a definition.
Definition: Decl.h:1144
static const TST TST_enum
Definition: DeclSpec.h:289
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1455
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
Definition: SemaDecl.cpp:9464
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, bool IsExplicit, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1616
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:12749
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1877
LookupResultKind getResultKind() const
Definition: Lookup.h:324
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, AttributeList *Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:15457
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec&#39;s type is equal...
Definition: SemaDecl.cpp:635
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:12494
Expr * getSubExpr()
Definition: Expr.h:2761
void ClearStorageClassSpecs()
Definition: DeclSpec.h:459
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
Declaration of a function specialization at template class scope.
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:172
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration&#39;s previous declaration was declared in the same block ...
Definition: Decl.h:1385
Compiling a module from a module map.
Definition: LangOptions.h:64
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6219
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword...
Definition: Diagnostic.h:1202
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:41
A user-defined literal name, e.g., operator "" _i.
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:6178
Describes a module or submodule.
Definition: Module.h:65
IdentifierTable & Idents
Definition: ASTContext.h:537
RawCommentList & getRawCommentList()
Definition: ASTContext.h:780
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:107
bool isInvalidType() const
Definition: DeclSpec.h:2412
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2167
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:266
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:507
bool getProducesResult() const
Definition: Type.h:3127
DeclClass * getAsSingle() const
Definition: Lookup.h:510
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, SmallVectorImpl< NamedDecl *> &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
Definition: SemaDecl.cpp:4456
bool isModuleVisible(const Module *M)
Definition: Sema.h:1558
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC&#39;s GC attribute of &#39;LHS&#39; and &#39;RHS&#39; attributes and ret...
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2066
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:443
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:954
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2703
Describes an C or C++ initializer list.
Definition: Expr.h:3872
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition: Scope.h:377
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:910
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2545
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1671
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:471
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:522
Represents the results of name lookup.
Definition: Lookup.h:32
PtrTy get() const
Definition: Ownership.h:162
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:2621
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We&#39;ve just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4022
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:169
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl *> Bindings=None)
Definition: SemaDecl.cpp:6210
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1308
MinSizeAttr * mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:986
static void filterNonConflictingPreviousTypedefDecls(Sema &S, TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don&#39;t have linkage, but they still denote the same entity if their types are the...
Definition: SemaDecl.cpp:2032
Decl * ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see &#39;struct foo&#39; or &#39;struct {&#39;.
Definition: SemaDecl.cpp:13077
TagKind getTagKind() const
Definition: Decl.h:3156
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:424
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
A convenient class for passing around template argument information.
Definition: TemplateBase.h:546
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1233
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:1908
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:14037
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11&#39;s _Align...
Definition: SemaDecl.cpp:2314
bool hasAddressSpace() const
Definition: Type.h:366
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes, if any.
Definition: Decl.cpp:4335
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Wrapper for source info for functions.
Definition: TypeLoc.h:1396
static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, Sema &S)
Definition: SemaDecl.cpp:11934
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:10569
SCS
storage-class-specifier
Definition: DeclSpec.h:232
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:4278
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3226
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2030
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl *> Elements, Scope *S, AttributeList *Attr)
Definition: SemaDecl.cpp:15727
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl *> Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:11450
Decl * getObjCDeclContext() const
Definition: SemaDecl.cpp:16398
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:32
Decl * ActOnObjCContainerStartDefinition(Decl *IDecl)
Definition: SemaDecl.cpp:14047
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:226
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1095
child_range children()
Definition: Stmt.cpp:226
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2144
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:147
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isConstWithoutErrno(unsigned ID) const
Return true if this function has no side effects and doesn&#39;t read memory, except for possibly errno...
Definition: Builtins.h:194
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:635
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:5192
static bool isRecordType(QualType T)
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2377
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1808
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2760
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2453
void setHasObjectMember(bool val)
Definition: Decl.h:3562
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5788
bool isShadowed() const
Determine whether the lookup result was shadowed by some other declaration that lookup ignored...
Definition: Lookup.h:462
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Definition: Decl.h:3390
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type *> &ValidTypes)
Definition: SemaDecl.cpp:8005
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:5946
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1431
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD...
Definition: SemaDecl.cpp:6888
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setHasImplicitReturnZero(bool IRZ)
Definition: Decl.h:2024
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Module * Parent
The parent of this module.
Definition: Module.h:91
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualfied nam...
Definition: SemaDecl.cpp:13050
enum clang::DeclaratorChunk::@198 Kind
unsigned getShortWidth() const
Return the size of &#39;signed short&#39; and &#39;unsigned short&#39; for this target, in bits.
Definition: TargetInfo.h:338
child_range children()
Definition: Expr.h:4055
unsigned getMSLastManglingNumber() const
Definition: Scope.h:303
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1366
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3341
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
DeclContextLookupResult slice(size_t N) const
Definition: DeclBase.h:1235
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:71
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a #include or similar preprocessing directiv...
Definition: SemaDecl.cpp:16184
Expr * getSizeExpr() const
Definition: Type.h:2737
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence...
Definition: SemaInit.cpp:6530
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:15963
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5718
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:705
field_iterator field_begin() const
Definition: Decl.cpp:3960
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3656
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1153
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:2157
void setTrivial(bool IT)
Definition: Decl.h:2008
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl *> &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions...
Definition: SemaDecl.cpp:14747
#define NULL
Definition: opencl-c.h:150
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:10123
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:100
void DiagnoseUnusedDecl(const NamedDecl *ND)
DiagnoseUnusedDecl - Emit warnings about declarations that are not used unless they are marked attr(u...
Definition: SemaDecl.cpp:1766
const Expr * getInitExpr() const
Definition: Decl.h:2690
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:3183
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:6322
int hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:7
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:15698
bool isNoreturnSpecified() const
Definition: DeclSpec.h:572
void setRedeclarationKind(Sema::RedeclarationKind RK)
Change this lookup&#39;s redeclaration kind.
Definition: Lookup.h:575
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:820
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2421
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
Definition: SemaDecl.cpp:8162
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2071
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:671
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:7223
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1404
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1869
const LangOptions & getLangOpts() const
Definition: Sema.h:1193
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:748
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:540
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:738
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1856
bool isScalarType() const
Definition: Type.h:6204
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1696
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:9618
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:12191
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:651
void revertBuiltin()
Revert the identifier to a non-builtin identifier.
Represents a linkage specification.
Definition: DeclCXX.h:2743
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:501
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:429
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3002
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1716
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:500
bool getNoReturn() const
Definition: Type.h:3126
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:394
bool isExported() const
Whether this declaration is exported (by virtue of being lexically within an ExportDecl or by being a...
Definition: DeclBase.cpp:436
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2106
static bool isUsingDecl(NamedDecl *D)
Definition: SemaDecl.cpp:1491
Ordinary names.
Definition: DeclBase.h:144
CanQualType UnsignedCharTy
Definition: ASTContext.h:1005
unsigned getLength() const
Efficiently return the length of this identifier info.
bool getNoCallerSavedRegs() const
Definition: Type.h:3128
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, bool isConstexprSpecified=false)
Definition: Decl.h:1881
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced...
Definition: DeclSpec.h:950
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:869
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Whether this is an anonymous struct or union.
Definition: Decl.h:3556
This object can be modified without requiring retains or releases.
Definition: Type.h:173
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition: Sema.h:1830
param_iterator param_begin()
Definition: Decl.h:2179
void setHasInheritedPrototype(bool P=true)
Definition: Decl.h:2039
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1536
Class that aids in the construction of nested-name-specifiers along with source-location information ...
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3177
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:467
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:449
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3327
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:7431
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1129
bool isHalfType() const
Definition: Type.h:6175
NodeId Parent
Definition: ASTDiff.cpp:192
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:216
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:1965
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void completeDefinition(QualType NewType, QualType PromotionType, unsigned NumPositiveBits, unsigned NumNegativeBits)
completeDefinition - When created, the EnumDecl corresponds to a forward-declared enum...
Definition: Decl.cpp:3834
bool decl_empty() const
Definition: Scope.h:279
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition: Decl.cpp:4463
bool hasAttr() const
Definition: DeclBase.h:535
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3269
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1848
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:274
void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name)
Make the given externally-produced declaration visible at the top level scope.
Definition: SemaDecl.cpp:1405
StringRef getString() const
Definition: Expr.h:1557
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:2399
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2381
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:759
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Definition: ScopeInfo.h:170
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:544
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3268
bool isFileVarDecl() const
isFileVarDecl - Returns true for file scoped variable declaration.
Definition: Decl.h:1186
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2787
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2165
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if &#39;E&#39;, which is an expression that is about to be modified, refers to a shadowing declaration...
Definition: SemaDecl.cpp:7084
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one. ...
Definition: SemaDecl.cpp:2721
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1302
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:602
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:5839
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:680
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:606
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1718
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:540
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1270
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld)
MergeFunctionDecl - We just parsed a function &#39;New&#39; from declarator D which has the same name and sco...
Definition: SemaDecl.cpp:2943
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:86
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:9100
bool isEnabled(llvm::StringRef Ext) const
Definition: OpenCLOptions.h:39
A conversion function name, e.g., operator int.
SourceRange getRange() const
Definition: DeclSpec.h:68
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
Captures information about a #pragma weak directive.
Definition: Weak.h:25
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:2847
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
TST getTypeSpecType() const
Definition: DeclSpec.h:477
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:7636
static bool isDeclRep(TST T)
Definition: DeclSpec.h:412
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isImplicitlyDeclared)
Definition: DeclCXX.cpp:2196
bool isCLike() const
True if this class is C-like, without C++-specific features, e.g.
Definition: DeclCXX.cpp:1106
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma...
Definition: Decl.cpp:3977
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:432
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:875
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1351
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:745
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:39
bool isEventT() const
Definition: Type.h:6100
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2241
bool isObjCGCStrong() const
true when Type is objc&#39;s strong.
Definition: Type.h:1065
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3127
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:627
Expr - This represents one expression.
Definition: Expr.h:106
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:2990
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e...
Definition: SemaDecl.cpp:4049
SourceLocation End
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:768
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1780
Represents a character-granular source range.
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4723
bool isFunctionNoProtoType() const
Definition: Type.h:1742
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2574
DLLImportAttr * mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:2012
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, unsigned TypeQuals, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation ConstQualifierLoc, SourceLocation VolatileQualifierLoc, SourceLocation RestrictQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl *> DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult())
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:152
bool isExplicitSpecified() const
Definition: DeclSpec.h:569
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
std::string Label
ModuleDeclKind
Definition: Sema.h:2052
void ResetObjCLayout(const ObjCContainerDecl *CD)
bool isDeclScope(Decl *D)
isDeclScope - Return true if this is the scope that the specified decl is declared in...
Definition: Scope.h:315
int Id
Definition: ASTDiff.cpp:191
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool hasLocalStorage() const
hasLocalStorage - Returns true if a variable with function scope is a non-static local variable...
Definition: Decl.h:1025
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:578
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4134
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2102
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
const FunctionProtoType * T
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:346
StateNode * Previous
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1348
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:7192
DeclContext * getEntity() const
Definition: Scope.h:319
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1267
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:321
unsigned SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new", "[", and "]" tokens in operator new [].
Definition: DeclSpec.h:930
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:70
bool getHasRegParm() const
Definition: Type.h:3129
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6368
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:7052
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:15528
OpaquePtr< T > get() const
Definition: Ownership.h:98
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:86
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2620
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
QualType getParenType(QualType NamedType) const
void setInit(Expr *I)
Definition: Decl.cpp:2156
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:1973
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
Definition: SemaDecl.cpp:16009
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:542
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:561
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:455
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:551
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:548
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure...
Definition: SemaDecl.cpp:4841
const Expr * getCallee() const
Definition: Expr.h:2249
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
Defines the clang::Preprocessor interface.
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:967
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache"...
Definition: Builtins.h:155
static void CheckPoppedLabel(LabelDecl *L, Sema &S)
Definition: SemaDecl.cpp:1791
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
field_iterator field_end() const
Definition: Decl.h:3622
Not compiling a module interface at all.
Definition: LangOptions.h:63
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:1926
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1052
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:121
bool isFileContext() const
Definition: DeclBase.h:1401
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:255
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:6250
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
DeclContext * getDeclContext()
Definition: DeclBase.h:425
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:731
bool isConstexprSpecified() const
Definition: DeclSpec.h:703
A parsed C++17 decomposition declarator of the form &#39;[&#39; identifier-list &#39;]&#39;.
Definition: DeclSpec.h:1653
This declaration is a tentative definition.
Definition: Decl.h:1141
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1594
TLSKind getTLSKind() const
Definition: Decl.cpp:1887
AttributeFactory & getFactory() const
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:15234
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2452
CanQualType ShortTy
Definition: ASTContext.h:1004
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:883
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:449
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2237
Decl * ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc)
Complete the definition of an export declaration.
Definition: SemaDecl.cpp:16328
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:108
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1956
Represents a C++ template name within the type system.
Definition: TemplateName.h:178
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name...
Definition: SemaDecl.cpp:5739
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:454
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:382
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:14251
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:992
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:1561
unsigned short getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:946
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2331
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:667
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:1956
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn&#39;t a simple identifier.
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:618
void setConstexpr(bool IC)
Definition: Decl.h:1369
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:14382
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling)
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition: Scope.h:332
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body (definition).
Definition: Decl.cpp:2580
QualType getType() const
Definition: Expr.h:128
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:2535
bool isFunctionOrMethod() const
Definition: DeclBase.h:1384
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:7778
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:5039
StorageClass
Storage classes.
Definition: Specifiers.h:203
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1594
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1410
decl_range decls() const
Definition: Scope.h:276
void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don&#39;t have one.
Direct list-initialization (C++11)
Definition: Decl.h:817
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:311
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:226
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
This declaration has an owning module, and is visible when that module is imported.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1335
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1417
static const TST TST_int
Definition: DeclSpec.h:278
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:903
QualType getRecordType(const RecordDecl *Decl) const
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:7623
bool isInvalid() const
Definition: Ownership.h:158
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:2863
SourceLocation getEnd() const
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1717
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1333
struct CXXOpName CXXOperatorName
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1041
DeclContext * getContainingDC(DeclContext *DC)
Definition: SemaDecl.cpp:1176
bool isFriendSpecified() const
Definition: DeclSpec.h:697
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4361
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6263
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2209
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1345
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex)
ValueDecl * getDecl()
Definition: Expr.h:1041
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:439
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1382
bool isUsable() const
Definition: Ownership.h:159
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:1882
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2682
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:1362
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1347
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:149
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2007
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isUnionType() const
Definition: Type.cpp:432
SourceLocation getLocEnd() const LLVM_READONLY
Definition: TypeLoc.h:155
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2073
QualType withoutLocalFastQualifiers() const
Definition: Type.h:874
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:6130
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading &#39;auto&#39; corresponding to a trailing return type...
Definition: Type.cpp:1691
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:167
static StringRef getIdentifier(const Token &Tok)
static void ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, OverrideErrorKind OEK=OEK_All)
Report an error regarding overriding, along with any relevant overriden methods.
Definition: SemaDecl.cpp:7517
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an &#39;@&#39;.
Definition: TokenKinds.h:41
decl_range found_decls()
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList *> TPLists)
Definition: Decl.cpp:3791
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:297
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:233
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLock is not of the desire...
Definition: TypeLoc.h:2344
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:1977
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:49
CanQualType SignedCharTy
Definition: ASTContext.h:1004
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:1102
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:220
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:122
AttrVec & getAttrs()
Definition: DeclBase.h:477
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:848
bool hasAttrs() const
Definition: DeclBase.h:471
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3150
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5777
bool isVoidPointerType() const
Definition: Type.cpp:426
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
Definition: SemaDecl.cpp:7109
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We&#39;ve determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1453
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition: SemaDecl.cpp:171
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:573
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:11893
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
void addAttr(Attr *A)
Definition: DeclBase.h:484
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:12181
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:408
UnqualifiedTypeNameLookupResult
Definition: SemaDecl.cpp:159
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:12508
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:6116
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:3941
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:397
void setTypeForDecl(const Type *TD)
Definition: Decl.h:2785
bool isStructureOrClassType() const
Definition: Type.cpp:418
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:217
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
Definition: SemaDecl.cpp:16189
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:203
Wrapper for source info for arrays.
Definition: TypeLoc.h:1529
Represents a C++ Modules TS module export declaration.
Definition: Decl.h:4036
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4061
There is no lifetime qualification on this type.
Definition: Type.h:169
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1328
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:868
UnqualifiedIdKind Kind
Describes the kind of unqualified-id parsed.
Definition: DeclSpec.h:917
This declaration has an owning module, but is globally visible (typically because its owning module i...
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1708
const AttributeList * getAttributes() const
Definition: DeclSpec.h:2374
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:11784
The "struct" keyword.
Definition: Type.h:4688
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:2997
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:180
Kind
static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, AttributeList::Kind Kind)
Definition: SemaDecl.cpp:6151
QualType getCanonicalType() const
Definition: Type.h:5757
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:144
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1196
param_type_range param_types() const
Definition: Type.h:3637
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:208
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1544
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3500
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:220
SCS getStorageClassSpec() const
Definition: DeclSpec.h:445
Expr * getAsmLabel() const
Definition: DeclSpec.h:2400
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:299
unsigned getMSCurManglingNumber() const
Definition: Scope.h:309
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition: DeclSpec.h:2096
unsigned getNumExprs() const
Definition: Expr.h:4618
static bool AllowOverloadingOfFunction(LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether we allow overloading of the function PrevDecl with another declaration.
Definition: SemaDecl.cpp:1330
OverrideErrorKind
Definition: SemaDecl.cpp:7508
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Encodes a location in the source.
bool isTypeSpecOwned() const
Definition: DeclSpec.h:481
Sugar for parentheses used when specifying types.
Definition: Type.h:2253
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:590
QualType getReturnType() const
Definition: Type.h:3201
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:1996
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:9638
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:14094
bool duplicatesAllowed() const
By default, attributes cannot be duplicated when being merged; however, an attribute can override thi...
Definition: Attr.h:116
void ActOnDocumentableDecls(ArrayRef< Decl *> Group)
Definition: SemaDecl.cpp:11492
SourceLocation CurrentPragmaLocation
Definition: Sema.h:436
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition: Decl.cpp:4509
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4002
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:783
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:5834
Expr * getSubExpr() const
Definition: Expr.h:1744
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2435
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1874
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:742
void setBraceRange(SourceRange R)
Definition: Decl.h:3073
Attr * clone(ASTContext &C) const
DLLExportAttr * mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1860
CastKind getCastKind() const
Definition: Expr.h:2757
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:11155
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2210
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function...
Definition: SemaDecl.cpp:12623
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:16365
void setFreeStanding(bool isFreeStanding=true)
Definition: Decl.h:3120
DeclarationName getName() const
getName - Returns the embedded declaration name.
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1276
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:207
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2944
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have...
Definition: Linkage.h:66
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:378
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of &#39;signed long long&#39; and &#39;unsigned long long&#39; for this targ...
Definition: TargetInfo.h:356
FunctionTypeInfo Fun
Definition: DeclSpec.h:1494
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:700
static const TST TST_union
Definition: DeclSpec.h:290
CallingConv getCC() const
Definition: Type.h:3138
bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context, will replace the declaration OldD if introduced into scope.
Definition: Decl.cpp:1595
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:94
CommonAttr * mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex)
unsigned getSpellingListIndex() const
Definition: Attr.h:88
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList *> TPLists)
Definition: Decl.cpp:1752
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C &#39;SEL&#39; type.
Definition: ASTContext.h:1810
LabelDecl - Represents the declaration of a label.
Definition: Decl.h:459
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error...
Definition: DeclSpec.cpp:551
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:1862
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1722
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
void setDefaulted(bool D=true)
Definition: Decl.h:2013
void setHasFlexibleArrayMember(bool V)
Definition: Decl.h:3542
SourceLocation getStrTokenLoc(unsigned TokNum) const
Definition: Expr.h:1619
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used...
Definition: SemaDecl.cpp:12145
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:3966
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn&#39;t read memory.
Definition: Builtins.h:107
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1067
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:1901
static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, QualType T, SourceLocation NameLoc)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:833
void setEntity(DeclContext *E)
Definition: Scope.h:320
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T)
Retrieve a version of the type &#39;T&#39; that is elaborated by Keyword and qualified by the nested-name-spe...
Definition: SemaType.cpp:7806
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2190
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1291
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:227
SourceLocation getLocation() const
Definition: Attr.h:91
A friend of a previously-declared entity.
Definition: DeclBase.h:1094
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:54
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1496
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2299
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible. ...
Definition: SemaDecl.cpp:3530
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1816
CanQualType VoidTy
Definition: ASTContext.h:996
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3415
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Describes the kind of initialization being performed, along with location information for tokens rela...
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
arg_range arguments()
Definition: Expr.h:2303
bool isAnyPointerType() const
Definition: Type.h:5946
bool isObjCObjectPointerType() const
Definition: Type.h:6039
Decl * getRepAsDecl() const
Definition: DeclSpec.h:489
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:620
This declaration is only a declaration.
Definition: Decl.h:1138
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:601
bool isMSAsmLabel() const
Definition: Decl.h:493
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const
Determine whether the token kind starts a simple-type-specifier.
Definition: SemaDecl.cpp:119
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2822
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:86
bool isFunctionProtoType() const
Definition: Type.h:1743
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1096
static const TST TST_typeofType
Definition: DeclSpec.h:295
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:416
Decl * ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc)
We have parsed the start of an export declaration, including the &#39;{&#39; (if present).
Definition: SemaDecl.cpp:16303
No entity found met the criteria.
Definition: Lookup.h:36
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:148
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:399
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1909
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:174
Expr ** getExprs()
Definition: Expr.h:4630
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted per C++0x.
Definition: Decl.h:2017
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:1907
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:389
static ImportDecl * CreateImplicit(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc)
Create a new module import declaration for an implicitly-generated import.
Definition: Decl.cpp:4471
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:562
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:3586
Assigning into this object requires a lifetime extension.
Definition: Type.h:186
static bool isExternC(T *D)
Definition: SemaDecl.cpp:2875
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:11833
void dropAttrs()
Definition: DeclBase.cpp:832
NamedDecl * next()
Definition: Lookup.h:646
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:138
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2023
void setObjCSuperType(QualType ST)
Definition: ASTContext.h:1558
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:450
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:488
bool hasFlexibleArrayMember() const
Definition: Decl.h:3541
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:565
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T...
Definition: SemaDecl.cpp:15217
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:261
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2427
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2214
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:80
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, IdentifierInfo *II)
Looks up the declaration of "struct objc_super" and saves it for later use in building builtin declar...
Definition: SemaDecl.cpp:1920
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:12867
bool isDesignatedInitializerForTheInterface(const ObjCMethodDecl **InitMethod=nullptr) const
Returns true if the method selector resolves to a designated initializer in the class&#39;s interface...
Definition: DeclObjC.cpp:794
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:615
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:3971
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
void setVirtualAsWritten(bool V)
Definition: Decl.h:1992
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1562
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1241
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2804
Expr * getLHS() const
Definition: Expr.h:3029
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:701
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1570
StringRef getName() const
Return the actual identifier string.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration. ...
Definition: SemaDecl.cpp:5794
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1876
void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2367
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn&#39;t shadow any declaration ...
Definition: SemaDecl.cpp:6926
CanQualType UnsignedShortTy
Definition: ASTContext.h:1005
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array&#39;s size can require, which limits the maximu...
Definition: Type.cpp:135
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery...
Definition: SemaDecl.cpp:16282
bool isObjCGCWeak() const
true when Type is objc&#39;s weak.
Definition: Type.h:1060
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2802
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
CanQualType CharTy
Definition: ASTContext.h:998
TLS with a dynamic initializer.
Definition: Decl.h:829
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1289
LabelStmt * getStmt() const
Definition: Decl.h:483
bool isDeduced() const
Definition: Type.h:4390
void setBody(Stmt *B)
Definition: Decl.cpp:2626
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons...
Definition: Type.h:2331
bool isPipeType() const
Definition: Type.h:6123
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:12885
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:69
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:3401
TagTypeKind
The kind of a tag type.
Definition: Type.h:4686
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2455
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2250
Dataflow Directional Tag Classes.
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:5565
bool isValid() const
Return true if this is a valid SourceLocation object.
void setImplicitlyInline()
Flag that this function is implicitly inline.
Definition: Decl.h:2250
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1686
ExtInfo getExtInfo() const
Definition: Type.h:3212
void setHasVolatileMember(bool val)
Definition: Decl.h:3565
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:11662
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:5685
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2000
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:539
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1256
const AttributeList * getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1515
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator&#39;s nested name ...
Definition: SemaDecl.cpp:1247
static const TST TST_decltype
Definition: DeclSpec.h:297
static const TST TST_auto
Definition: DeclSpec.h:300
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:224
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion)
We are trying to inject an anonymous member into the given scope; check if there&#39;s an existing declar...
Definition: SemaDecl.cpp:4415
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:130
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1010
bool isRecord() const
Definition: DeclBase.h:1409
attr_range attrs() const
Definition: DeclBase.h:494
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
OpenCLParamType
Definition: SemaDecl.cpp:7963
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool EnumUnderlyingIsImplicit, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:12824
IndirectFieldDecl - An instance of this class is created to represent a field injected from an anonym...
Definition: Decl.h:2711
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2096
bool isDependentAddressSpaceType() const
Definition: Type.h:6035
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
Definition: SemaDecl.cpp:16218
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1560
QualType getUnderlyingType() const
Definition: Decl.h:2853
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:15182
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition: Scope.h:270
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1006
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1275
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include&#39;d file otherwise it returns an invalid location...
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:116
const Expr * getInit() const
Definition: Decl.h:1212
AccessSpecifier getAccess() const
Definition: DeclBase.h:460
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1568
SectionAttr * mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex)
A decomposition declaration.
Definition: DeclCXX.h:3766
MapType::iterator iterator
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:76
void setShadowed()
Note that we found and ignored a declaration while performing lookup.
Definition: Lookup.h:466
void setWillHaveBody(bool V=true)
Definition: Decl.h:2155
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclarationName - The name of a declaration.
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:520
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
Definition: SemaDecl.cpp:14621
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:337
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
bool isBooleanType() const
Definition: Type.h:6232
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:5692
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4067
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:97
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1212
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:7814
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:2653
A mapping from each virtual member function to its set of final overriders.
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:731
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:752
EnumDecl - Represents an enum.
Definition: Decl.h:3239
VisibilityAttr * mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex)
redecl_iterator redecls_end() const
Definition: Redeclarable.h:306
void setInlineSpecified()
Definition: Decl.h:1355
void mergeNRVOIntoParent()
Definition: Scope.cpp:122
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:73
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2502
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:1859
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:783
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D)
Definition: SemaDecl.cpp:1643
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type. ...
Definition: Type.cpp:1962
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition&#39;s base-specifie...
Definition: SemaDecl.cpp:14057
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1375
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:3271
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1390
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:3273
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:3808
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:11717
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
static const TST TST_unspecified
Definition: DeclSpec.h:272
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:4409
IdentifierInfo * getCorrectionAsIdentifierInfo() const
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1600
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:10156
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 &#39;auto&#39; typ...
Definition: Type.h:6238
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:54
This declaration is not owned by a module.
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1382
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:2829
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it&#39;s the object of a friend declaration...
Definition: DeclBase.h:1063
All of the names in this module are visible.
Definition: Module.h:264
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2552
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1156
llvm::APInt getValue() const
Definition: Expr.h:1279
QualType getModifiedType() const
Definition: Type.h:4103
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it&#39;s a function-local extern declaration...
Definition: DeclBase.h:1034
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1542
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated", "unavailable", and "availability").
Definition: Sema.h:2388
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:5652
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:71
UsingDecl * getUsingDecl() const
Gets the using declaration to which this declaration is tied.
Definition: DeclCXX.cpp:2406
void RemoveDecl(Decl *D)
Definition: Scope.h:285
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:45
void setImplicitlyInline()
Definition: Decl.h:1360
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1712
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1253
unsigned getIntWidth(QualType T) const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2571
bool isIncompleteArrayType() const
Definition: Type.h:5999
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1045
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn&#39;t annotated with enum_extensibility(ope...
Definition: Decl.cpp:3853
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3976
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:566
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl *> Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:11675
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:3771
CanQualType UnknownAnyTy
Definition: ASTContext.h:1013
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:14139
bool empty() const
Definition: Type.h:429
bool checkInitIsICE() const
Determine whether the value of the initializer attached to this declaration is an integral constant e...
Definition: Decl.cpp:2281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:539
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:1740
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
ValueType CurrentValue
Definition: Sema.h:435
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:567
bool isReserveIDT() const
Definition: Type.h:6112
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1231
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:153
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant...
Definition: Expr.cpp:2753
CanQualType UnsignedLongTy
Definition: ASTContext.h:1005
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1074
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1111
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1722
T * getAttr() const
Definition: DeclBase.h:531
CanQualType DependentTy
Definition: ASTContext.h:1013
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false)
isDeclInScope - If &#39;Ctx&#39; is a function/method, isDeclInScope returns true if &#39;D&#39; is in Scope &#39;S&#39;...
Definition: SemaDecl.cpp:1410
bool isImageType() const
Definition: Type.h:6116
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:15258
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value...
Definition: Expr.h:3389
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope...
Definition: SemaDecl.cpp:1415
bool isFunctionType() const
Definition: Type.h:5938
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:713
bool isStaticLocal() const
isStaticLocal - Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1049
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:707
static const TST TST_typename
Definition: DeclSpec.h:294
Expr * getSizeExpr() const
Definition: TypeLoc.h:1554
Opcode getOpcode() const
Definition: Expr.h:1741
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1365
param_const_iterator param_begin() const
Definition: DeclObjC.h:386
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2419
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1663
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2190
static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:5833
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
QualType getAutoDeductType() const
C++11 deduction pattern for &#39;auto&#39; type.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1534
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname...
Definition: SemaDecl.cpp:16340
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, bool isConstexpr, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1696
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1330
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:10837
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union...
Definition: SemaDecl.cpp:4574
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:90
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1425
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:4539
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
void setInherited(bool I)
Definition: Attr.h:139
void setBlockVarCopyInits(VarDecl *VD, Expr *Init)
Set the copy inialization expression of a block var decl.
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:265
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd)
Definition: SemaDecl.cpp:10880
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3597
The "class" keyword.
Definition: Type.h:4697
bool isConstantArrayType() const
Definition: Type.h:5995
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, ModuleIdPath Path)
The parser has processed a module import declaration.
Definition: SemaDecl.cpp:16133
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
Represents a base class of a C++ class.
Definition: DeclCXX.h:191
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:497
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2479
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
static void checkModuleImportContext(Sema &S, Module *M, SourceLocation ImportLoc, DeclContext *DC, bool FromInclude=false)
Definition: SemaDecl.cpp:15975
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2007
This is a scope that can contain a declaration.
Definition: Scope.h:58
SourceManager & getSourceManager()
Definition: ASTContext.h:643
void * SkippedDefinitionContext
Definition: Sema.h:2264
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any...
Definition: Decl.cpp:3181
bool isObjCObjectType() const
Definition: Type.h:6043
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1986
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:742
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:5274
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2257
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2112
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2174
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:517
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3359
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:1859
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:239
SourceRange getSourceRange() const
Definition: DeclSpec.h:1698
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:112
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1378
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2411
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Reading or writing from this object requires a barrier call.
Definition: Type.h:183
ExternCContextDecl * getExternCContextDecl() const
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:9997
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class, struct, or __interface).
Definition: SemaDecl.cpp:12880
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1554
bool isResolvedMSAsmLabel() const
Definition: Decl.h:494
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
getCXXLiteralOperatorName - Get the name of the literal operator function with II as the identifier...
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4031
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
QualType getParamType(unsigned i) const
Definition: Type.h:3491
Call-style initialization (C++98)
Definition: Decl.h:814
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
bool Failed() const
Determine whether the initialization sequence is invalid.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:989
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2387
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:190
Describes the sequence of initializations required to initialize a given object or reference with a s...
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:5497
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:8153
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:541
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3187
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:9134
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl *> Group)
Definition: SemaDecl.cpp:11379
bool isThisDeclarationADefinition() const
isThisDeclarationADefinition() - Return true if this declaration is a completion definition of the ty...
Definition: Decl.h:3091
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
Definition: ASTContext.cpp:966
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn&#39;t on...
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:6864
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3113
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:248
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1014
bool isValid() const
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations from the lookup results.
Definition: SemaDecl.cpp:1498
bool isVoidType() const
Definition: Type.h:6169
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable &#39;New&#39; which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:3733
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2856
CUDAFunctionTarget
Definition: Sema.h:9983
Represents a C array with an unspecified size.
Definition: Type.h:2672
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
NeedsRebuildingInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in th...
Definition: SemaDecl.cpp:5074
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth=nullptr)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width...
Definition: SemaDecl.cpp:14158
Missing a type from <stdio.h>
Definition: ASTContext.h:1948
Look up a friend of a local class.
Definition: Sema.h:3026
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member...
Definition: Decl.cpp:2140
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3342
void setConstexpr(bool IC)
Definition: Decl.h:2043
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:2917
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5745
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:3407
The parameter type of a method or function.
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1964
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:4327
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1177
Capturing by reference.
Definition: Lambda.h:38
bool isInherited() const
Definition: Attr.h:95
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1170
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1841
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:539
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:328
bool isSamplerT() const
Definition: Type.h:6096
The "enum" keyword.
Definition: Type.h:4700
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
Definition: SemaDecl.cpp:1805
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Declaration of a class template.
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:3779
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1010
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool isVirtualSpecified() const
Definition: DeclSpec.h:566
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:4518
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:61
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:127
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1058
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2143
void addVLATypeCapture(SourceLocation Loc, QualType CaptureType)
Definition: ScopeInfo.h:619
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
unsigned getRegParmType() const
Definition: Type.h:3204
iterator end() const
Definition: Lookup.h:339
A template-id, e.g., f<int>.
AttributePool & getPool() const
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:265
ParsedType getRepAsType() const
Definition: DeclSpec.h:485
decl_iterator end()
TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:1072
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1509
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U)
Determine whether two function types are the same, ignoring exception specifications in cases where t...
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
bool isInlineSpecified() const
Definition: DeclSpec.h:559
TLS with a known-constant initializer.
Definition: Decl.h:826
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3509
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3364
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body - that is, if it is a non-delete...
Definition: Decl.h:1980
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:543
ExprResult ExprError()
Definition: Ownership.h:267
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:3230
The translation unit is a complete translation unit.
Definition: LangOptions.h:244
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3231
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines &#39;SEL&#39;.
Definition: ASTContext.h:1620
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2324
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2283
CanQualType IntTy
Definition: ASTContext.h:1004
static OpaquePtr make(QualType P)
Definition: Ownership.h:54
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid, given that we know it&#39;s not an overload (nor a hidden tag declaration).
Definition: SemaDecl.cpp:2882
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:230
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:107
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:570
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1858
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:704
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition: Scope.h:229
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:734
bool isUnion() const
Definition: Decl.h:3165
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4493
Expr * getRHS() const
Definition: Expr.h:3031
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:381
static const TST TST_atomic
Definition: DeclSpec.h:303
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2077
bool isPointerType() const
Definition: Type.h:5942
bool hasObjectMember() const
Definition: Decl.h:3561
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
Definition: SemaDecl.cpp:5627
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1121
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1443
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:14123
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:96
SourceManager & SourceMgr
Definition: Sema.h:319
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
static const TST TST_struct
Definition: DeclSpec.h:291
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:64
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, Expr *Cpy)
Definition: ScopeInfo.h:611
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:1980
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we&#39;re skipping.
Definition: SemaDecl.cpp:1226
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:197
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1126
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:3077
static bool hasDependentAlignment(VarDecl *VD)
Determines if a variable&#39;s alignment is dependent.
Definition: SemaDecl.cpp:11144
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:586
bool isLocalVarDecl() const
isLocalVarDecl - Returns true for local variable declarations other than parameters.
Definition: Decl.h:1095
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
Definition: SemaDecl.cpp:16242
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:2692
QualType getType() const
Definition: Decl.h:638
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:111
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:342
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1174
bool isFloatingType() const
Definition: Type.cpp:1877
A trivial tuple used to represent a source range.
bool hasUnrecoverableErrorOccurred() const
Definition: Scope.h:324
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:3376
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:301
ASTContext & Context
Definition: Sema.h:316
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2845
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex)
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:999
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1712
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1690
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void dropAttr()
Definition: DeclBase.h:506
bool isTranslationUnit() const
Definition: DeclBase.h:1405
Expr * getRepAsExpr() const
Definition: DeclSpec.h:493
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:2859
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:75
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:455
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2717
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen&#39;ed or deserialized from PCH lazily, only when used; this is onl...
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:6897
No keyword precedes the qualified type name.
Definition: Type.h:4726
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1348
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1514
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:5883
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition: DeclSpec.h:971
iterator begin() const
Definition: Lookup.h:338
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:549
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:3696
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:609
Describes an entity that is being initialized.
bool isFunctionPointerType() const
Definition: Type.h:5966
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:3631
attr::Kind getKind() const
Definition: Attr.h:84
unsigned NumArgs
NumArgs - The number of template arguments.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList)
Definition: SemaDecl.cpp:14781
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:527
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:122
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2440
NamedDecl * Previous
Definition: Sema.h:1673
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclSpec.h:1878
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:607
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:3566
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:2910
Missing a type from <setjmp.h>
Definition: ASTContext.h:1951
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
void setType(QualType newType)
Definition: Decl.h:639
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared, bool isConstexpr, InheritedConstructor Inherited=InheritedConstructor())
Definition: DeclCXX.cpp:2057
bool hasInit() const
Definition: Decl.cpp:2115
Wrapper for source info for pointers.
Definition: TypeLoc.h:1271
SourceLocation getBegin() const
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:363
ParsedAttributes - A collection of parsed attributes.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:688
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2079
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2302
An implicit &#39;self&#39; parameter.
No in-class initializer.
Definition: Specifiers.h:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:4888
This class handles loading and caching of source files into memory.
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, unsigned AttrSpellingListIndex)
Attribute merging methods. Return true if a new attribute was added.
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:2799
Defines enum values for all the target-independent builtin functions.
A deduction-guide name (a template-name)
Declaration of a template function.
Definition: DeclTemplate.h:967
iterator - Iterate over the decls of a specified declaration name.
void clear()
Clears out any current state.
Definition: Lookup.h:557
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:3171
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3081
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1310
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1671
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2005
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1104
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
Attr - This represents one attribute.
Definition: Attr.h:43
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:738
SourceLocation getLocation() const
Definition: DeclBase.h:416
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3066
bool isExternallyVisible() const
Definition: Decl.h:370
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:3108
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2748
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1223
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2434
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:5143
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:95
CanQualType UnsignedIntTy
Definition: ASTContext.h:1005
This is a C++ Modules TS module interface unit.
Definition: Module.h:79
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:366
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:7462
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don&#39;t fall within the given scope as determined by isDeclInScope...
Definition: SemaDecl.cpp:1432
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1070
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:1073
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
A RAII object to temporarily push a declaration context.
Definition: Sema.h:705
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:1752
The translation unit is a module.
Definition: LangOptions.h:249
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:290
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.