clang  3.7.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 
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/DeclSpec.h"
41 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
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  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70  AllowClassTemplates(AllowTemplates) {
71  WantExpressionKeywords = false;
72  WantCXXNamedCasts = false;
73  WantRemainingKeywords = false;
74  }
75 
76  bool ValidateCandidate(const TypoCorrection &candidate) override {
77  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79  bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80  return (IsType || AllowedTemplate) &&
81  (AllowInvalidDecl || !ND->isInvalidDecl());
82  }
83  return !WantClassName && candidate.isKeyword();
84  }
85 
86  private:
87  bool AllowInvalidDecl;
88  bool WantClassName;
89  bool AllowClassTemplates;
90 };
91 
92 }
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
96  switch (Kind) {
97  // FIXME: Take into account the current language when deciding whether a
98  // token kind is a valid type specifier
99  case tok::kw_short:
100  case tok::kw_long:
101  case tok::kw___int64:
102  case tok::kw___int128:
103  case tok::kw_signed:
104  case tok::kw_unsigned:
105  case tok::kw_void:
106  case tok::kw_char:
107  case tok::kw_int:
108  case tok::kw_half:
109  case tok::kw_float:
110  case tok::kw_double:
111  case tok::kw_wchar_t:
112  case tok::kw_bool:
113  case tok::kw___underlying_type:
114  return true;
115 
116  case tok::annot_typename:
117  case tok::kw_char16_t:
118  case tok::kw_char32_t:
119  case tok::kw_typeof:
120  case tok::annot_decltype:
121  case tok::kw_decltype:
122  return getLangOpts().CPlusPlus;
123 
124  default:
125  break;
126  }
127 
128  return false;
129 }
130 
131 namespace {
133  NotFound,
134  FoundNonType,
135  FoundType
136 };
137 } // namespace
138 
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
140 /// dependent class.
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
145  SourceLocation NameLoc,
146  const CXXRecordDecl *RD) {
147  if (!RD->hasDefinition())
148  return UnqualifiedTypeNameLookupResult::NotFound;
149  // Look for type decls in base classes.
150  UnqualifiedTypeNameLookupResult FoundTypeDecl =
151  UnqualifiedTypeNameLookupResult::NotFound;
152  for (const auto &Base : RD->bases()) {
153  const CXXRecordDecl *BaseRD = nullptr;
154  if (auto *BaseTT = Base.getType()->getAs<TagType>())
155  BaseRD = BaseTT->getAsCXXRecordDecl();
156  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157  // Look for type decls in dependent base classes that have known primary
158  // templates.
159  if (!TST || !TST->isDependentType())
160  continue;
161  auto *TD = TST->getTemplateName().getAsTemplateDecl();
162  if (!TD)
163  continue;
164  auto *BasePrimaryTemplate =
165  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166  if (!BasePrimaryTemplate)
167  continue;
168  BaseRD = BasePrimaryTemplate;
169  }
170  if (BaseRD) {
171  for (NamedDecl *ND : BaseRD->lookup(&II)) {
172  if (!isa<TypeDecl>(ND))
173  return UnqualifiedTypeNameLookupResult::FoundNonType;
174  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
175  }
176  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178  case UnqualifiedTypeNameLookupResult::FoundNonType:
179  return UnqualifiedTypeNameLookupResult::FoundNonType;
180  case UnqualifiedTypeNameLookupResult::FoundType:
181  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
182  break;
183  case UnqualifiedTypeNameLookupResult::NotFound:
184  break;
185  }
186  }
187  }
188  }
189 
190  return FoundTypeDecl;
191 }
192 
194  const IdentifierInfo &II,
195  SourceLocation NameLoc) {
196  // Lookup in the parent class template context, if any.
197  const CXXRecordDecl *RD = nullptr;
198  UnqualifiedTypeNameLookupResult FoundTypeDecl =
199  UnqualifiedTypeNameLookupResult::NotFound;
200  for (DeclContext *DC = S.CurContext;
201  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202  DC = DC->getParent()) {
203  // Look for type decls in dependent base classes that have known primary
204  // templates.
205  RD = dyn_cast<CXXRecordDecl>(DC);
206  if (RD && RD->getDescribedClassTemplate())
207  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
208  }
209  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
210  return ParsedType();
211 
212  // We found some types in dependent base classes. Recover as if the user
213  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
214  // lookup during template instantiation.
215  S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
216 
218  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219  cast<Type>(Context.getRecordType(RD)));
220  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
221 
222  CXXScopeSpec SS;
223  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
224 
226  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227  DepTL.setNameLoc(NameLoc);
229  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
231 }
232 
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
235 ///
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
242  Scope *S, CXXScopeSpec *SS,
243  bool isClassName, bool HasTrailingDot,
244  ParsedType ObjectTypePtr,
245  bool IsCtorOrDtorName,
246  bool WantNontrivialTypeSourceInfo,
247  IdentifierInfo **CorrectedII) {
248  // Determine where we will perform name lookup.
249  DeclContext *LookupCtx = nullptr;
250  if (ObjectTypePtr) {
251  QualType ObjectType = ObjectTypePtr.get();
252  if (ObjectType->isRecordType())
253  LookupCtx = computeDeclContext(ObjectType);
254  } else if (SS && SS->isNotEmpty()) {
255  LookupCtx = computeDeclContext(*SS, false);
256 
257  if (!LookupCtx) {
258  if (isDependentScopeSpecifier(*SS)) {
259  // C++ [temp.res]p3:
260  // A qualified-id that refers to a type and in which the
261  // nested-name-specifier depends on a template-parameter (14.6.2)
262  // shall be prefixed by the keyword typename to indicate that the
263  // qualified-id denotes a type, forming an
264  // elaborated-type-specifier (7.1.5.3).
265  //
266  // We therefore do not perform any name lookup if the result would
267  // refer to a member of an unknown specialization.
268  if (!isClassName && !IsCtorOrDtorName)
269  return ParsedType();
270 
271  // We know from the grammar that this name refers to a type,
272  // so build a dependent node to describe the type.
273  if (WantNontrivialTypeSourceInfo)
274  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
275 
277  QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
278  II, NameLoc);
279  return ParsedType::make(T);
280  }
281 
282  return ParsedType();
283  }
284 
285  if (!LookupCtx->isDependentContext() &&
286  RequireCompleteDeclContext(*SS, LookupCtx))
287  return ParsedType();
288  }
289 
290  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291  // lookup for class-names.
292  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
293  LookupOrdinaryName;
294  LookupResult Result(*this, &II, NameLoc, Kind);
295  if (LookupCtx) {
296  // Perform "qualified" name lookup into the declaration context we
297  // computed, which is either the type of the base of a member access
298  // expression or the declaration context associated with a prior
299  // nested-name-specifier.
300  LookupQualifiedName(Result, LookupCtx);
301 
302  if (ObjectTypePtr && Result.empty()) {
303  // C++ [basic.lookup.classref]p3:
304  // If the unqualified-id is ~type-name, the type-name is looked up
305  // in the context of the entire postfix-expression. If the type T of
306  // the object expression is of a class type C, the type-name is also
307  // looked up in the scope of class C. At least one of the lookups shall
308  // find a name that refers to (possibly cv-qualified) T.
309  LookupName(Result, S);
310  }
311  } else {
312  // Perform unqualified name lookup.
313  LookupName(Result, S);
314 
315  // For unqualified lookup in a class template in MSVC mode, look into
316  // dependent base classes where the primary class template is known.
317  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318  if (ParsedType TypeInBase =
319  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
320  return TypeInBase;
321  }
322  }
323 
324  NamedDecl *IIDecl = nullptr;
325  switch (Result.getResultKind()) {
328  if (CorrectedII) {
329  TypoCorrection Correction = CorrectTypo(
330  Result.getLookupNameInfo(), Kind, S, SS,
331  llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
332  CTK_ErrorRecovery);
333  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
334  TemplateTy Template;
335  bool MemberOfUnknownSpecialization;
337  TemplateName.setIdentifier(NewII, NameLoc);
338  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339  CXXScopeSpec NewSS, *NewSSPtr = SS;
340  if (SS && NNS) {
341  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
342  NewSSPtr = &NewSS;
343  }
344  if (Correction && (NNS || NewII != &II) &&
345  // Ignore a correction to a template type as the to-be-corrected
346  // identifier is not a template (typo correction for template names
347  // is handled elsewhere).
348  !(getLangOpts().CPlusPlus && NewSSPtr &&
349  isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350  false, Template, MemberOfUnknownSpecialization))) {
351  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352  isClassName, HasTrailingDot, ObjectTypePtr,
353  IsCtorOrDtorName,
354  WantNontrivialTypeSourceInfo);
355  if (Ty) {
356  diagnoseTypo(Correction,
357  PDiag(diag::err_unknown_type_or_class_name_suggest)
358  << Result.getLookupName() << isClassName);
359  if (SS && NNS)
360  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361  *CorrectedII = NewII;
362  return Ty;
363  }
364  }
365  }
366  // If typo correction failed or was not performed, fall through
369  Result.suppressDiagnostics();
370  return ParsedType();
371 
373  // Recover from type-hiding ambiguities by hiding the type. We'll
374  // do the lookup again when looking for an object, and we can
375  // diagnose the error then. If we don't do this, then the error
376  // about hiding the type will be immediately followed by an error
377  // that only makes sense if the identifier was treated like a type.
379  Result.suppressDiagnostics();
380  return ParsedType();
381  }
382 
383  // Look to see if we have a type anywhere in the list of results.
384  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385  Res != ResEnd; ++Res) {
386  if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
387  if (!IIDecl ||
388  (*Res)->getLocation().getRawEncoding() <
389  IIDecl->getLocation().getRawEncoding())
390  IIDecl = *Res;
391  }
392  }
393 
394  if (!IIDecl) {
395  // None of the entities we found is a type, so there is no way
396  // to even assume that the result is a type. In this case, don't
397  // complain about the ambiguity. The parser will either try to
398  // perform this lookup again (e.g., as an object name), which
399  // will produce the ambiguity, or will complain that it expected
400  // a type name.
401  Result.suppressDiagnostics();
402  return ParsedType();
403  }
404 
405  // We found a type within the ambiguous lookup; diagnose the
406  // ambiguity and then return that type. This might be the right
407  // answer, or it might not be, but it suppresses any attempt to
408  // perform the name lookup again.
409  break;
410 
411  case LookupResult::Found:
412  IIDecl = Result.getFoundDecl();
413  break;
414  }
415 
416  assert(IIDecl && "Didn't find decl");
417 
418  QualType T;
419  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420  DiagnoseUseOfDecl(IIDecl, NameLoc);
421 
422  T = Context.getTypeDeclType(TD);
423  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
424 
425  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426  // constructor or destructor name (in such a case, the scope specifier
427  // will be attached to the enclosing Expr or Decl node).
428  if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429  if (WantNontrivialTypeSourceInfo) {
430  // Construct a type with type-source information.
432  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
433 
434  T = getElaboratedType(ETK_None, *SS, T);
435  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
438  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
439  } else {
440  T = getElaboratedType(ETK_None, *SS, T);
441  }
442  }
443  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
445  if (!HasTrailingDot)
446  T = Context.getObjCInterfaceType(IDecl);
447  }
448 
449  if (T.isNull()) {
450  // If it's not plausibly a type, suppress diagnostics.
451  Result.suppressDiagnostics();
452  return ParsedType();
453  }
454  return ParsedType::make(T);
455 }
456 
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
460  for (;; DC = DC->getLookupParent()) {
461  DC = DC->getPrimaryContext();
462  auto *ND = dyn_cast<NamespaceDecl>(DC);
463  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464  return NestedNameSpecifier::Create(Context, nullptr, ND);
465  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467  RD->getTypeForDecl());
468  else if (isa<TranslationUnitDecl>(DC))
469  return NestedNameSpecifier::GlobalSpecifier(Context);
470  }
471  llvm_unreachable("something isn't in TU scope?");
472 }
473 
475  SourceLocation NameLoc) {
476  // Accepting an undeclared identifier as a default argument for a template
477  // type parameter is a Microsoft extension.
478  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
479 
480  // Build a fake DependentNameType that will perform lookup into CurContext at
481  // instantiation time. The name specifier isn't dependent, so template
482  // instantiation won't transform it. It will retry the lookup, however.
483  NestedNameSpecifier *NNS =
486 
487  // Build type location information. We synthesized the qualifier, so we have
488  // to build a fake NestedNameSpecifierLoc.
489  NestedNameSpecifierLocBuilder NNSLocBuilder;
490  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
492 
494  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495  DepTL.setNameLoc(NameLoc);
497  DepTL.setQualifierLoc(QualifierLoc);
498  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
499 }
500 
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo"). If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
507  // Do a tag name lookup in this scope.
508  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509  LookupName(R, S, false);
512  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513  switch (TD->getTagKind()) {
514  case TTK_Struct: return DeclSpec::TST_struct;
516  case TTK_Union: return DeclSpec::TST_union;
517  case TTK_Class: return DeclSpec::TST_class;
518  case TTK_Enum: return DeclSpec::TST_enum;
519  }
520  }
521 
523 }
524 
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
529 /// @code
530 /// template<class T> class A {
531 /// public:
532 /// typedef int TYPE;
533 /// };
534 /// template<class T> class B : public A<T> {
535 /// public:
536 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
537 /// };
538 /// @endcode
540  if (CurContext->isRecord()) {
542  return true;
543 
544  const Type *Ty = SS->getScopeRep()->getAsType();
545 
546  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547  for (const auto &Base : RD->bases())
548  if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
549  return true;
550  return S->isFunctionPrototypeScope();
551  }
552  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
553 }
554 
556  SourceLocation IILoc,
557  Scope *S,
558  CXXScopeSpec *SS,
559  ParsedType &SuggestedType,
560  bool AllowClassTemplates) {
561  // We don't have anything to suggest (yet).
562  SuggestedType = ParsedType();
563 
564  // There may have been a typo in the name of the type. Look up typo
565  // results, in case we have something that we can suggest.
566  if (TypoCorrection Corrected =
567  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568  llvm::make_unique<TypeNameValidatorCCC>(
569  false, false, AllowClassTemplates),
570  CTK_ErrorRecovery)) {
571  if (Corrected.isKeyword()) {
572  // We corrected to a keyword.
573  diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574  II = Corrected.getCorrectionAsIdentifierInfo();
575  } else {
576  // We found a similarly-named type or interface; suggest that.
577  if (!SS || !SS->isSet()) {
578  diagnoseTypo(Corrected,
579  PDiag(diag::err_unknown_typename_suggest) << II);
580  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583  II->getName().equals(CorrectedStr);
584  diagnoseTypo(Corrected,
585  PDiag(diag::err_unknown_nested_typename_suggest)
586  << II << DC << DroppedSpecifier << SS->getRange());
587  } else {
588  llvm_unreachable("could not have corrected a typo here");
589  }
590 
591  CXXScopeSpec tmpSS;
592  if (Corrected.getCorrectionSpecifier())
593  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
594  SourceRange(IILoc));
595  SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596  IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
597  false, ParsedType(),
598  /*IsCtorOrDtorName=*/false,
599  /*NonTrivialTypeSourceInfo=*/true);
600  }
601  return;
602  }
603 
604  if (getLangOpts().CPlusPlus) {
605  // See if II is a class template that the user forgot to pass arguments to.
606  UnqualifiedId Name;
607  Name.setIdentifier(II, IILoc);
608  CXXScopeSpec EmptySS;
609  TemplateTy TemplateResult;
610  bool MemberOfUnknownSpecialization;
611  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612  Name, ParsedType(), true, TemplateResult,
613  MemberOfUnknownSpecialization) == TNK_Type_template) {
614  TemplateName TplName = TemplateResult.get();
615  Diag(IILoc, diag::err_template_missing_args) << TplName;
616  if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617  Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618  << TplDecl->getTemplateParameters()->getSourceRange();
619  }
620  return;
621  }
622  }
623 
624  // FIXME: Should we move the logic that tries to recover from a missing tag
625  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
626 
627  if (!SS || (!SS->isSet() && !SS->isInvalid()))
628  Diag(IILoc, diag::err_unknown_typename) << II;
629  else if (DeclContext *DC = computeDeclContext(*SS, false))
630  Diag(IILoc, diag::err_typename_nested_not_found)
631  << II << DC << SS->getRange();
632  else if (isDependentScopeSpecifier(*SS)) {
633  unsigned DiagID = diag::err_typename_missing;
634  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635  DiagID = diag::ext_typename_missing;
636 
637  Diag(SS->getRange().getBegin(), DiagID)
638  << SS->getScopeRep() << II->getName()
639  << SourceRange(SS->getRange().getBegin(), IILoc)
640  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641  SuggestedType = ActOnTypenameType(S, SourceLocation(),
642  *SS, *II, IILoc).get();
643  } else {
644  assert(SS && SS->isInvalid() &&
645  "Invalid scope specifier has already been diagnosed");
646  }
647 }
648 
649 /// \brief Determine whether the given result set contains either a type name
650 /// or
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653  NextToken.is(tok::less);
654 
655  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
657  return true;
658 
659  if (CheckTemplate && isa<TemplateDecl>(*I))
660  return true;
661  }
662 
663  return false;
664 }
665 
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667  Scope *S, CXXScopeSpec &SS,
668  IdentifierInfo *&Name,
669  SourceLocation NameLoc) {
670  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671  SemaRef.LookupParsedName(R, S, &SS);
672  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673  StringRef FixItTagName;
674  switch (Tag->getTagKind()) {
675  case TTK_Class:
676  FixItTagName = "class ";
677  break;
678 
679  case TTK_Enum:
680  FixItTagName = "enum ";
681  break;
682 
683  case TTK_Struct:
684  FixItTagName = "struct ";
685  break;
686 
687  case TTK_Interface:
688  FixItTagName = "__interface ";
689  break;
690 
691  case TTK_Union:
692  FixItTagName = "union ";
693  break;
694  }
695 
696  StringRef TagName = FixItTagName.drop_back();
697  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
700 
701  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
702  I != IEnd; ++I)
703  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
704  << Name << TagName;
705 
706  // Replace lookup results with just the tag decl.
707  Result.clear(Sema::LookupTagName);
708  SemaRef.LookupParsedName(Result, S, &SS);
709  return true;
710  }
711 
712  return false;
713 }
714 
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
717  QualType T, SourceLocation NameLoc) {
719 
721  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
722 
723  T = S.getElaboratedType(ETK_None, SS, T);
724  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
726  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
728 }
729 
732  SourceLocation NameLoc, const Token &NextToken,
733  bool IsAddressOfOperand,
734  std::unique_ptr<CorrectionCandidateCallback> CCC) {
735  DeclarationNameInfo NameInfo(Name, NameLoc);
736  ObjCMethodDecl *CurMethod = getCurMethodDecl();
737 
738  if (NextToken.is(tok::coloncolon)) {
739  BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740  QualType(), false, SS, nullptr, false);
741  }
742 
743  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744  LookupParsedName(Result, S, &SS, !CurMethod);
745 
746  // For unqualified lookup in a class template in MSVC mode, look into
747  // dependent base classes where the primary class template is known.
748  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749  if (ParsedType TypeInBase =
750  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
751  return TypeInBase;
752  }
753 
754  // Perform lookup for Objective-C instance variables (including automatically
755  // synthesized instance variables), if we're in an Objective-C method.
756  // FIXME: This lookup really, really needs to be folded in to the normal
757  // unqualified lookup mechanism.
758  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759  ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760  if (E.get() || E.isInvalid())
761  return E;
762  }
763 
764  bool SecondTry = false;
765  bool IsFilteredTemplateName = false;
766 
767 Corrected:
768  switch (Result.getResultKind()) {
770  // If an unqualified-id is followed by a '(', then we have a function
771  // call.
772  if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773  // In C++, this is an ADL-only call.
774  // FIXME: Reference?
775  if (getLangOpts().CPlusPlus)
776  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
777 
778  // C90 6.3.2.2:
779  // If the expression that precedes the parenthesized argument list in a
780  // function call consists solely of an identifier, and if no
781  // declaration is visible for this identifier, the identifier is
782  // implicitly declared exactly as if, in the innermost block containing
783  // the function call, the declaration
784  //
785  // extern int identifier ();
786  //
787  // appeared.
788  //
789  // We also allow this in C99 as an extension.
790  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
791  Result.addDecl(D);
792  Result.resolveKind();
793  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
794  }
795  }
796 
797  // In C, we first see whether there is a tag type by the same name, in
798  // which case it's likely that the user just forget to write "enum",
799  // "struct", or "union".
800  if (!getLangOpts().CPlusPlus && !SecondTry &&
801  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
802  break;
803  }
804 
805  // Perform typo correction to determine if there is another name that is
806  // close to this name.
807  if (!SecondTry && CCC) {
808  SecondTry = true;
809  if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810  Result.getLookupKind(), S,
811  &SS, std::move(CCC),
812  CTK_ErrorRecovery)) {
813  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814  unsigned QualifiedDiag = diag::err_no_member_suggest;
815 
816  NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817  NamedDecl *UnderlyingFirstDecl
818  = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
819  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821  UnqualifiedDiag = diag::err_no_template_suggest;
822  QualifiedDiag = diag::err_no_member_template_suggest;
823  } else if (UnderlyingFirstDecl &&
824  (isa<TypeDecl>(UnderlyingFirstDecl) ||
825  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827  UnqualifiedDiag = diag::err_unknown_typename_suggest;
828  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829  }
830 
831  if (SS.isEmpty()) {
832  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833  } else {// FIXME: is this even reachable? Test it.
834  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836  Name->getName().equals(CorrectedStr);
837  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838  << Name << computeDeclContext(SS, false)
839  << DroppedSpecifier << SS.getRange());
840  }
841 
842  // Update the name, so that the caller has the new name.
843  Name = Corrected.getCorrectionAsIdentifierInfo();
844 
845  // Typo correction corrected to a keyword.
846  if (Corrected.isKeyword())
847  return Name;
848 
849  // Also update the LookupResult...
850  // FIXME: This should probably go away at some point
851  Result.clear();
852  Result.setLookupName(Corrected.getCorrection());
853  if (FirstDecl)
854  Result.addDecl(FirstDecl);
855 
856  // If we found an Objective-C instance variable, let
857  // LookupInObjCMethod build the appropriate expression to
858  // reference the ivar.
859  // FIXME: This is a gross hack.
860  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861  Result.clear();
862  ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863  return E;
864  }
865 
866  goto Corrected;
867  }
868  }
869 
870  // We failed to correct; just fall through and let the parser deal with it.
871  Result.suppressDiagnostics();
873 
875  // We performed name lookup into the current instantiation, and there were
876  // dependent bases, so we treat this result the same way as any other
877  // dependent nested-name-specifier.
878 
879  // C++ [temp.res]p2:
880  // A name used in a template declaration or definition and that is
881  // dependent on a template-parameter is assumed not to name a type
882  // unless the applicable name lookup finds a type name or the name is
883  // qualified by the keyword typename.
884  //
885  // FIXME: If the next token is '<', we might want to ask the parser to
886  // perform some heroics to see if we actually have a
887  // template-argument-list, which would indicate a missing 'template'
888  // keyword here.
889  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890  NameInfo, IsAddressOfOperand,
891  /*TemplateArgs=*/nullptr);
892  }
893 
894  case LookupResult::Found:
897  break;
898 
900  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901  hasAnyAcceptableTemplateNames(Result)) {
902  // C++ [temp.local]p3:
903  // A lookup that finds an injected-class-name (10.2) can result in an
904  // ambiguity in certain cases (for example, if it is found in more than
905  // one base class). If all of the injected-class-names that are found
906  // refer to specializations of the same class template, and if the name
907  // is followed by a template-argument-list, the reference refers to the
908  // class template itself and not a specialization thereof, and is not
909  // ambiguous.
910  //
911  // This filtering can make an ambiguous result into an unambiguous one,
912  // so try again after filtering out template names.
913  FilterAcceptableTemplateNames(Result);
914  if (!Result.isAmbiguous()) {
915  IsFilteredTemplateName = true;
916  break;
917  }
918  }
919 
920  // Diagnose the ambiguity and return an error.
921  return NameClassification::Error();
922  }
923 
924  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925  (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926  // C++ [temp.names]p3:
927  // After name lookup (3.4) finds that a name is a template-name or that
928  // an operator-function-id or a literal- operator-id refers to a set of
929  // overloaded functions any member of which is a function template if
930  // this is followed by a <, the < is always taken as the delimiter of a
931  // template-argument-list and never as the less-than operator.
932  if (!IsFilteredTemplateName)
933  FilterAcceptableTemplateNames(Result);
934 
935  if (!Result.empty()) {
936  bool IsFunctionTemplate;
937  bool IsVarTemplate;
938  TemplateName Template;
939  if (Result.end() - Result.begin() > 1) {
940  IsFunctionTemplate = true;
941  Template = Context.getOverloadedTemplateName(Result.begin(),
942  Result.end());
943  } else {
944  TemplateDecl *TD
945  = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947  IsVarTemplate = isa<VarTemplateDecl>(TD);
948 
949  if (SS.isSet() && !SS.isInvalid())
951  /*TemplateKeyword=*/false,
952  TD);
953  else
954  Template = TemplateName(TD);
955  }
956 
957  if (IsFunctionTemplate) {
958  // Function templates always go through overload resolution, at which
959  // point we'll perform the various checks (e.g., accessibility) we need
960  // to based on which function we selected.
961  Result.suppressDiagnostics();
962 
963  return NameClassification::FunctionTemplate(Template);
964  }
965 
966  return IsVarTemplate ? NameClassification::VarTemplate(Template)
967  : NameClassification::TypeTemplate(Template);
968  }
969  }
970 
971  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973  DiagnoseUseOfDecl(Type, NameLoc);
974  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
976  if (SS.isNotEmpty())
977  return buildNestedType(*this, SS, T, NameLoc);
978  return ParsedType::make(T);
979  }
980 
981  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982  if (!Class) {
983  // FIXME: It's unfortunate that we don't have a Type node for handling this.
984  if (ObjCCompatibleAliasDecl *Alias =
985  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986  Class = Alias->getClassInterface();
987  }
988 
989  if (Class) {
990  DiagnoseUseOfDecl(Class, NameLoc);
991 
992  if (NextToken.is(tok::period)) {
993  // Interface. <something> is parsed as a property reference expression.
994  // Just return "unknown" as a fall-through for now.
995  Result.suppressDiagnostics();
997  }
998 
1000  return ParsedType::make(T);
1001  }
1002 
1003  // We can have a type template here if we're classifying a template argument.
1004  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005  return NameClassification::TypeTemplate(
1006  TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 
1008  // Check for a tag type hidden by a non-type decl in a few cases where it
1009  // seems likely a type is wanted instead of the non-type that was found.
1010  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011  if ((NextToken.is(tok::identifier) ||
1012  (NextIsOp &&
1013  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016  DiagnoseUseOfDecl(Type, NameLoc);
1017  QualType T = Context.getTypeDeclType(Type);
1018  if (SS.isNotEmpty())
1019  return buildNestedType(*this, SS, T, NameLoc);
1020  return ParsedType::make(T);
1021  }
1022 
1023  if (FirstDecl->isCXXClassMember())
1024  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025  nullptr);
1026 
1027  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028  return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030 
1031 // Determines the context to return to after temporarily entering a
1032 // context. This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1035 
1036  // Functions defined inline within classes aren't parsed until we've
1037  // finished parsing the top-level class, so the top-level class is
1038  // the context we'll need to return to.
1039  // A Lambda call operator whose parent is a class must not be treated
1040  // as an inline member function. A Lambda can be used legally
1041  // either as an in-class member initializer or a default argument. These
1042  // are parsed once the class has been marked complete and so the containing
1043  // context would be the nested class (when the lambda is defined in one);
1044  // If the class is not complete, then the lambda is being used in an
1045  // ill-formed fashion (such as to specify the width of a bit-field, or
1046  // in an array-bound) - in which case we still want to return the
1047  // lexically containing DC (which could be a nested class).
1048  if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049  DC = DC->getLexicalParent();
1050 
1051  // A function not defined within a class will always return to its
1052  // lexical context.
1053  if (!isa<CXXRecordDecl>(DC))
1054  return DC;
1055 
1056  // A C++ inline method/friend is parsed *after* the topmost class
1057  // it was declared in is fully parsed ("complete"); the topmost
1058  // class is the context we need to return to.
1059  while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060  DC = RD;
1061 
1062  // Return the declaration context of the topmost class the inline method is
1063  // declared in.
1064  return DC;
1065  }
1066 
1067  return DC->getLexicalParent();
1068 }
1069 
1071  assert(getContainingDC(DC) == CurContext &&
1072  "The next DeclContext should be lexically contained in the current one.");
1073  CurContext = DC;
1074  S->setEntity(DC);
1075 }
1076 
1078  assert(CurContext && "DeclContext imbalance!");
1079 
1080  CurContext = getContainingDC(CurContext);
1081  assert(CurContext && "Popped translation unit!");
1082 }
1083 
1085  Decl *D) {
1086  // Unlike PushDeclContext, the context to which we return is not necessarily
1087  // the containing DC of TD, because the new context will be some pre-existing
1088  // TagDecl definition instead of a fresh one.
1089  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090  CurContext = cast<TagDecl>(D)->getDefinition();
1091  assert(CurContext && "skipping definition of undefined tag");
1092  S->setEntity(CurContext);
1093  return Result;
1094 }
1095 
1097  CurContext = static_cast<decltype(CurContext)>(Context);
1098 }
1099 
1100 /// EnterDeclaratorContext - Used when we must lookup names in the context
1101 /// of a declarator's nested name specifier.
1102 ///
1104  // C++0x [basic.lookup.unqual]p13:
1105  // A name used in the definition of a static data member of class
1106  // X (after the qualified-id of the static member) is looked up as
1107  // if the name was used in a member function of X.
1108  // C++0x [basic.lookup.unqual]p14:
1109  // If a variable member of a namespace is defined outside of the
1110  // scope of its namespace then any name used in the definition of
1111  // the variable member (after the declarator-id) is looked up as
1112  // if the definition of the variable member occurred in its
1113  // namespace.
1114  // Both of these imply that we should push a scope whose context
1115  // is the semantic context of the declaration. We can't use
1116  // PushDeclContext here because that context is not necessarily
1117  // lexically contained in the current context. Fortunately,
1118  // the containing scope should have the appropriate information.
1119 
1120  assert(!S->getEntity() && "scope already has entity");
1121 
1122 #ifndef NDEBUG
1123  Scope *Ancestor = S->getParent();
1124  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1125  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1126 #endif
1127 
1128  CurContext = DC;
1129  S->setEntity(DC);
1130 }
1131 
1133  assert(S->getEntity() == CurContext && "Context imbalance!");
1134 
1135  // Switch back to the lexical context. The safety of this is
1136  // enforced by an assert in EnterDeclaratorContext.
1137  Scope *Ancestor = S->getParent();
1138  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1139  CurContext = Ancestor->getEntity();
1140 
1141  // We don't need to do anything with the scope, which is going to
1142  // disappear.
1143 }
1144 
1145 
1147  // We assume that the caller has already called
1148  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1149  FunctionDecl *FD = D->getAsFunction();
1150  if (!FD)
1151  return;
1152 
1153  // Same implementation as PushDeclContext, but enters the context
1154  // from the lexical parent, rather than the top-level class.
1155  assert(CurContext == FD->getLexicalParent() &&
1156  "The next DeclContext should be lexically contained in the current one.");
1157  CurContext = FD;
1158  S->setEntity(CurContext);
1159 
1160  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1161  ParmVarDecl *Param = FD->getParamDecl(P);
1162  // If the parameter has an identifier, then add it to the scope
1163  if (Param->getIdentifier()) {
1164  S->AddDecl(Param);
1165  IdResolver.AddDecl(Param);
1166  }
1167  }
1168 }
1169 
1170 
1172  // Same implementation as PopDeclContext, but returns to the lexical parent,
1173  // rather than the top-level class.
1174  assert(CurContext && "DeclContext imbalance!");
1175  CurContext = CurContext->getLexicalParent();
1176  assert(CurContext && "Popped translation unit!");
1177 }
1178 
1179 
1180 /// \brief Determine whether we allow overloading of the function
1181 /// PrevDecl with another declaration.
1182 ///
1183 /// This routine determines whether overloading is possible, not
1184 /// whether some new function is actually an overload. It will return
1185 /// true in C++ (where we can always provide overloads) or, as an
1186 /// extension, in C when the previous function is already an
1187 /// overloaded function declaration or has the "overloadable"
1188 /// attribute.
1190  ASTContext &Context) {
1191  if (Context.getLangOpts().CPlusPlus)
1192  return true;
1193 
1194  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1195  return true;
1196 
1197  return (Previous.getResultKind() == LookupResult::Found
1198  && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1199 }
1200 
1201 /// Add this decl to the scope shadowed decl chains.
1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1203  // Move up the scope chain until we find the nearest enclosing
1204  // non-transparent context. The declaration will be introduced into this
1205  // scope.
1206  while (S->getEntity() && S->getEntity()->isTransparentContext())
1207  S = S->getParent();
1208 
1209  // Add scoped declarations into their context, so that they can be
1210  // found later. Declarations without a context won't be inserted
1211  // into any context.
1212  if (AddToContext)
1213  CurContext->addDecl(D);
1214 
1215  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1216  // are function-local declarations.
1217  if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1221  return;
1222 
1223  // Template instantiations should also not be pushed into scope.
1224  if (isa<FunctionDecl>(D) &&
1225  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1226  return;
1227 
1228  // If this replaces anything in the current scope,
1229  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1230  IEnd = IdResolver.end();
1231  for (; I != IEnd; ++I) {
1232  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1233  S->RemoveDecl(*I);
1234  IdResolver.RemoveDecl(*I);
1235 
1236  // Should only need to replace one decl.
1237  break;
1238  }
1239  }
1240 
1241  S->AddDecl(D);
1242 
1243  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1244  // Implicitly-generated labels may end up getting generated in an order that
1245  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1246  // the label at the appropriate place in the identifier chain.
1247  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1248  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1249  if (IDC == CurContext) {
1250  if (!S->isDeclScope(*I))
1251  continue;
1252  } else if (IDC->Encloses(CurContext))
1253  break;
1254  }
1255 
1256  IdResolver.InsertDeclAfter(I, D);
1257  } else {
1258  IdResolver.AddDecl(D);
1259  }
1260 }
1261 
1263  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1264  TUScope->AddDecl(D);
1265 }
1266 
1268  bool AllowInlineNamespace) {
1269  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1270 }
1271 
1273  DeclContext *TargetDC = DC->getPrimaryContext();
1274  do {
1275  if (DeclContext *ScopeDC = S->getEntity())
1276  if (ScopeDC->getPrimaryContext() == TargetDC)
1277  return S;
1278  } while ((S = S->getParent()));
1279 
1280  return nullptr;
1281 }
1282 
1284  DeclContext*,
1285  ASTContext&);
1286 
1287 /// Filters out lookup results that don't fall within the given scope
1288 /// as determined by isDeclInScope.
1290  bool ConsiderLinkage,
1291  bool AllowInlineNamespace) {
1293  while (F.hasNext()) {
1294  NamedDecl *D = F.next();
1295 
1296  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1297  continue;
1298 
1299  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1300  continue;
1301 
1302  F.erase();
1303  }
1304 
1305  F.done();
1306 }
1307 
1308 static bool isUsingDecl(NamedDecl *D) {
1309  return isa<UsingShadowDecl>(D) ||
1310  isa<UnresolvedUsingTypenameDecl>(D) ||
1311  isa<UnresolvedUsingValueDecl>(D);
1312 }
1313 
1314 /// Removes using shadow declarations from the lookup results.
1317  while (F.hasNext())
1318  if (isUsingDecl(F.next()))
1319  F.erase();
1320 
1321  F.done();
1322 }
1323 
1324 /// \brief Check for this common pattern:
1325 /// @code
1326 /// class S {
1327 /// S(const S&); // DO NOT IMPLEMENT
1328 /// void operator=(const S&); // DO NOT IMPLEMENT
1329 /// };
1330 /// @endcode
1332  // FIXME: Should check for private access too but access is set after we get
1333  // the decl here.
1335  return false;
1336 
1337  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1338  return CD->isCopyConstructor();
1339  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1340  return Method->isCopyAssignmentOperator();
1341  return false;
1342 }
1343 
1344 // We need this to handle
1345 //
1346 // typedef struct {
1347 // void *foo() { return 0; }
1348 // } A;
1349 //
1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1351 // for example. If 'A', foo will have external linkage. If we have '*A',
1352 // foo will have no linkage. Since we can't know until we get to the end
1353 // of the typedef, this function finds out if D might have non-external linkage.
1354 // Callers should verify at the end of the TU if it D has external linkage or
1355 // not.
1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1357  const DeclContext *DC = D->getDeclContext();
1358  while (!DC->isTranslationUnit()) {
1359  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1360  if (!RD->hasNameForLinkage())
1361  return true;
1362  }
1363  DC = DC->getParent();
1364  }
1365 
1366  return !D->isExternallyVisible();
1367 }
1368 
1369 // FIXME: This needs to be refactored; some other isInMainFile users want
1370 // these semantics.
1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1372  if (S.TUKind != TU_Complete)
1373  return false;
1374  return S.SourceMgr.isInMainFile(Loc);
1375 }
1376 
1378  assert(D);
1379 
1380  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1381  return false;
1382 
1383  // Ignore all entities declared within templates, and out-of-line definitions
1384  // of members of class templates.
1385  if (D->getDeclContext()->isDependentContext() ||
1387  return false;
1388 
1389  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1390  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1391  return false;
1392 
1393  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1394  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1395  return false;
1396  } else {
1397  // 'static inline' functions are defined in headers; don't warn.
1398  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1399  return false;
1400  }
1401 
1402  if (FD->doesThisDeclarationHaveABody() &&
1404  return false;
1405  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1406  // Constants and utility variables are defined in headers with internal
1407  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1408  // like "inline".)
1409  if (!isMainFileLoc(*this, VD->getLocation()))
1410  return false;
1411 
1412  if (Context.DeclMustBeEmitted(VD))
1413  return false;
1414 
1415  if (VD->isStaticDataMember() &&
1416  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1417  return false;
1418  } else {
1419  return false;
1420  }
1421 
1422  // Only warn for unused decls internal to the translation unit.
1423  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1424  // for inline functions defined in the main source file, for instance.
1425  return mightHaveNonExternalLinkage(D);
1426 }
1427 
1429  if (!D)
1430  return;
1431 
1432  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1433  const FunctionDecl *First = FD->getFirstDecl();
1434  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1435  return; // First should already be in the vector.
1436  }
1437 
1438  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1439  const VarDecl *First = VD->getFirstDecl();
1440  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1441  return; // First should already be in the vector.
1442  }
1443 
1444  if (ShouldWarnIfUnusedFileScopedDecl(D))
1445  UnusedFileScopedDecls.push_back(D);
1446 }
1447 
1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1449  if (D->isInvalidDecl())
1450  return false;
1451 
1452  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1453  D->hasAttr<ObjCPreciseLifetimeAttr>())
1454  return false;
1455 
1456  if (isa<LabelDecl>(D))
1457  return true;
1458 
1459  // Except for labels, we only care about unused decls that are local to
1460  // functions.
1461  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1462  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1463  // For dependent types, the diagnostic is deferred.
1464  WithinFunction =
1465  WithinFunction || (R->isLocalClass() && !R->isDependentType());
1466  if (!WithinFunction)
1467  return false;
1468 
1469  if (isa<TypedefNameDecl>(D))
1470  return true;
1471 
1472  // White-list anything that isn't a local variable.
1473  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1474  return false;
1475 
1476  // Types of valid local variables should be complete, so this should succeed.
1477  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1478 
1479  // White-list anything with an __attribute__((unused)) type.
1480  QualType Ty = VD->getType();
1481 
1482  // Only look at the outermost level of typedef.
1483  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1484  if (TT->getDecl()->hasAttr<UnusedAttr>())
1485  return false;
1486  }
1487 
1488  // If we failed to complete the type for some reason, or if the type is
1489  // dependent, don't diagnose the variable.
1490  if (Ty->isIncompleteType() || Ty->isDependentType())
1491  return false;
1492 
1493  if (const TagType *TT = Ty->getAs<TagType>()) {
1494  const TagDecl *Tag = TT->getDecl();
1495  if (Tag->hasAttr<UnusedAttr>())
1496  return false;
1497 
1498  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1499  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1500  return false;
1501 
1502  if (const Expr *Init = VD->getInit()) {
1503  if (const ExprWithCleanups *Cleanups =
1504  dyn_cast<ExprWithCleanups>(Init))
1505  Init = Cleanups->getSubExpr();
1506  const CXXConstructExpr *Construct =
1507  dyn_cast<CXXConstructExpr>(Init);
1508  if (Construct && !Construct->isElidable()) {
1509  CXXConstructorDecl *CD = Construct->getConstructor();
1510  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1511  return false;
1512  }
1513  }
1514  }
1515  }
1516 
1517  // TODO: __attribute__((unused)) templates?
1518  }
1519 
1520  return true;
1521 }
1522 
1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1524  FixItHint &Hint) {
1525  if (isa<LabelDecl>(D)) {
1527  tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1528  if (AfterColon.isInvalid())
1529  return;
1531  getCharRange(D->getLocStart(), AfterColon));
1532  }
1533  return;
1534 }
1535 
1537  if (D->getTypeForDecl()->isDependentType())
1538  return;
1539 
1540  for (auto *TmpD : D->decls()) {
1541  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1542  DiagnoseUnusedDecl(T);
1543  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1544  DiagnoseUnusedNestedTypedefs(R);
1545  }
1546 }
1547 
1548 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1549 /// unless they are marked attr(unused).
1551  if (!ShouldDiagnoseUnusedDecl(D))
1552  return;
1553 
1554  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1555  // typedefs can be referenced later on, so the diagnostics are emitted
1556  // at end-of-translation-unit.
1557  UnusedLocalTypedefNameCandidates.insert(TD);
1558  return;
1559  }
1560 
1561  FixItHint Hint;
1563 
1564  unsigned DiagID;
1565  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1566  DiagID = diag::warn_unused_exception_param;
1567  else if (isa<LabelDecl>(D))
1568  DiagID = diag::warn_unused_label;
1569  else
1570  DiagID = diag::warn_unused_variable;
1571 
1572  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1573 }
1574 
1575 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1576  // Verify that we have no forward references left. If so, there was a goto
1577  // or address of a label taken, but no definition of it. Label fwd
1578  // definitions are indicated with a null substmt which is also not a resolved
1579  // MS inline assembly label name.
1580  bool Diagnose = false;
1581  if (L->isMSAsmLabel())
1582  Diagnose = !L->isResolvedMSAsmLabel();
1583  else
1584  Diagnose = L->getStmt() == nullptr;
1585  if (Diagnose)
1586  S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1587 }
1588 
1590  S->mergeNRVOIntoParent();
1591 
1592  if (S->decl_empty()) return;
1593  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1594  "Scope shouldn't contain decls!");
1595 
1596  for (auto *TmpD : S->decls()) {
1597  assert(TmpD && "This decl didn't get pushed??");
1598 
1599  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1600  NamedDecl *D = cast<NamedDecl>(TmpD);
1601 
1602  if (!D->getDeclName()) continue;
1603 
1604  // Diagnose unused variables in this scope.
1605  if (!S->hasUnrecoverableErrorOccurred()) {
1606  DiagnoseUnusedDecl(D);
1607  if (const auto *RD = dyn_cast<RecordDecl>(D))
1608  DiagnoseUnusedNestedTypedefs(RD);
1609  }
1610 
1611  // If this was a forward reference to a label, verify it was defined.
1612  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1613  CheckPoppedLabel(LD, *this);
1614 
1615  // Remove this name from our lexical scope.
1616  IdResolver.RemoveDecl(D);
1617  }
1618 }
1619 
1620 /// \brief Look for an Objective-C class in the translation unit.
1621 ///
1622 /// \param Id The name of the Objective-C class we're looking for. If
1623 /// typo-correction fixes this name, the Id will be updated
1624 /// to the fixed name.
1625 ///
1626 /// \param IdLoc The location of the name in the translation unit.
1627 ///
1628 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1629 /// if there is no class with the given name.
1630 ///
1631 /// \returns The declaration of the named Objective-C class, or NULL if the
1632 /// class could not be found.
1634  SourceLocation IdLoc,
1635  bool DoTypoCorrection) {
1636  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1637  // creation from this context.
1638  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1639 
1640  if (!IDecl && DoTypoCorrection) {
1641  // Perform typo correction at the given location, but only if we
1642  // find an Objective-C class name.
1643  if (TypoCorrection C = CorrectTypo(
1644  DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1645  llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1646  CTK_ErrorRecovery)) {
1647  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1648  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1649  Id = IDecl->getIdentifier();
1650  }
1651  }
1652  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1653  // This routine must always return a class definition, if any.
1654  if (Def && Def->getDefinition())
1655  Def = Def->getDefinition();
1656  return Def;
1657 }
1658 
1659 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1660 /// from S, where a non-field would be declared. This routine copes
1661 /// with the difference between C and C++ scoping rules in structs and
1662 /// unions. For example, the following code is well-formed in C but
1663 /// ill-formed in C++:
1664 /// @code
1665 /// struct S6 {
1666 /// enum { BAR } e;
1667 /// };
1668 ///
1669 /// void test_S6() {
1670 /// struct S6 a;
1671 /// a.e = BAR;
1672 /// }
1673 /// @endcode
1674 /// For the declaration of BAR, this routine will return a different
1675 /// scope. The scope S will be the scope of the unnamed enumeration
1676 /// within S6. In C++, this routine will return the scope associated
1677 /// with S6, because the enumeration's scope is a transparent
1678 /// context but structures can contain non-field names. In C, this
1679 /// routine will return the translation unit scope, since the
1680 /// enumeration's scope is a transparent context and structures cannot
1681 /// contain non-field names.
1683  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1684  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1685  (S->isClassScope() && !getLangOpts().CPlusPlus))
1686  S = S->getParent();
1687  return S;
1688 }
1689 
1690 /// \brief Looks up the declaration of "struct objc_super" and
1691 /// saves it for later use in building builtin declaration of
1692 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1693 /// pre-existing declaration exists no action takes place.
1694 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1695  IdentifierInfo *II) {
1696  if (!II->isStr("objc_msgSendSuper"))
1697  return;
1698  ASTContext &Context = ThisSema.Context;
1699 
1700  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1702  ThisSema.LookupName(Result, S);
1703  if (Result.getResultKind() == LookupResult::Found)
1704  if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1705  Context.setObjCSuperType(Context.getTagDeclType(TD));
1706 }
1707 
1709  switch (Error) {
1710  case ASTContext::GE_None:
1711  return "";
1713  return "stdio.h";
1715  return "setjmp.h";
1717  return "ucontext.h";
1718  }
1719  llvm_unreachable("unhandled error kind");
1720 }
1721 
1722 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1723 /// file scope. lazily create a decl for it. ForRedeclaration is true
1724 /// if we're creating this built-in in anticipation of redeclaring the
1725 /// built-in.
1727  Scope *S, bool ForRedeclaration,
1728  SourceLocation Loc) {
1729  LookupPredefedObjCSuperType(*this, S, II);
1730 
1732  QualType R = Context.GetBuiltinType(ID, Error);
1733  if (Error) {
1734  if (ForRedeclaration)
1735  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1736  << getHeaderName(Error)
1737  << Context.BuiltinInfo.GetName(ID);
1738  return nullptr;
1739  }
1740 
1741  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1742  Diag(Loc, diag::ext_implicit_lib_function_decl)
1743  << Context.BuiltinInfo.GetName(ID)
1744  << R;
1745  if (Context.BuiltinInfo.getHeaderName(ID) &&
1746  !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1747  Diag(Loc, diag::note_include_header_or_declare)
1749  << Context.BuiltinInfo.GetName(ID);
1750  }
1751 
1753  if (getLangOpts().CPlusPlus) {
1754  LinkageSpecDecl *CLinkageDecl =
1755  LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1756  LinkageSpecDecl::lang_c, false);
1757  CLinkageDecl->setImplicit();
1758  Parent->addDecl(CLinkageDecl);
1759  Parent = CLinkageDecl;
1760  }
1761 
1763  Parent,
1764  Loc, Loc, II, R, /*TInfo=*/nullptr,
1765  SC_Extern,
1766  false,
1767  R->isFunctionProtoType());
1768  New->setImplicit();
1769 
1770  // Create Decl objects for each parameter, adding them to the
1771  // FunctionDecl.
1772  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1774  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775  ParmVarDecl *parm =
1777  nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778  SC_None, nullptr);
1779  parm->setScopeInfo(0, i);
1780  Params.push_back(parm);
1781  }
1782  New->setParams(Params);
1783  }
1784 
1785  AddKnownFunctionAttributes(New);
1786  RegisterLocallyScopedExternCDecl(New, S);
1787 
1788  // TUScope is the translation-unit scope to insert this function into.
1789  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1790  // relate Scopes to DeclContexts, and probably eliminate CurContext
1791  // entirely, but we're not there yet.
1792  DeclContext *SavedContext = CurContext;
1793  CurContext = Parent;
1794  PushOnScopeChains(New, TUScope);
1795  CurContext = SavedContext;
1796  return New;
1797 }
1798 
1799 /// \brief Filter out any previous declarations that the given declaration
1800 /// should not consider because they are not permitted to conflict, e.g.,
1801 /// because they come from hidden sub-modules and do not refer to the same
1802 /// entity.
1804  NamedDecl *decl,
1805  LookupResult &previous){
1806  // This is only interesting when modules are enabled.
1807  if ((!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) ||
1808  !S.getLangOpts().ModulesHideInternalLinkage)
1809  return;
1810 
1811  // Empty sets are uninteresting.
1812  if (previous.empty())
1813  return;
1814 
1815  LookupResult::Filter filter = previous.makeFilter();
1816  while (filter.hasNext()) {
1817  NamedDecl *old = filter.next();
1818 
1819  // Non-hidden declarations are never ignored.
1820  if (S.isVisible(old))
1821  continue;
1822 
1823  if (!old->isExternallyVisible())
1824  filter.erase();
1825  }
1826 
1827  filter.done();
1828 }
1829 
1830 /// Typedef declarations don't have linkage, but they still denote the same
1831 /// entity if their types are the same.
1832 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1833 /// isSameEntity.
1837  // This is only interesting when modules are enabled.
1838  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1839  return;
1840 
1841  // Empty sets are uninteresting.
1842  if (Previous.empty())
1843  return;
1844 
1845  LookupResult::Filter Filter = Previous.makeFilter();
1846  while (Filter.hasNext()) {
1847  NamedDecl *Old = Filter.next();
1848 
1849  // Non-hidden declarations are never ignored.
1850  if (S.isVisible(Old))
1851  continue;
1852 
1853  // Declarations of the same entity are not ignored, even if they have
1854  // different linkages.
1855  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1856  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1857  Decl->getUnderlyingType()))
1858  continue;
1859 
1860  // If both declarations give a tag declaration a typedef name for linkage
1861  // purposes, then they declare the same entity.
1862  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1864  continue;
1865  }
1866 
1867  if (!Old->isExternallyVisible())
1868  Filter.erase();
1869  }
1870 
1871  Filter.done();
1872 }
1873 
1875  QualType OldType;
1876  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1877  OldType = OldTypedef->getUnderlyingType();
1878  else
1879  OldType = Context.getTypeDeclType(Old);
1880  QualType NewType = New->getUnderlyingType();
1881 
1882  if (NewType->isVariablyModifiedType()) {
1883  // Must not redefine a typedef with a variably-modified type.
1884  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1885  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1886  << Kind << NewType;
1887  if (Old->getLocation().isValid())
1888  Diag(Old->getLocation(), diag::note_previous_definition);
1889  New->setInvalidDecl();
1890  return true;
1891  }
1892 
1893  if (OldType != NewType &&
1894  !OldType->isDependentType() &&
1895  !NewType->isDependentType() &&
1896  !Context.hasSameType(OldType, NewType)) {
1897  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1898  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1899  << Kind << NewType << OldType;
1900  if (Old->getLocation().isValid())
1901  Diag(Old->getLocation(), diag::note_previous_definition);
1902  New->setInvalidDecl();
1903  return true;
1904  }
1905  return false;
1906 }
1907 
1908 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1909 /// same name and scope as a previous declaration 'Old'. Figure out
1910 /// how to resolve this situation, merging decls or emitting
1911 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1912 ///
1914  // If the new decl is known invalid already, don't bother doing any
1915  // merging checks.
1916  if (New->isInvalidDecl()) return;
1917 
1918  // Allow multiple definitions for ObjC built-in typedefs.
1919  // FIXME: Verify the underlying types are equivalent!
1920  if (getLangOpts().ObjC1) {
1921  const IdentifierInfo *TypeID = New->getIdentifier();
1922  switch (TypeID->getLength()) {
1923  default: break;
1924  case 2:
1925  {
1926  if (!TypeID->isStr("id"))
1927  break;
1928  QualType T = New->getUnderlyingType();
1929  if (!T->isPointerType())
1930  break;
1931  if (!T->isVoidPointerType()) {
1932  QualType PT = T->getAs<PointerType>()->getPointeeType();
1933  if (!PT->isStructureType())
1934  break;
1935  }
1937  // Install the built-in type for 'id', ignoring the current definition.
1939  return;
1940  }
1941  case 5:
1942  if (!TypeID->isStr("Class"))
1943  break;
1945  // Install the built-in type for 'Class', ignoring the current definition.
1947  return;
1948  case 3:
1949  if (!TypeID->isStr("SEL"))
1950  break;
1952  // Install the built-in type for 'SEL', ignoring the current definition.
1954  return;
1955  }
1956  // Fall through - the typedef name was not a builtin type.
1957  }
1958 
1959  // Verify the old decl was also a type.
1960  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1961  if (!Old) {
1962  Diag(New->getLocation(), diag::err_redefinition_different_kind)
1963  << New->getDeclName();
1964 
1965  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1966  if (OldD->getLocation().isValid())
1967  Diag(OldD->getLocation(), diag::note_previous_definition);
1968 
1969  return New->setInvalidDecl();
1970  }
1971 
1972  // If the old declaration is invalid, just give up here.
1973  if (Old->isInvalidDecl())
1974  return New->setInvalidDecl();
1975 
1976  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1977  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1978  auto *NewTag = New->getAnonDeclWithTypedefName();
1979  NamedDecl *Hidden = nullptr;
1980  if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1981  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1982  !hasVisibleDefinition(OldTag, &Hidden)) {
1983  // There is a definition of this tag, but it is not visible. Use it
1984  // instead of our tag.
1985  New->setTypeForDecl(OldTD->getTypeForDecl());
1986  if (OldTD->isModed())
1987  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1988  OldTD->getUnderlyingType());
1989  else
1990  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1991 
1992  // Make the old tag definition visible.
1993  makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1994  }
1995  }
1996 
1997  // If the typedef types are not identical, reject them in all languages and
1998  // with any extensions enabled.
1999  if (isIncompatibleTypedef(Old, New))
2000  return;
2001 
2002  // The types match. Link up the redeclaration chain and merge attributes if
2003  // the old declaration was a typedef.
2004  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2005  New->setPreviousDecl(Typedef);
2006  mergeDeclAttributes(New, Old);
2007  }
2008 
2009  if (getLangOpts().MicrosoftExt)
2010  return;
2011 
2012  if (getLangOpts().CPlusPlus) {
2013  // C++ [dcl.typedef]p2:
2014  // In a given non-class scope, a typedef specifier can be used to
2015  // redefine the name of any type declared in that scope to refer
2016  // to the type to which it already refers.
2017  if (!isa<CXXRecordDecl>(CurContext))
2018  return;
2019 
2020  // C++0x [dcl.typedef]p4:
2021  // In a given class scope, a typedef specifier can be used to redefine
2022  // any class-name declared in that scope that is not also a typedef-name
2023  // to refer to the type to which it already refers.
2024  //
2025  // This wording came in via DR424, which was a correction to the
2026  // wording in DR56, which accidentally banned code like:
2027  //
2028  // struct S {
2029  // typedef struct A { } A;
2030  // };
2031  //
2032  // in the C++03 standard. We implement the C++0x semantics, which
2033  // allow the above but disallow
2034  //
2035  // struct S {
2036  // typedef int I;
2037  // typedef int I;
2038  // };
2039  //
2040  // since that was the intent of DR56.
2041  if (!isa<TypedefNameDecl>(Old))
2042  return;
2043 
2044  Diag(New->getLocation(), diag::err_redefinition)
2045  << New->getDeclName();
2046  Diag(Old->getLocation(), diag::note_previous_definition);
2047  return New->setInvalidDecl();
2048  }
2049 
2050  // Modules always permit redefinition of typedefs, as does C11.
2051  if (getLangOpts().Modules || getLangOpts().C11)
2052  return;
2053 
2054  // If we have a redefinition of a typedef in C, emit a warning. This warning
2055  // is normally mapped to an error, but can be controlled with
2056  // -Wtypedef-redefinition. If either the original or the redefinition is
2057  // in a system header, don't emit this for compatibility with GCC.
2058  if (getDiagnostics().getSuppressSystemWarnings() &&
2061  return;
2062 
2063  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2064  << New->getDeclName();
2065  Diag(Old->getLocation(), diag::note_previous_definition);
2066 }
2067 
2068 /// DeclhasAttr - returns true if decl Declaration already has the target
2069 /// attribute.
2070 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2071  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2072  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2073  for (const auto *i : D->attrs())
2074  if (i->getKind() == A->getKind()) {
2075  if (Ann) {
2076  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2077  return true;
2078  continue;
2079  }
2080  // FIXME: Don't hardcode this check
2081  if (OA && isa<OwnershipAttr>(i))
2082  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2083  return true;
2084  }
2085 
2086  return false;
2087 }
2088 
2090  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2091  return VD->isThisDeclarationADefinition();
2092  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2093  return TD->isCompleteDefinition() || TD->isBeingDefined();
2094  return true;
2095 }
2096 
2097 /// Merge alignment attributes from \p Old to \p New, taking into account the
2098 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2099 ///
2100 /// \return \c true if any attributes were added to \p New.
2101 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2102  // Look for alignas attributes on Old, and pick out whichever attribute
2103  // specifies the strictest alignment requirement.
2104  AlignedAttr *OldAlignasAttr = nullptr;
2105  AlignedAttr *OldStrictestAlignAttr = nullptr;
2106  unsigned OldAlign = 0;
2107  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2108  // FIXME: We have no way of representing inherited dependent alignments
2109  // in a case like:
2110  // template<int A, int B> struct alignas(A) X;
2111  // template<int A, int B> struct alignas(B) X {};
2112  // For now, we just ignore any alignas attributes which are not on the
2113  // definition in such a case.
2114  if (I->isAlignmentDependent())
2115  return false;
2116 
2117  if (I->isAlignas())
2118  OldAlignasAttr = I;
2119 
2120  unsigned Align = I->getAlignment(S.Context);
2121  if (Align > OldAlign) {
2122  OldAlign = Align;
2123  OldStrictestAlignAttr = I;
2124  }
2125  }
2126 
2127  // Look for alignas attributes on New.
2128  AlignedAttr *NewAlignasAttr = nullptr;
2129  unsigned NewAlign = 0;
2130  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2131  if (I->isAlignmentDependent())
2132  return false;
2133 
2134  if (I->isAlignas())
2135  NewAlignasAttr = I;
2136 
2137  unsigned Align = I->getAlignment(S.Context);
2138  if (Align > NewAlign)
2139  NewAlign = Align;
2140  }
2141 
2142  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2143  // Both declarations have 'alignas' attributes. We require them to match.
2144  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2145  // fall short. (If two declarations both have alignas, they must both match
2146  // every definition, and so must match each other if there is a definition.)
2147 
2148  // If either declaration only contains 'alignas(0)' specifiers, then it
2149  // specifies the natural alignment for the type.
2150  if (OldAlign == 0 || NewAlign == 0) {
2151  QualType Ty;
2152  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2153  Ty = VD->getType();
2154  else
2155  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2156 
2157  if (OldAlign == 0)
2158  OldAlign = S.Context.getTypeAlign(Ty);
2159  if (NewAlign == 0)
2160  NewAlign = S.Context.getTypeAlign(Ty);
2161  }
2162 
2163  if (OldAlign != NewAlign) {
2164  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2165  << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2166  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2167  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2168  }
2169  }
2170 
2171  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2172  // C++11 [dcl.align]p6:
2173  // if any declaration of an entity has an alignment-specifier,
2174  // every defining declaration of that entity shall specify an
2175  // equivalent alignment.
2176  // C11 6.7.5/7:
2177  // If the definition of an object does not have an alignment
2178  // specifier, any other declaration of that object shall also
2179  // have no alignment specifier.
2180  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2181  << OldAlignasAttr;
2182  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2183  << OldAlignasAttr;
2184  }
2185 
2186  bool AnyAdded = false;
2187 
2188  // Ensure we have an attribute representing the strictest alignment.
2189  if (OldAlign > NewAlign) {
2190  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2191  Clone->setInherited(true);
2192  New->addAttr(Clone);
2193  AnyAdded = true;
2194  }
2195 
2196  // Ensure we have an alignas attribute if the old declaration had one.
2197  if (OldAlignasAttr && !NewAlignasAttr &&
2198  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2199  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2200  Clone->setInherited(true);
2201  New->addAttr(Clone);
2202  AnyAdded = true;
2203  }
2204 
2205  return AnyAdded;
2206 }
2207 
2209  const InheritableAttr *Attr, bool Override) {
2210  InheritableAttr *NewAttr = nullptr;
2211  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2212  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2213  NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2214  AA->getIntroduced(), AA->getDeprecated(),
2215  AA->getObsoleted(), AA->getUnavailable(),
2216  AA->getMessage(), Override,
2217  AttrSpellingListIndex);
2218  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2219  NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2220  AttrSpellingListIndex);
2221  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2222  NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2223  AttrSpellingListIndex);
2224  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2225  NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2226  AttrSpellingListIndex);
2227  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2228  NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2229  AttrSpellingListIndex);
2230  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2231  NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2232  FA->getFormatIdx(), FA->getFirstArg(),
2233  AttrSpellingListIndex);
2234  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2235  NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2236  AttrSpellingListIndex);
2237  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2238  NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2239  AttrSpellingListIndex,
2240  IA->getSemanticSpelling());
2241  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2242  NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2243  &S.Context.Idents.get(AA->getSpelling()),
2244  AttrSpellingListIndex);
2245  else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2246  NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2247  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2248  NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2249  else if (isa<AlignedAttr>(Attr))
2250  // AlignedAttrs are handled separately, because we need to handle all
2251  // such attributes on a declaration at the same time.
2252  NewAttr = nullptr;
2253  else if (isa<DeprecatedAttr>(Attr) && Override)
2254  NewAttr = nullptr;
2255  else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2256  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2257 
2258  if (NewAttr) {
2259  NewAttr->setInherited(true);
2260  D->addAttr(NewAttr);
2261  return true;
2262  }
2263 
2264  return false;
2265 }
2266 
2267 static const Decl *getDefinition(const Decl *D) {
2268  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2269  return TD->getDefinition();
2270  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2271  const VarDecl *Def = VD->getDefinition();
2272  if (Def)
2273  return Def;
2274  return VD->getActingDefinition();
2275  }
2276  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2277  const FunctionDecl* Def;
2278  if (FD->isDefined(Def))
2279  return Def;
2280  }
2281  return nullptr;
2282 }
2283 
2284 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2285  for (const auto *Attribute : D->attrs())
2286  if (Attribute->getKind() == Kind)
2287  return true;
2288  return false;
2289 }
2290 
2291 /// checkNewAttributesAfterDef - If we already have a definition, check that
2292 /// there are no new attributes in this declaration.
2293 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2294  if (!New->hasAttrs())
2295  return;
2296 
2297  const Decl *Def = getDefinition(Old);
2298  if (!Def || Def == New)
2299  return;
2300 
2301  AttrVec &NewAttributes = New->getAttrs();
2302  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2303  const Attr *NewAttribute = NewAttributes[I];
2304 
2305  if (isa<AliasAttr>(NewAttribute)) {
2306  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2307  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2308  else {
2309  VarDecl *VD = cast<VarDecl>(New);
2310  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2312  ? diag::err_alias_after_tentative
2313  : diag::err_redefinition;
2314  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2315  S.Diag(Def->getLocation(), diag::note_previous_definition);
2316  VD->setInvalidDecl();
2317  }
2318  ++I;
2319  continue;
2320  }
2321 
2322  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2323  // Tentative definitions are only interesting for the alias check above.
2324  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2325  ++I;
2326  continue;
2327  }
2328  }
2329 
2330  if (hasAttribute(Def, NewAttribute->getKind())) {
2331  ++I;
2332  continue; // regular attr merging will take care of validating this.
2333  }
2334 
2335  if (isa<C11NoReturnAttr>(NewAttribute)) {
2336  // C's _Noreturn is allowed to be added to a function after it is defined.
2337  ++I;
2338  continue;
2339  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2340  if (AA->isAlignas()) {
2341  // C++11 [dcl.align]p6:
2342  // if any declaration of an entity has an alignment-specifier,
2343  // every defining declaration of that entity shall specify an
2344  // equivalent alignment.
2345  // C11 6.7.5/7:
2346  // If the definition of an object does not have an alignment
2347  // specifier, any other declaration of that object shall also
2348  // have no alignment specifier.
2349  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2350  << AA;
2351  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2352  << AA;
2353  NewAttributes.erase(NewAttributes.begin() + I);
2354  --E;
2355  continue;
2356  }
2357  }
2358 
2359  S.Diag(NewAttribute->getLocation(),
2360  diag::warn_attribute_precede_definition);
2361  S.Diag(Def->getLocation(), diag::note_previous_definition);
2362  NewAttributes.erase(NewAttributes.begin() + I);
2363  --E;
2364  }
2365 }
2366 
2367 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2369  AvailabilityMergeKind AMK) {
2370  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2371  UsedAttr *NewAttr = OldAttr->clone(Context);
2372  NewAttr->setInherited(true);
2373  New->addAttr(NewAttr);
2374  }
2375 
2376  if (!Old->hasAttrs() && !New->hasAttrs())
2377  return;
2378 
2379  // attributes declared post-definition are currently ignored
2380  checkNewAttributesAfterDef(*this, New, Old);
2381 
2382  if (!Old->hasAttrs())
2383  return;
2384 
2385  bool foundAny = New->hasAttrs();
2386 
2387  // Ensure that any moving of objects within the allocated map is done before
2388  // we process them.
2389  if (!foundAny) New->setAttrs(AttrVec());
2390 
2391  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2392  bool Override = false;
2393  // Ignore deprecated/unavailable/availability attributes if requested.
2394  if (isa<DeprecatedAttr>(I) ||
2395  isa<UnavailableAttr>(I) ||
2396  isa<AvailabilityAttr>(I)) {
2397  switch (AMK) {
2398  case AMK_None:
2399  continue;
2400 
2401  case AMK_Redeclaration:
2402  break;
2403 
2404  case AMK_Override:
2405  Override = true;
2406  break;
2407  }
2408  }
2409 
2410  // Already handled.
2411  if (isa<UsedAttr>(I))
2412  continue;
2413 
2414  if (mergeDeclAttribute(*this, New, I, Override))
2415  foundAny = true;
2416  }
2417 
2418  if (mergeAlignedAttrs(*this, New, Old))
2419  foundAny = true;
2420 
2421  if (!foundAny) New->dropAttrs();
2422 }
2423 
2424 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2425 /// to the new one.
2427  const ParmVarDecl *oldDecl,
2428  Sema &S) {
2429  // C++11 [dcl.attr.depend]p2:
2430  // The first declaration of a function shall specify the
2431  // carries_dependency attribute for its declarator-id if any declaration
2432  // of the function specifies the carries_dependency attribute.
2433  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2434  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2435  S.Diag(CDA->getLocation(),
2436  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2437  // Find the first declaration of the parameter.
2438  // FIXME: Should we build redeclaration chains for function parameters?
2439  const FunctionDecl *FirstFD =
2440  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2441  const ParmVarDecl *FirstVD =
2442  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2443  S.Diag(FirstVD->getLocation(),
2444  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2445  }
2446 
2447  if (!oldDecl->hasAttrs())
2448  return;
2449 
2450  bool foundAny = newDecl->hasAttrs();
2451 
2452  // Ensure that any moving of objects within the allocated map is
2453  // done before we process them.
2454  if (!foundAny) newDecl->setAttrs(AttrVec());
2455 
2456  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2457  if (!DeclHasAttr(newDecl, I)) {
2458  InheritableAttr *newAttr =
2459  cast<InheritableParamAttr>(I->clone(S.Context));
2460  newAttr->setInherited(true);
2461  newDecl->addAttr(newAttr);
2462  foundAny = true;
2463  }
2464  }
2465 
2466  if (!foundAny) newDecl->dropAttrs();
2467 }
2468 
2469 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2470  const ParmVarDecl *OldParam,
2471  Sema &S) {
2472  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2473  if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2474  if (*Oldnullability != *Newnullability) {
2475  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2477  *Newnullability,
2479  != 0))
2481  *Oldnullability,
2483  != 0));
2484  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2485  }
2486  } else {
2487  QualType NewT = NewParam->getType();
2488  NewT = S.Context.getAttributedType(
2489  AttributedType::getNullabilityAttrKind(*Oldnullability),
2490  NewT, NewT);
2491  NewParam->setType(NewT);
2492  }
2493  }
2494 }
2495 
2496 namespace {
2497 
2498 /// Used in MergeFunctionDecl to keep track of function parameters in
2499 /// C.
2500 struct GNUCompatibleParamWarning {
2501  ParmVarDecl *OldParm;
2502  ParmVarDecl *NewParm;
2503  QualType PromotedType;
2504 };
2505 
2506 }
2507 
2508 /// getSpecialMember - get the special member enum for a method.
2510  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2511  if (Ctor->isDefaultConstructor())
2513 
2514  if (Ctor->isCopyConstructor())
2515  return Sema::CXXCopyConstructor;
2516 
2517  if (Ctor->isMoveConstructor())
2518  return Sema::CXXMoveConstructor;
2519  } else if (isa<CXXDestructorDecl>(MD)) {
2520  return Sema::CXXDestructor;
2521  } else if (MD->isCopyAssignmentOperator()) {
2522  return Sema::CXXCopyAssignment;
2523  } else if (MD->isMoveAssignmentOperator()) {
2524  return Sema::CXXMoveAssignment;
2525  }
2526 
2527  return Sema::CXXInvalid;
2528 }
2529 
2530 // Determine whether the previous declaration was a definition, implicit
2531 // declaration, or a declaration.
2532 template <typename T>
2533 static std::pair<diag::kind, SourceLocation>
2534 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2535  diag::kind PrevDiag;
2536  SourceLocation OldLocation = Old->getLocation();
2537  if (Old->isThisDeclarationADefinition())
2538  PrevDiag = diag::note_previous_definition;
2539  else if (Old->isImplicit()) {
2540  PrevDiag = diag::note_previous_implicit_declaration;
2541  if (OldLocation.isInvalid())
2542  OldLocation = New->getLocation();
2543  } else
2544  PrevDiag = diag::note_previous_declaration;
2545  return std::make_pair(PrevDiag, OldLocation);
2546 }
2547 
2548 /// canRedefineFunction - checks if a function can be redefined. Currently,
2549 /// only extern inline functions can be redefined, and even then only in
2550 /// GNU89 mode.
2551 static bool canRedefineFunction(const FunctionDecl *FD,
2552  const LangOptions& LangOpts) {
2553  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2554  !LangOpts.CPlusPlus &&
2555  FD->isInlineSpecified() &&
2556  FD->getStorageClass() == SC_Extern);
2557 }
2558 
2560  const AttributedType *AT = T->getAs<AttributedType>();
2561  while (AT && !AT->isCallingConv())
2562  AT = AT->getModifiedType()->getAs<AttributedType>();
2563  return AT;
2564 }
2565 
2566 template <typename T>
2567 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2568  const DeclContext *DC = Old->getDeclContext();
2569  if (DC->isRecord())
2570  return false;
2571 
2572  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2573  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2574  return true;
2575  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2576  return true;
2577  return false;
2578 }
2579 
2580 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2581 static bool isExternC(VarTemplateDecl *) { return false; }
2582 
2583 /// \brief Check whether a redeclaration of an entity introduced by a
2584 /// using-declaration is valid, given that we know it's not an overload
2585 /// (nor a hidden tag declaration).
2586 template<typename ExpectedDecl>
2588  ExpectedDecl *New) {
2589  // C++11 [basic.scope.declarative]p4:
2590  // Given a set of declarations in a single declarative region, each of
2591  // which specifies the same unqualified name,
2592  // -- they shall all refer to the same entity, or all refer to functions
2593  // and function templates; or
2594  // -- exactly one declaration shall declare a class name or enumeration
2595  // name that is not a typedef name and the other declarations shall all
2596  // refer to the same variable or enumerator, or all refer to functions
2597  // and function templates; in this case the class name or enumeration
2598  // name is hidden (3.3.10).
2599 
2600  // C++11 [namespace.udecl]p14:
2601  // If a function declaration in namespace scope or block scope has the
2602  // same name and the same parameter-type-list as a function introduced
2603  // by a using-declaration, and the declarations do not declare the same
2604  // function, the program is ill-formed.
2605 
2606  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2607  if (Old &&
2608  !Old->getDeclContext()->getRedeclContext()->Equals(
2609  New->getDeclContext()->getRedeclContext()) &&
2610  !(isExternC(Old) && isExternC(New)))
2611  Old = nullptr;
2612 
2613  if (!Old) {
2614  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2615  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2616  S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2617  return true;
2618  }
2619  return false;
2620 }
2621 
2622 /// MergeFunctionDecl - We just parsed a function 'New' from
2623 /// declarator D which has the same name and scope as a previous
2624 /// declaration 'Old'. Figure out how to resolve this situation,
2625 /// merging decls or emitting diagnostics as appropriate.
2626 ///
2627 /// In C++, New and Old must be declarations that are not
2628 /// overloaded. Use IsOverload to determine whether New and Old are
2629 /// overloaded, and to select the Old declaration that New should be
2630 /// merged with.
2631 ///
2632 /// Returns true if there was an error, false otherwise.
2634  Scope *S, bool MergeTypeWithOld) {
2635  // Verify the old decl was also a function.
2636  FunctionDecl *Old = OldD->getAsFunction();
2637  if (!Old) {
2638  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2639  if (New->getFriendObjectKind()) {
2640  Diag(New->getLocation(), diag::err_using_decl_friend);
2641  Diag(Shadow->getTargetDecl()->getLocation(),
2642  diag::note_using_decl_target);
2643  Diag(Shadow->getUsingDecl()->getLocation(),
2644  diag::note_using_decl) << 0;
2645  return true;
2646  }
2647 
2648  // Check whether the two declarations might declare the same function.
2649  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2650  return true;
2651  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2652  } else {
2653  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2654  << New->getDeclName();
2655  Diag(OldD->getLocation(), diag::note_previous_definition);
2656  return true;
2657  }
2658  }
2659 
2660  // If the old declaration is invalid, just give up here.
2661  if (Old->isInvalidDecl())
2662  return true;
2663 
2664  diag::kind PrevDiag;
2665  SourceLocation OldLocation;
2666  std::tie(PrevDiag, OldLocation) =
2668 
2669  // Don't complain about this if we're in GNU89 mode and the old function
2670  // is an extern inline function.
2671  // Don't complain about specializations. They are not supposed to have
2672  // storage classes.
2673  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2674  New->getStorageClass() == SC_Static &&
2675  Old->hasExternalFormalLinkage() &&
2677  !canRedefineFunction(Old, getLangOpts())) {
2678  if (getLangOpts().MicrosoftExt) {
2679  Diag(New->getLocation(), diag::ext_static_non_static) << New;
2680  Diag(OldLocation, PrevDiag);
2681  } else {
2682  Diag(New->getLocation(), diag::err_static_non_static) << New;
2683  Diag(OldLocation, PrevDiag);
2684  return true;
2685  }
2686  }
2687 
2688 
2689  // If a function is first declared with a calling convention, but is later
2690  // declared or defined without one, all following decls assume the calling
2691  // convention of the first.
2692  //
2693  // It's OK if a function is first declared without a calling convention,
2694  // but is later declared or defined with the default calling convention.
2695  //
2696  // To test if either decl has an explicit calling convention, we look for
2697  // AttributedType sugar nodes on the type as written. If they are missing or
2698  // were canonicalized away, we assume the calling convention was implicit.
2699  //
2700  // Note also that we DO NOT return at this point, because we still have
2701  // other tests to run.
2702  QualType OldQType = Context.getCanonicalType(Old->getType());
2703  QualType NewQType = Context.getCanonicalType(New->getType());
2704  const FunctionType *OldType = cast<FunctionType>(OldQType);
2705  const FunctionType *NewType = cast<FunctionType>(NewQType);
2706  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2707  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2708  bool RequiresAdjustment = false;
2709 
2710  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2711  FunctionDecl *First = Old->getFirstDecl();
2712  const FunctionType *FT =
2714  FunctionType::ExtInfo FI = FT->getExtInfo();
2715  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2716  if (!NewCCExplicit) {
2717  // Inherit the CC from the previous declaration if it was specified
2718  // there but not here.
2719  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2720  RequiresAdjustment = true;
2721  } else {
2722  // Calling conventions aren't compatible, so complain.
2723  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2724  Diag(New->getLocation(), diag::err_cconv_change)
2725  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2726  << !FirstCCExplicit
2727  << (!FirstCCExplicit ? "" :
2728  FunctionType::getNameForCallConv(FI.getCC()));
2729 
2730  // Put the note on the first decl, since it is the one that matters.
2731  Diag(First->getLocation(), diag::note_previous_declaration);
2732  return true;
2733  }
2734  }
2735 
2736  // FIXME: diagnose the other way around?
2737  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2738  NewTypeInfo = NewTypeInfo.withNoReturn(true);
2739  RequiresAdjustment = true;
2740  }
2741 
2742  // Merge regparm attribute.
2743  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2744  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2745  if (NewTypeInfo.getHasRegParm()) {
2746  Diag(New->getLocation(), diag::err_regparm_mismatch)
2747  << NewType->getRegParmType()
2748  << OldType->getRegParmType();
2749  Diag(OldLocation, diag::note_previous_declaration);
2750  return true;
2751  }
2752 
2753  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2754  RequiresAdjustment = true;
2755  }
2756 
2757  // Merge ns_returns_retained attribute.
2758  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2759  if (NewTypeInfo.getProducesResult()) {
2760  Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2761  Diag(OldLocation, diag::note_previous_declaration);
2762  return true;
2763  }
2764 
2765  NewTypeInfo = NewTypeInfo.withProducesResult(true);
2766  RequiresAdjustment = true;
2767  }
2768 
2769  if (RequiresAdjustment) {
2770  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2771  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2772  New->setType(QualType(AdjustedType, 0));
2773  NewQType = Context.getCanonicalType(New->getType());
2774  NewType = cast<FunctionType>(NewQType);
2775  }
2776 
2777  // If this redeclaration makes the function inline, we may need to add it to
2778  // UndefinedButUsed.
2779  if (!Old->isInlined() && New->isInlined() &&
2780  !New->hasAttr<GNUInlineAttr>() &&
2781  !getLangOpts().GNUInline &&
2782  Old->isUsed(false) &&
2783  !Old->isDefined() && !New->isThisDeclarationADefinition())
2784  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2785  SourceLocation()));
2786 
2787  // If this redeclaration makes it newly gnu_inline, we don't want to warn
2788  // about it.
2789  if (New->hasAttr<GNUInlineAttr>() &&
2790  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2791  UndefinedButUsed.erase(Old->getCanonicalDecl());
2792  }
2793 
2794  if (getLangOpts().CPlusPlus) {
2795  // (C++98 13.1p2):
2796  // Certain function declarations cannot be overloaded:
2797  // -- Function declarations that differ only in the return type
2798  // cannot be overloaded.
2799 
2800  // Go back to the type source info to compare the declared return types,
2801  // per C++1y [dcl.type.auto]p13:
2802  // Redeclarations or specializations of a function or function template
2803  // with a declared return type that uses a placeholder type shall also
2804  // use that placeholder, not a deduced type.
2805  QualType OldDeclaredReturnType =
2806  (Old->getTypeSourceInfo()
2808  : OldType)->getReturnType();
2809  QualType NewDeclaredReturnType =
2810  (New->getTypeSourceInfo()
2812  : NewType)->getReturnType();
2813  QualType ResQT;
2814  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2815  !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2816  New->isLocalExternDecl())) {
2817  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2818  OldDeclaredReturnType->isObjCObjectPointerType())
2819  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2820  if (ResQT.isNull()) {
2821  if (New->isCXXClassMember() && New->isOutOfLine())
2822  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2823  << New << New->getReturnTypeSourceRange();
2824  else
2825  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2826  << New->getReturnTypeSourceRange();
2827  Diag(OldLocation, PrevDiag) << Old << Old->getType()
2828  << Old->getReturnTypeSourceRange();
2829  return true;
2830  }
2831  else
2832  NewQType = ResQT;
2833  }
2834 
2835  QualType OldReturnType = OldType->getReturnType();
2836  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2837  if (OldReturnType != NewReturnType) {
2838  // If this function has a deduced return type and has already been
2839  // defined, copy the deduced value from the old declaration.
2840  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2841  if (OldAT && OldAT->isDeduced()) {
2842  New->setType(
2843  SubstAutoType(New->getType(),
2845  : OldAT->getDeducedType()));
2846  NewQType = Context.getCanonicalType(
2847  SubstAutoType(NewQType,
2849  : OldAT->getDeducedType()));
2850  }
2851  }
2852 
2853  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2854  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2855  if (OldMethod && NewMethod) {
2856  // Preserve triviality.
2857  NewMethod->setTrivial(OldMethod->isTrivial());
2858 
2859  // MSVC allows explicit template specialization at class scope:
2860  // 2 CXXMethodDecls referring to the same function will be injected.
2861  // We don't want a redeclaration error.
2862  bool IsClassScopeExplicitSpecialization =
2863  OldMethod->isFunctionTemplateSpecialization() &&
2864  NewMethod->isFunctionTemplateSpecialization();
2865  bool isFriend = NewMethod->getFriendObjectKind();
2866 
2867  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2868  !IsClassScopeExplicitSpecialization) {
2869  // -- Member function declarations with the same name and the
2870  // same parameter types cannot be overloaded if any of them
2871  // is a static member function declaration.
2872  if (OldMethod->isStatic() != NewMethod->isStatic()) {
2873  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2874  Diag(OldLocation, PrevDiag) << Old << Old->getType();
2875  return true;
2876  }
2877 
2878  // C++ [class.mem]p1:
2879  // [...] A member shall not be declared twice in the
2880  // member-specification, except that a nested class or member
2881  // class template can be declared and then later defined.
2882  if (ActiveTemplateInstantiations.empty()) {
2883  unsigned NewDiag;
2884  if (isa<CXXConstructorDecl>(OldMethod))
2885  NewDiag = diag::err_constructor_redeclared;
2886  else if (isa<CXXDestructorDecl>(NewMethod))
2887  NewDiag = diag::err_destructor_redeclared;
2888  else if (isa<CXXConversionDecl>(NewMethod))
2889  NewDiag = diag::err_conv_function_redeclared;
2890  else
2891  NewDiag = diag::err_member_redeclared;
2892 
2893  Diag(New->getLocation(), NewDiag);
2894  } else {
2895  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2896  << New << New->getType();
2897  }
2898  Diag(OldLocation, PrevDiag) << Old << Old->getType();
2899  return true;
2900 
2901  // Complain if this is an explicit declaration of a special
2902  // member that was initially declared implicitly.
2903  //
2904  // As an exception, it's okay to befriend such methods in order
2905  // to permit the implicit constructor/destructor/operator calls.
2906  } else if (OldMethod->isImplicit()) {
2907  if (isFriend) {
2908  NewMethod->setImplicit();
2909  } else {
2910  Diag(NewMethod->getLocation(),
2911  diag::err_definition_of_implicitly_declared_member)
2912  << New << getSpecialMember(OldMethod);
2913  return true;
2914  }
2915  } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2916  Diag(NewMethod->getLocation(),
2917  diag::err_definition_of_explicitly_defaulted_member)
2918  << getSpecialMember(OldMethod);
2919  return true;
2920  }
2921  }
2922 
2923  // C++11 [dcl.attr.noreturn]p1:
2924  // The first declaration of a function shall specify the noreturn
2925  // attribute if any declaration of that function specifies the noreturn
2926  // attribute.
2927  const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2928  if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2929  Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2930  Diag(Old->getFirstDecl()->getLocation(),
2931  diag::note_noreturn_missing_first_decl);
2932  }
2933 
2934  // C++11 [dcl.attr.depend]p2:
2935  // The first declaration of a function shall specify the
2936  // carries_dependency attribute for its declarator-id if any declaration
2937  // of the function specifies the carries_dependency attribute.
2938  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2939  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2940  Diag(CDA->getLocation(),
2941  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2942  Diag(Old->getFirstDecl()->getLocation(),
2943  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2944  }
2945 
2946  // (C++98 8.3.5p3):
2947  // All declarations for a function shall agree exactly in both the
2948  // return type and the parameter-type-list.
2949  // We also want to respect all the extended bits except noreturn.
2950 
2951  // noreturn should now match unless the old type info didn't have it.
2952  QualType OldQTypeForComparison = OldQType;
2953  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2954  assert(OldQType == QualType(OldType, 0));
2955  const FunctionType *OldTypeForComparison
2956  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2957  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2958  assert(OldQTypeForComparison.isCanonical());
2959  }
2960 
2961  if (haveIncompatibleLanguageLinkages(Old, New)) {
2962  // As a special case, retain the language linkage from previous
2963  // declarations of a friend function as an extension.
2964  //
2965  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2966  // and is useful because there's otherwise no way to specify language
2967  // linkage within class scope.
2968  //
2969  // Check cautiously as the friend object kind isn't yet complete.
2970  if (New->getFriendObjectKind() != Decl::FOK_None) {
2971  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2972  Diag(OldLocation, PrevDiag);
2973  } else {
2974  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2975  Diag(OldLocation, PrevDiag);
2976  return true;
2977  }
2978  }
2979 
2980  if (OldQTypeForComparison == NewQType)
2981  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2982 
2983  if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2984  New->isLocalExternDecl()) {
2985  // It's OK if we couldn't merge types for a local function declaraton
2986  // if either the old or new type is dependent. We'll merge the types
2987  // when we instantiate the function.
2988  return false;
2989  }
2990 
2991  // Fall through for conflicting redeclarations and redefinitions.
2992  }
2993 
2994  // C: Function types need to be compatible, not identical. This handles
2995  // duplicate function decls like "void f(int); void f(enum X);" properly.
2996  if (!getLangOpts().CPlusPlus &&
2997  Context.typesAreCompatible(OldQType, NewQType)) {
2998  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2999  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3000  const FunctionProtoType *OldProto = nullptr;
3001  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3002  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3003  // The old declaration provided a function prototype, but the
3004  // new declaration does not. Merge in the prototype.
3005  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3006  SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3007  NewQType =
3008  Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3009  OldProto->getExtProtoInfo());
3010  New->setType(NewQType);
3011  New->setHasInheritedPrototype();
3012 
3013  // Synthesize parameters with the same types.
3015  for (const auto &ParamType : OldProto->param_types()) {
3017  SourceLocation(), nullptr,
3018  ParamType, /*TInfo=*/nullptr,
3019  SC_None, nullptr);
3020  Param->setScopeInfo(0, Params.size());
3021  Param->setImplicit();
3022  Params.push_back(Param);
3023  }
3024 
3025  New->setParams(Params);
3026  }
3027 
3028  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3029  }
3030 
3031  // GNU C permits a K&R definition to follow a prototype declaration
3032  // if the declared types of the parameters in the K&R definition
3033  // match the types in the prototype declaration, even when the
3034  // promoted types of the parameters from the K&R definition differ
3035  // from the types in the prototype. GCC then keeps the types from
3036  // the prototype.
3037  //
3038  // If a variadic prototype is followed by a non-variadic K&R definition,
3039  // the K&R definition becomes variadic. This is sort of an edge case, but
3040  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3041  // C99 6.9.1p8.
3042  if (!getLangOpts().CPlusPlus &&
3043  Old->hasPrototype() && !New->hasPrototype() &&
3044  New->getType()->getAs<FunctionProtoType>() &&
3045  Old->getNumParams() == New->getNumParams()) {
3046  SmallVector<QualType, 16> ArgTypes;
3048  const FunctionProtoType *OldProto
3049  = Old->getType()->getAs<FunctionProtoType>();
3050  const FunctionProtoType *NewProto
3051  = New->getType()->getAs<FunctionProtoType>();
3052 
3053  // Determine whether this is the GNU C extension.
3054  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3055  NewProto->getReturnType());
3056  bool LooseCompatible = !MergedReturn.isNull();
3057  for (unsigned Idx = 0, End = Old->getNumParams();
3058  LooseCompatible && Idx != End; ++Idx) {
3059  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3060  ParmVarDecl *NewParm = New->getParamDecl(Idx);
3061  if (Context.typesAreCompatible(OldParm->getType(),
3062  NewProto->getParamType(Idx))) {
3063  ArgTypes.push_back(NewParm->getType());
3064  } else if (Context.typesAreCompatible(OldParm->getType(),
3065  NewParm->getType(),
3066  /*CompareUnqualified=*/true)) {
3067  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3068  NewProto->getParamType(Idx) };
3069  Warnings.push_back(Warn);
3070  ArgTypes.push_back(NewParm->getType());
3071  } else
3072  LooseCompatible = false;
3073  }
3074 
3075  if (LooseCompatible) {
3076  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3077  Diag(Warnings[Warn].NewParm->getLocation(),
3078  diag::ext_param_promoted_not_compatible_with_prototype)
3079  << Warnings[Warn].PromotedType
3080  << Warnings[Warn].OldParm->getType();
3081  if (Warnings[Warn].OldParm->getLocation().isValid())
3082  Diag(Warnings[Warn].OldParm->getLocation(),
3083  diag::note_previous_declaration);
3084  }
3085 
3086  if (MergeTypeWithOld)
3087  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3088  OldProto->getExtProtoInfo()));
3089  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3090  }
3091 
3092  // Fall through to diagnose conflicting types.
3093  }
3094 
3095  // A function that has already been declared has been redeclared or
3096  // defined with a different type; show an appropriate diagnostic.
3097 
3098  // If the previous declaration was an implicitly-generated builtin
3099  // declaration, then at the very least we should use a specialized note.
3100  unsigned BuiltinID;
3101  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3102  // If it's actually a library-defined builtin function like 'malloc'
3103  // or 'printf', just warn about the incompatible redeclaration.
3104  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3105  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3106  Diag(OldLocation, diag::note_previous_builtin_declaration)
3107  << Old << Old->getType();
3108 
3109  // If this is a global redeclaration, just forget hereafter
3110  // about the "builtin-ness" of the function.
3111  //
3112  // Doing this for local extern declarations is problematic. If
3113  // the builtin declaration remains visible, a second invalid
3114  // local declaration will produce a hard error; if it doesn't
3115  // remain visible, a single bogus local redeclaration (which is
3116  // actually only a warning) could break all the downstream code.
3119 
3120  return false;
3121  }
3122 
3123  PrevDiag = diag::note_previous_builtin_declaration;
3124  }
3125 
3126  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3127  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3128  return true;
3129 }
3130 
3131 /// \brief Completes the merge of two function declarations that are
3132 /// known to be compatible.
3133 ///
3134 /// This routine handles the merging of attributes and other
3135 /// properties of function declarations from the old declaration to
3136 /// the new declaration, once we know that New is in fact a
3137 /// redeclaration of Old.
3138 ///
3139 /// \returns false
3141  Scope *S, bool MergeTypeWithOld) {
3142  // Merge the attributes
3143  mergeDeclAttributes(New, Old);
3144 
3145  // Merge "pure" flag.
3146  if (Old->isPure())
3147  New->setPure();
3148 
3149  // Merge "used" flag.
3150  if (Old->getMostRecentDecl()->isUsed(false))
3151  New->setIsUsed();
3152 
3153  // Merge attributes from the parameters. These can mismatch with K&R
3154  // declarations.
3155  if (New->getNumParams() == Old->getNumParams())
3156  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3157  ParmVarDecl *NewParam = New->getParamDecl(i);
3158  ParmVarDecl *OldParam = Old->getParamDecl(i);
3159  mergeParamDeclAttributes(NewParam, OldParam, *this);
3160  mergeParamDeclTypes(NewParam, OldParam, *this);
3161  }
3162 
3163  if (getLangOpts().CPlusPlus)
3164  return MergeCXXFunctionDecl(New, Old, S);
3165 
3166  // Merge the function types so the we get the composite types for the return
3167  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3168  // was visible.
3169  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3170  if (!Merged.isNull() && MergeTypeWithOld)
3171  New->setType(Merged);
3172 
3173  return false;
3174 }
3175 
3176 
3178  ObjCMethodDecl *oldMethod) {
3179 
3180  // Merge the attributes, including deprecated/unavailable
3181  AvailabilityMergeKind MergeKind =
3182  isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3183  : AMK_Override;
3184  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3185 
3186  // Merge attributes from the parameters.
3188  oe = oldMethod->param_end();
3190  ni = newMethod->param_begin(), ne = newMethod->param_end();
3191  ni != ne && oi != oe; ++ni, ++oi)
3192  mergeParamDeclAttributes(*ni, *oi, *this);
3193 
3194  CheckObjCMethodOverride(newMethod, oldMethod);
3195 }
3196 
3197 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3198 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3199 /// emitting diagnostics as appropriate.
3200 ///
3201 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3202 /// to here in AddInitializerToDecl. We can't check them before the initializer
3203 /// is attached.
3205  bool MergeTypeWithOld) {
3206  if (New->isInvalidDecl() || Old->isInvalidDecl())
3207  return;
3208 
3209  QualType MergedT;
3210  if (getLangOpts().CPlusPlus) {
3211  if (New->getType()->isUndeducedType()) {
3212  // We don't know what the new type is until the initializer is attached.
3213  return;
3214  } else if (Context.hasSameType(New->getType(), Old->getType())) {
3215  // These could still be something that needs exception specs checked.
3216  return MergeVarDeclExceptionSpecs(New, Old);
3217  }
3218  // C++ [basic.link]p10:
3219  // [...] the types specified by all declarations referring to a given
3220  // object or function shall be identical, except that declarations for an
3221  // array object can specify array types that differ by the presence or
3222  // absence of a major array bound (8.3.4).
3223  else if (Old->getType()->isIncompleteArrayType() &&
3224  New->getType()->isArrayType()) {
3225  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3226  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3227  if (Context.hasSameType(OldArray->getElementType(),
3228  NewArray->getElementType()))
3229  MergedT = New->getType();
3230  } else if (Old->getType()->isArrayType() &&
3231  New->getType()->isIncompleteArrayType()) {
3232  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3233  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3234  if (Context.hasSameType(OldArray->getElementType(),
3235  NewArray->getElementType()))
3236  MergedT = Old->getType();
3237  } else if (New->getType()->isObjCObjectPointerType() &&
3238  Old->getType()->isObjCObjectPointerType()) {
3239  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3240  Old->getType());
3241  }
3242  } else {
3243  // C 6.2.7p2:
3244  // All declarations that refer to the same object or function shall have
3245  // compatible type.
3246  MergedT = Context.mergeTypes(New->getType(), Old->getType());
3247  }
3248  if (MergedT.isNull()) {
3249  // It's OK if we couldn't merge types if either type is dependent, for a
3250  // block-scope variable. In other cases (static data members of class
3251  // templates, variable templates, ...), we require the types to be
3252  // equivalent.
3253  // FIXME: The C++ standard doesn't say anything about this.
3254  if ((New->getType()->isDependentType() ||
3255  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3256  // If the old type was dependent, we can't merge with it, so the new type
3257  // becomes dependent for now. We'll reproduce the original type when we
3258  // instantiate the TypeSourceInfo for the variable.
3259  if (!New->getType()->isDependentType() && MergeTypeWithOld)
3260  New->setType(Context.DependentTy);
3261  return;
3262  }
3263 
3264  // FIXME: Even if this merging succeeds, some other non-visible declaration
3265  // of this variable might have an incompatible type. For instance:
3266  //
3267  // extern int arr[];
3268  // void f() { extern int arr[2]; }
3269  // void g() { extern int arr[3]; }
3270  //
3271  // Neither C nor C++ requires a diagnostic for this, but we should still try
3272  // to diagnose it.
3274  ? diag::err_redefinition_different_type
3275  : diag::err_redeclaration_different_type)
3276  << New->getDeclName() << New->getType() << Old->getType();
3277 
3278  diag::kind PrevDiag;
3279  SourceLocation OldLocation;
3280  std::tie(PrevDiag, OldLocation) =
3282  Diag(OldLocation, PrevDiag);
3283  return New->setInvalidDecl();
3284  }
3285 
3286  // Don't actually update the type on the new declaration if the old
3287  // declaration was an extern declaration in a different scope.
3288  if (MergeTypeWithOld)
3289  New->setType(MergedT);
3290 }
3291 
3292 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3294  // C11 6.2.7p4:
3295  // For an identifier with internal or external linkage declared
3296  // in a scope in which a prior declaration of that identifier is
3297  // visible, if the prior declaration specifies internal or
3298  // external linkage, the type of the identifier at the later
3299  // declaration becomes the composite type.
3300  //
3301  // If the variable isn't visible, we do not merge with its type.
3302  if (Previous.isShadowed())
3303  return false;
3304 
3305  if (S.getLangOpts().CPlusPlus) {
3306  // C++11 [dcl.array]p3:
3307  // If there is a preceding declaration of the entity in the same
3308  // scope in which the bound was specified, an omitted array bound
3309  // is taken to be the same as in that earlier declaration.
3310  return NewVD->isPreviousDeclInSameBlockScope() ||
3311  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3313  } else {
3314  // If the old declaration was function-local, don't merge with its
3315  // type unless we're in the same function.
3316  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3317  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3318  }
3319 }
3320 
3321 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3322 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3323 /// situation, merging decls or emitting diagnostics as appropriate.
3324 ///
3325 /// Tentative definition rules (C99 6.9.2p2) are checked by
3326 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3327 /// definitions here, since the initializer hasn't been attached.
3328 ///
3330  // If the new decl is already invalid, don't do any other checking.
3331  if (New->isInvalidDecl())
3332  return;
3333 
3334  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3335 
3336  // Verify the old decl was also a variable or variable template.
3337  VarDecl *Old = nullptr;
3338  VarTemplateDecl *OldTemplate = nullptr;
3339  if (Previous.isSingleResult()) {
3340  if (NewTemplate) {
3341  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3342  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3343 
3344  if (auto *Shadow =
3345  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3346  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3347  return New->setInvalidDecl();
3348  } else {
3349  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3350 
3351  if (auto *Shadow =
3352  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3353  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3354  return New->setInvalidDecl();
3355  }
3356  }
3357  if (!Old) {
3358  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3359  << New->getDeclName();
3360  Diag(Previous.getRepresentativeDecl()->getLocation(),
3361  diag::note_previous_definition);
3362  return New->setInvalidDecl();
3363  }
3364 
3365  if (!shouldLinkPossiblyHiddenDecl(Old, New))
3366  return;
3367 
3368  // Ensure the template parameters are compatible.
3369  if (NewTemplate &&
3370  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3371  OldTemplate->getTemplateParameters(),
3372  /*Complain=*/true, TPL_TemplateMatch))
3373  return;
3374 
3375  // C++ [class.mem]p1:
3376  // A member shall not be declared twice in the member-specification [...]
3377  //
3378  // Here, we need only consider static data members.
3379  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3380  Diag(New->getLocation(), diag::err_duplicate_member)
3381  << New->getIdentifier();
3382  Diag(Old->getLocation(), diag::note_previous_declaration);
3383  New->setInvalidDecl();
3384  }
3385 
3386  mergeDeclAttributes(New, Old);
3387  // Warn if an already-declared variable is made a weak_import in a subsequent
3388  // declaration
3389  if (New->hasAttr<WeakImportAttr>() &&
3390  Old->getStorageClass() == SC_None &&
3391  !Old->hasAttr<WeakImportAttr>()) {
3392  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3393  Diag(Old->getLocation(), diag::note_previous_definition);
3394  // Remove weak_import attribute on new declaration.
3395  New->dropAttr<WeakImportAttr>();
3396  }
3397 
3398  // Merge the types.
3399  VarDecl *MostRecent = Old->getMostRecentDecl();
3400  if (MostRecent != Old) {
3401  MergeVarDeclTypes(New, MostRecent,
3402  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3403  if (New->isInvalidDecl())
3404  return;
3405  }
3406 
3407  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3408  if (New->isInvalidDecl())
3409  return;
3410 
3411  diag::kind PrevDiag;
3412  SourceLocation OldLocation;
3413  std::tie(PrevDiag, OldLocation) =
3415 
3416  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3417  if (New->getStorageClass() == SC_Static &&
3418  !New->isStaticDataMember() &&
3419  Old->hasExternalFormalLinkage()) {
3420  if (getLangOpts().MicrosoftExt) {
3421  Diag(New->getLocation(), diag::ext_static_non_static)
3422  << New->getDeclName();
3423  Diag(OldLocation, PrevDiag);
3424  } else {
3425  Diag(New->getLocation(), diag::err_static_non_static)
3426  << New->getDeclName();
3427  Diag(OldLocation, PrevDiag);
3428  return New->setInvalidDecl();
3429  }
3430  }
3431  // C99 6.2.2p4:
3432  // For an identifier declared with the storage-class specifier
3433  // extern in a scope in which a prior declaration of that
3434  // identifier is visible,23) if the prior declaration specifies
3435  // internal or external linkage, the linkage of the identifier at
3436  // the later declaration is the same as the linkage specified at
3437  // the prior declaration. If no prior declaration is visible, or
3438  // if the prior declaration specifies no linkage, then the
3439  // identifier has external linkage.
3440  if (New->hasExternalStorage() && Old->hasLinkage())
3441  /* Okay */;
3442  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3443  !New->isStaticDataMember() &&
3445  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3446  Diag(OldLocation, PrevDiag);
3447  return New->setInvalidDecl();
3448  }
3449 
3450  // Check if extern is followed by non-extern and vice-versa.
3451  if (New->hasExternalStorage() &&
3452  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3453  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3454  Diag(OldLocation, PrevDiag);
3455  return New->setInvalidDecl();
3456  }
3457  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3458  !New->hasExternalStorage()) {
3459  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3460  Diag(OldLocation, PrevDiag);
3461  return New->setInvalidDecl();
3462  }
3463 
3464  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3465 
3466  // FIXME: The test for external storage here seems wrong? We still
3467  // need to check for mismatches.
3468  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3469  // Don't complain about out-of-line definitions of static members.
3470  !(Old->getLexicalDeclContext()->isRecord() &&
3471  !New->getLexicalDeclContext()->isRecord())) {
3472  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3473  Diag(OldLocation, PrevDiag);
3474  return New->setInvalidDecl();
3475  }
3476 
3477  if (New->getTLSKind() != Old->getTLSKind()) {
3478  if (!Old->getTLSKind()) {
3479  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3480  Diag(OldLocation, PrevDiag);
3481  } else if (!New->getTLSKind()) {
3482  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3483  Diag(OldLocation, PrevDiag);
3484  } else {
3485  // Do not allow redeclaration to change the variable between requiring
3486  // static and dynamic initialization.
3487  // FIXME: GCC allows this, but uses the TLS keyword on the first
3488  // declaration to determine the kind. Do we need to be compatible here?
3489  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3490  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3491  Diag(OldLocation, PrevDiag);
3492  }
3493  }
3494 
3495  // C++ doesn't have tentative definitions, so go right ahead and check here.
3496  VarDecl *Def;
3497  if (getLangOpts().CPlusPlus &&
3499  (Def = Old->getDefinition())) {
3500  NamedDecl *Hidden = nullptr;
3501  if (!hasVisibleDefinition(Def, &Hidden) &&
3502  (New->getFormalLinkage() == InternalLinkage ||
3503  New->getDescribedVarTemplate() ||
3505  New->getDeclContext()->isDependentContext())) {
3506  // The previous definition is hidden, and multiple definitions are
3507  // permitted (in separate TUs). Form another definition of it.
3508  } else {
3509  Diag(New->getLocation(), diag::err_redefinition) << New;
3510  Diag(Def->getLocation(), diag::note_previous_definition);
3511  New->setInvalidDecl();
3512  return;
3513  }
3514  }
3515 
3516  if (haveIncompatibleLanguageLinkages(Old, New)) {
3517  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3518  Diag(OldLocation, PrevDiag);
3519  New->setInvalidDecl();
3520  return;
3521  }
3522 
3523  // Merge "used" flag.
3524  if (Old->getMostRecentDecl()->isUsed(false))
3525  New->setIsUsed();
3526 
3527  // Keep a chain of previous declarations.
3528  New->setPreviousDecl(Old);
3529  if (NewTemplate)
3530  NewTemplate->setPreviousDecl(OldTemplate);
3531 
3532  // Inherit access appropriately.
3533  New->setAccess(Old->getAccess());
3534  if (NewTemplate)
3535  NewTemplate->setAccess(New->getAccess());
3536 }
3537 
3538 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3539 /// no declarator (e.g. "struct foo;") is parsed.
3541  DeclSpec &DS) {
3542  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3543 }
3544 
3545 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3546 // disambiguate entities defined in different scopes.
3547 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3548 // compatibility.
3549 // We will pick our mangling number depending on which version of MSVC is being
3550 // targeted.
3551 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3553  ? S->getMSCurManglingNumber()
3554  : S->getMSLastManglingNumber();
3555 }
3556 
3557 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3558  if (!Context.getLangOpts().CPlusPlus)
3559  return;
3560 
3561  if (isa<CXXRecordDecl>(Tag->getParent())) {
3562  // If this tag is the direct child of a class, number it if
3563  // it is anonymous.
3564  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3565  return;
3566  MangleNumberingContext &MCtx =
3569  Tag, MCtx.getManglingNumber(
3570  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3571  return;
3572  }
3573 
3574  // If this tag isn't a direct child of a class, number it if it is local.
3575  Decl *ManglingContextDecl;
3576  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3577  Tag->getDeclContext(), ManglingContextDecl)) {
3579  Tag, MCtx->getManglingNumber(
3580  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3581  }
3582 }
3583 
3585  TypedefNameDecl *NewTD) {
3586  // Do nothing if the tag is not anonymous or already has an
3587  // associated typedef (from an earlier typedef in this decl group).
3588  if (TagFromDeclSpec->getIdentifier())
3589  return;
3590  if (TagFromDeclSpec->getTypedefNameForAnonDecl())
3591  return;
3592 
3593  // A well-formed anonymous tag must always be a TUK_Definition.
3594  assert(TagFromDeclSpec->isThisDeclarationADefinition());
3595 
3596  // The type must match the tag exactly; no qualifiers allowed.
3597  if (!Context.hasSameType(NewTD->getUnderlyingType(),
3598  Context.getTagDeclType(TagFromDeclSpec)))
3599  return;
3600 
3601  // If we've already computed linkage for the anonymous tag, then
3602  // adding a typedef name for the anonymous decl can change that
3603  // linkage, which might be a serious problem. Diagnose this as
3604  // unsupported and ignore the typedef name. TODO: we should
3605  // pursue this as a language defect and establish a formal rule
3606  // for how to handle it.
3607  if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3608  Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3609 
3610  SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3611  tagLoc = getLocForEndOfToken(tagLoc);
3612 
3613  llvm::SmallString<40> textToInsert;
3614  textToInsert += ' ';
3615  textToInsert += NewTD->getIdentifier()->getName();
3616  Diag(tagLoc, diag::note_typedef_changes_linkage)
3617  << FixItHint::CreateInsertion(tagLoc, textToInsert);
3618  return;
3619  }
3620 
3621  // Otherwise, set this is the anon-decl typedef for the tag.
3622  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3623 }
3624 
3626  switch (T) {
3627  case DeclSpec::TST_class:
3628  return 0;
3629  case DeclSpec::TST_struct:
3630  return 1;
3632  return 2;
3633  case DeclSpec::TST_union:
3634  return 3;
3635  case DeclSpec::TST_enum:
3636  return 4;
3637  default:
3638  llvm_unreachable("unexpected type specifier");
3639  }
3640 }
3641 
3642 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3643 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3644 /// parameters to cope with template friend declarations.
3646  DeclSpec &DS,
3647  MultiTemplateParamsArg TemplateParams,
3648  bool IsExplicitInstantiation) {
3649  Decl *TagD = nullptr;
3650  TagDecl *Tag = nullptr;
3651  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3656  TagD = DS.getRepAsDecl();
3657 
3658  if (!TagD) // We probably had an error
3659  return nullptr;
3660 
3661  // Note that the above type specs guarantee that the
3662  // type rep is a Decl, whereas in many of the others
3663  // it's a Type.
3664  if (isa<TagDecl>(TagD))
3665  Tag = cast<TagDecl>(TagD);
3666  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3667  Tag = CTD->getTemplatedDecl();
3668  }
3669 
3670  if (Tag) {
3671  handleTagNumbering(Tag, S);
3672  Tag->setFreeStanding();
3673  if (Tag->isInvalidDecl())
3674  return Tag;
3675  }
3676 
3677  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3678  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3679  // or incomplete types shall not be restrict-qualified."
3680  if (TypeQuals & DeclSpec::TQ_restrict)
3681  Diag(DS.getRestrictSpecLoc(),
3682  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3683  << DS.getSourceRange();
3684  }
3685 
3686  if (DS.isConstexprSpecified()) {
3687  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3688  // and definitions of functions and variables.
3689  if (Tag)
3690  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3692  else
3693  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3694  // Don't emit warnings after this error.
3695  return TagD;
3696  }
3697 
3698  DiagnoseFunctionSpecifiers(DS);
3699 
3700  if (DS.isFriendSpecified()) {
3701  // If we're dealing with a decl but not a TagDecl, assume that
3702  // whatever routines created it handled the friendship aspect.
3703  if (TagD && !Tag)
3704  return nullptr;
3705  return ActOnFriendTypeDecl(S, DS, TemplateParams);
3706  }
3707 
3708  const CXXScopeSpec &SS = DS.getTypeSpecScope();
3709  bool IsExplicitSpecialization =
3710  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3711  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3712  !IsExplicitInstantiation && !IsExplicitSpecialization) {
3713  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3714  // nested-name-specifier unless it is an explicit instantiation
3715  // or an explicit specialization.
3716  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3717  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3719  return nullptr;
3720  }
3721 
3722  // Track whether this decl-specifier declares anything.
3723  bool DeclaresAnything = true;
3724 
3725  // Handle anonymous struct definitions.
3726  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3727  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3729  if (getLangOpts().CPlusPlus ||
3730  Record->getDeclContext()->isRecord())
3731  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3733 
3734  DeclaresAnything = false;
3735  }
3736  }
3737 
3738  // C11 6.7.2.1p2:
3739  // A struct-declaration that does not declare an anonymous structure or
3740  // anonymous union shall contain a struct-declarator-list.
3741  //
3742  // This rule also existed in C89 and C99; the grammar for struct-declaration
3743  // did not permit a struct-declaration without a struct-declarator-list.
3744  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3746  // Check for Microsoft C extension: anonymous struct/union member.
3747  // Handle 2 kinds of anonymous struct/union:
3748  // struct STRUCT;
3749  // union UNION;
3750  // and
3751  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3752  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3753  if ((Tag && Tag->getDeclName()) ||
3755  RecordDecl *Record = nullptr;
3756  if (Tag)
3757  Record = dyn_cast<RecordDecl>(Tag);
3758  else if (const RecordType *RT =
3760  Record = RT->getDecl();
3761  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3762  Record = UT->getDecl();
3763 
3764  if (Record && getLangOpts().MicrosoftExt) {
3765  Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3766  << Record->isUnion() << DS.getSourceRange();
3767  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3768  }
3769 
3770  DeclaresAnything = false;
3771  }
3772  }
3773 
3774  // Skip all the checks below if we have a type error.
3775  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3776  (TagD && TagD->isInvalidDecl()))
3777  return TagD;
3778 
3779  if (getLangOpts().CPlusPlus &&
3781  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3782  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3783  !Enum->getIdentifier() && !Enum->isInvalidDecl())
3784  DeclaresAnything = false;
3785 
3786  if (!DS.isMissingDeclaratorOk()) {
3787  // Customize diagnostic for a typedef missing a name.
3789  Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3790  << DS.getSourceRange();
3791  else
3792  DeclaresAnything = false;
3793  }
3794 
3795  if (DS.isModulePrivateSpecified() &&
3796  Tag && Tag->getDeclContext()->isFunctionOrMethod())
3797  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3798  << Tag->getTagKind()
3800 
3801  ActOnDocumentableDecl(TagD);
3802 
3803  // C 6.7/2:
3804  // A declaration [...] shall declare at least a declarator [...], a tag,
3805  // or the members of an enumeration.
3806  // C++ [dcl.dcl]p3:
3807  // [If there are no declarators], and except for the declaration of an
3808  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3809  // names into the program, or shall redeclare a name introduced by a
3810  // previous declaration.
3811  if (!DeclaresAnything) {
3812  // In C, we allow this as a (popular) extension / bug. Don't bother
3813  // producing further diagnostics for redundant qualifiers after this.
3814  Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3815  return TagD;
3816  }
3817 
3818  // C++ [dcl.stc]p1:
3819  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3820  // init-declarator-list of the declaration shall not be empty.
3821  // C++ [dcl.fct.spec]p1:
3822  // If a cv-qualifier appears in a decl-specifier-seq, the
3823  // init-declarator-list of the declaration shall not be empty.
3824  //
3825  // Spurious qualifiers here appear to be valid in C.
3826  unsigned DiagID = diag::warn_standalone_specifier;
3827  if (getLangOpts().CPlusPlus)
3828  DiagID = diag::ext_standalone_specifier;
3829 
3830  // Note that a linkage-specification sets a storage class, but
3831  // 'extern "C" struct foo;' is actually valid and not theoretically
3832  // useless.
3833  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3834  if (SCS == DeclSpec::SCS_mutable)
3835  // Since mutable is not a viable storage class specifier in C, there is
3836  // no reason to treat it as an extension. Instead, diagnose as an error.
3837  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3838  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3839  Diag(DS.getStorageClassSpecLoc(), DiagID)
3841  }
3842 
3843  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3844  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3845  << DeclSpec::getSpecifierName(TSCS);
3846  if (DS.getTypeQualifiers()) {
3848  Diag(DS.getConstSpecLoc(), DiagID) << "const";
3850  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3851  // Restrict is covered above.
3853  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3854  }
3855 
3856  // Warn about ignored type attributes, for example:
3857  // __attribute__((aligned)) struct A;
3858  // Attributes should be placed after tag to apply to type declaration.
3859  if (!DS.getAttributes().empty()) {
3860  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3861  if (TypeSpecType == DeclSpec::TST_class ||
3862  TypeSpecType == DeclSpec::TST_struct ||
3863  TypeSpecType == DeclSpec::TST_interface ||
3864  TypeSpecType == DeclSpec::TST_union ||
3865  TypeSpecType == DeclSpec::TST_enum) {
3866  for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3867  attrs = attrs->getNext())
3868  Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3869  << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3870  }
3871  }
3872 
3873  return TagD;
3874 }
3875 
3876 /// We are trying to inject an anonymous member into the given scope;
3877 /// check if there's an existing declaration that can't be overloaded.
3878 ///
3879 /// \return true if this is a forbidden redeclaration
3880 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3881  Scope *S,
3882  DeclContext *Owner,
3883  DeclarationName Name,
3884  SourceLocation NameLoc,
3885  unsigned diagnostic) {
3886  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3888  if (!SemaRef.LookupName(R, S)) return false;
3889 
3890  if (R.getAsSingle<TagDecl>())
3891  return false;
3892 
3893  // Pick a representative declaration.
3895  assert(PrevDecl && "Expected a non-null Decl");
3896 
3897  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3898  return false;
3899 
3900  SemaRef.Diag(NameLoc, diagnostic) << Name;
3901  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3902 
3903  return true;
3904 }
3905 
3906 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3907 /// anonymous struct or union AnonRecord into the owning context Owner
3908 /// and scope S. This routine will be invoked just after we realize
3909 /// that an unnamed union or struct is actually an anonymous union or
3910 /// struct, e.g.,
3911 ///
3912 /// @code
3913 /// union {
3914 /// int i;
3915 /// float f;
3916 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3917 /// // f into the surrounding scope.x
3918 /// @endcode
3919 ///
3920 /// This routine is recursive, injecting the names of nested anonymous
3921 /// structs/unions into the owning context and scope as well.
3923  DeclContext *Owner,
3924  RecordDecl *AnonRecord,
3925  AccessSpecifier AS,
3926  SmallVectorImpl<NamedDecl *> &Chaining,
3927  bool MSAnonStruct) {
3928  unsigned diagKind
3929  = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3930  : diag::err_anonymous_struct_member_redecl;
3931 
3932  bool Invalid = false;
3933 
3934  // Look every FieldDecl and IndirectFieldDecl with a name.
3935  for (auto *D : AnonRecord->decls()) {
3936  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3937  cast<NamedDecl>(D)->getDeclName()) {
3938  ValueDecl *VD = cast<ValueDecl>(D);
3939  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3940  VD->getLocation(), diagKind)) {
3941  // C++ [class.union]p2:
3942  // The names of the members of an anonymous union shall be
3943  // distinct from the names of any other entity in the
3944  // scope in which the anonymous union is declared.
3945  Invalid = true;
3946  } else {
3947  // C++ [class.union]p2:
3948  // For the purpose of name lookup, after the anonymous union
3949  // definition, the members of the anonymous union are
3950  // considered to have been defined in the scope in which the
3951  // anonymous union is declared.
3952  unsigned OldChainingSize = Chaining.size();
3953  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3954  Chaining.append(IF->chain_begin(), IF->chain_end());
3955  else
3956  Chaining.push_back(VD);
3957 
3958  assert(Chaining.size() >= 2);
3959  NamedDecl **NamedChain =
3960  new (SemaRef.Context)NamedDecl*[Chaining.size()];
3961  for (unsigned i = 0; i < Chaining.size(); i++)
3962  NamedChain[i] = Chaining[i];
3963 
3965  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3966  VD->getType(), NamedChain, Chaining.size());
3967 
3968  for (const auto *Attr : VD->attrs())
3969  IndirectField->addAttr(Attr->clone(SemaRef.Context));
3970 
3971  IndirectField->setAccess(AS);
3972  IndirectField->setImplicit();
3973  SemaRef.PushOnScopeChains(IndirectField, S);
3974 
3975  // That includes picking up the appropriate access specifier.
3976  if (AS != AS_none) IndirectField->setAccess(AS);
3977 
3978  Chaining.resize(OldChainingSize);
3979  }
3980  }
3981  }
3982 
3983  return Invalid;
3984 }
3985 
3986 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3987 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3988 /// illegal input values are mapped to SC_None.
3989 static StorageClass
3991  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3992  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3993  "Parser allowed 'typedef' as storage class VarDecl.");
3994  switch (StorageClassSpec) {
3995  case DeclSpec::SCS_unspecified: return SC_None;
3996  case DeclSpec::SCS_extern:
3997  if (DS.isExternInLinkageSpec())
3998  return SC_None;
3999  return SC_Extern;
4000  case DeclSpec::SCS_static: return SC_Static;
4001  case DeclSpec::SCS_auto: return SC_Auto;
4002  case DeclSpec::SCS_register: return SC_Register;
4004  // Illegal SCSs map to None: error reporting is up to the caller.
4005  case DeclSpec::SCS_mutable: // Fall through.
4006  case DeclSpec::SCS_typedef: return SC_None;
4007  }
4008  llvm_unreachable("unknown storage class specifier");
4009 }
4010 
4012  assert(Record->hasInClassInitializer());
4013 
4014  for (const auto *I : Record->decls()) {
4015  const auto *FD = dyn_cast<FieldDecl>(I);
4016  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4017  FD = IFD->getAnonField();
4018  if (FD && FD->hasInClassInitializer())
4019  return FD->getLocation();
4020  }
4021 
4022  llvm_unreachable("couldn't find in-class initializer");
4023 }
4024 
4026  SourceLocation DefaultInitLoc) {
4027  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4028  return;
4029 
4030  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4031  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4032 }
4033 
4035  CXXRecordDecl *AnonUnion) {
4036  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4037  return;
4038 
4039  checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4040 }
4041 
4042 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4043 /// anonymous structure or union. Anonymous unions are a C++ feature
4044 /// (C++ [class.union]) and a C11 feature; anonymous structures
4045 /// are a C11 feature and GNU C++ extension.
4047  AccessSpecifier AS,
4048  RecordDecl *Record,
4049  const PrintingPolicy &Policy) {
4050  DeclContext *Owner = Record->getDeclContext();
4051 
4052  // Diagnose whether this anonymous struct/union is an extension.
4053  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4054  Diag(Record->getLocation(), diag::ext_anonymous_union);
4055  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4056  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4057  else if (!Record->isUnion() && !getLangOpts().C11)
4058  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4059 
4060  // C and C++ require different kinds of checks for anonymous
4061  // structs/unions.
4062  bool Invalid = false;
4063  if (getLangOpts().CPlusPlus) {
4064  const char *PrevSpec = nullptr;
4065  unsigned DiagID;
4066  if (Record->isUnion()) {
4067  // C++ [class.union]p6:
4068  // Anonymous unions declared in a named namespace or in the
4069  // global namespace shall be declared static.
4071  (isa<TranslationUnitDecl>(Owner) ||
4072  (isa<NamespaceDecl>(Owner) &&
4073  cast<NamespaceDecl>(Owner)->getDeclName()))) {
4074  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4075  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4076 
4077  // Recover by adding 'static'.
4079  PrevSpec, DiagID, Policy);
4080  }
4081  // C++ [class.union]p6:
4082  // A storage class is not allowed in a declaration of an
4083  // anonymous union in a class scope.
4085  isa<RecordDecl>(Owner)) {
4087  diag::err_anonymous_union_with_storage_spec)
4089 
4090  // Recover by removing the storage specifier.
4092  SourceLocation(),
4093  PrevSpec, DiagID, Context.getPrintingPolicy());
4094  }
4095  }
4096 
4097  // Ignore const/volatile/restrict qualifiers.
4098  if (DS.getTypeQualifiers()) {
4100  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4101  << Record->isUnion() << "const"
4104  Diag(DS.getVolatileSpecLoc(),
4105  diag::ext_anonymous_struct_union_qualified)
4106  << Record->isUnion() << "volatile"
4109  Diag(DS.getRestrictSpecLoc(),
4110  diag::ext_anonymous_struct_union_qualified)
4111  << Record->isUnion() << "restrict"
4114  Diag(DS.getAtomicSpecLoc(),
4115  diag::ext_anonymous_struct_union_qualified)
4116  << Record->isUnion() << "_Atomic"
4118 
4119  DS.ClearTypeQualifiers();
4120  }
4121 
4122  // C++ [class.union]p2:
4123  // The member-specification of an anonymous union shall only
4124  // define non-static data members. [Note: nested types and
4125  // functions cannot be declared within an anonymous union. ]
4126  for (auto *Mem : Record->decls()) {
4127  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4128  // C++ [class.union]p3:
4129  // An anonymous union shall not have private or protected
4130  // members (clause 11).
4131  assert(FD->getAccess() != AS_none);
4132  if (FD->getAccess() != AS_public) {
4133  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4134  << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
4135  Invalid = true;
4136  }
4137 
4138  // C++ [class.union]p1
4139  // An object of a class with a non-trivial constructor, a non-trivial
4140  // copy constructor, a non-trivial destructor, or a non-trivial copy
4141  // assignment operator cannot be a member of a union, nor can an
4142  // array of such objects.
4143  if (CheckNontrivialField(FD))
4144  Invalid = true;
4145  } else if (Mem->isImplicit()) {
4146  // Any implicit members are fine.
4147  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4148  // This is a type that showed up in an
4149  // elaborated-type-specifier inside the anonymous struct or
4150  // union, but which actually declares a type outside of the
4151  // anonymous struct or union. It's okay.
4152  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4153  if (!MemRecord->isAnonymousStructOrUnion() &&
4154  MemRecord->getDeclName()) {
4155  // Visual C++ allows type definition in anonymous struct or union.
4156  if (getLangOpts().MicrosoftExt)
4157  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4158  << (int)Record->isUnion();
4159  else {
4160  // This is a nested type declaration.
4161  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4162  << (int)Record->isUnion();
4163  Invalid = true;
4164  }
4165  } else {
4166  // This is an anonymous type definition within another anonymous type.
4167  // This is a popular extension, provided by Plan9, MSVC and GCC, but
4168  // not part of standard C++.
4169  Diag(MemRecord->getLocation(),
4170  diag::ext_anonymous_record_with_anonymous_type)
4171  << (int)Record->isUnion();
4172  }
4173  } else if (isa<AccessSpecDecl>(Mem)) {
4174  // Any access specifier is fine.
4175  } else if (isa<StaticAssertDecl>(Mem)) {
4176  // In C++1z, static_assert declarations are also fine.
4177  } else {
4178  // We have something that isn't a non-static data
4179  // member. Complain about it.
4180  unsigned DK = diag::err_anonymous_record_bad_member;
4181  if (isa<TypeDecl>(Mem))
4182  DK = diag::err_anonymous_record_with_type;
4183  else if (isa<FunctionDecl>(Mem))
4184  DK = diag::err_anonymous_record_with_function;
4185  else if (isa<VarDecl>(Mem))
4186  DK = diag::err_anonymous_record_with_static;
4187 
4188  // Visual C++ allows type definition in anonymous struct or union.
4189  if (getLangOpts().MicrosoftExt &&
4190  DK == diag::err_anonymous_record_with_type)
4191  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4192  << (int)Record->isUnion();
4193  else {
4194  Diag(Mem->getLocation(), DK)
4195  << (int)Record->isUnion();
4196  Invalid = true;
4197  }
4198  }
4199  }
4200 
4201  // C++11 [class.union]p8 (DR1460):
4202  // At most one variant member of a union may have a
4203  // brace-or-equal-initializer.
4204  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4205  Owner->isRecord())
4206  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4207  cast<CXXRecordDecl>(Record));
4208  }
4209 
4210  if (!Record->isUnion() && !Owner->isRecord()) {
4211  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4212  << (int)getLangOpts().CPlusPlus;
4213  Invalid = true;
4214  }
4215 
4216  // Mock up a declarator.
4218  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4219  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4220 
4221  // Create a declaration for this anonymous struct/union.
4222  NamedDecl *Anon = nullptr;
4223  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4224  Anon = FieldDecl::Create(Context, OwningClass,
4225  DS.getLocStart(),
4226  Record->getLocation(),
4227  /*IdentifierInfo=*/nullptr,
4228  Context.getTypeDeclType(Record),
4229  TInfo,
4230  /*BitWidth=*/nullptr, /*Mutable=*/false,
4231  /*InitStyle=*/ICIS_NoInit);
4232  Anon->setAccess(AS);
4233  if (getLangOpts().CPlusPlus)
4234  FieldCollector->Add(cast<FieldDecl>(Anon));
4235  } else {
4236  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4238  if (SCSpec == DeclSpec::SCS_mutable) {
4239  // mutable can only appear on non-static class members, so it's always
4240  // an error here
4241  Diag(Record->getLocation(), diag::err_mutable_nonmember);
4242  Invalid = true;
4243  SC = SC_None;
4244  }
4245 
4246  Anon = VarDecl::Create(Context, Owner,
4247  DS.getLocStart(),
4248  Record->getLocation(), /*IdentifierInfo=*/nullptr,
4249  Context.getTypeDeclType(Record),
4250  TInfo, SC);
4251 
4252  // Default-initialize the implicit variable. This initialization will be
4253  // trivial in almost all cases, except if a union member has an in-class
4254  // initializer:
4255  // union { int n = 0; };
4256  ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4257  }
4258  Anon->setImplicit();
4259 
4260  // Mark this as an anonymous struct/union type.
4261  Record->setAnonymousStructOrUnion(true);
4262 
4263  // Add the anonymous struct/union object to the current
4264  // context. We'll be referencing this object when we refer to one of
4265  // its members.
4266  Owner->addDecl(Anon);
4267 
4268  // Inject the members of the anonymous struct/union into the owning
4269  // context and into the identifier resolver chain for name lookup
4270  // purposes.
4272  Chain.push_back(Anon);
4273 
4274  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4275  Chain, false))
4276  Invalid = true;
4277 
4278  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4279  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4280  Decl *ManglingContextDecl;
4281  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4282  NewVD->getDeclContext(), ManglingContextDecl)) {
4284  NewVD, MCtx->getManglingNumber(
4285  NewVD, getMSManglingNumber(getLangOpts(), S)));
4286  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4287  }
4288  }
4289  }
4290 
4291  if (Invalid)
4292  Anon->setInvalidDecl();
4293 
4294  return Anon;
4295 }
4296 
4297 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4298 /// Microsoft C anonymous structure.
4299 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4300 /// Example:
4301 ///
4302 /// struct A { int a; };
4303 /// struct B { struct A; int b; };
4304 ///
4305 /// void foo() {
4306 /// B var;
4307 /// var.a = 3;
4308 /// }
4309 ///
4311  RecordDecl *Record) {
4312  assert(Record && "expected a record!");
4313 
4314  // Mock up a declarator.
4316  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4317  assert(TInfo && "couldn't build declarator info for anonymous struct");
4318 
4319  auto *ParentDecl = cast<RecordDecl>(CurContext);
4320  QualType RecTy = Context.getTypeDeclType(Record);
4321 
4322  // Create a declaration for this anonymous struct.
4324  ParentDecl,
4325  DS.getLocStart(),
4326  DS.getLocStart(),
4327  /*IdentifierInfo=*/nullptr,
4328  RecTy,
4329  TInfo,
4330  /*BitWidth=*/nullptr, /*Mutable=*/false,
4331  /*InitStyle=*/ICIS_NoInit);
4332  Anon->setImplicit();
4333 
4334  // Add the anonymous struct object to the current context.
4335  CurContext->addDecl(Anon);
4336 
4337  // Inject the members of the anonymous struct into the current
4338  // context and into the identifier resolver chain for name lookup
4339  // purposes.
4341  Chain.push_back(Anon);
4342 
4343  RecordDecl *RecordDef = Record->getDefinition();
4344  if (RequireCompleteType(Anon->getLocation(), RecTy,
4345  diag::err_field_incomplete) ||
4346  InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4347  AS_none, Chain, true)) {
4348  Anon->setInvalidDecl();
4349  ParentDecl->setInvalidDecl();
4350  }
4351 
4352  return Anon;
4353 }
4354 
4355 /// GetNameForDeclarator - Determine the full declaration name for the
4356 /// given Declarator.
4358  return GetNameFromUnqualifiedId(D.getName());
4359 }
4360 
4361 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4364  DeclarationNameInfo NameInfo;
4365  NameInfo.setLoc(Name.StartLocation);
4366 
4367  switch (Name.getKind()) {
4368 
4371  NameInfo.setName(Name.Identifier);
4372  NameInfo.setLoc(Name.StartLocation);
4373  return NameInfo;
4374 
4378  NameInfo.setLoc(Name.StartLocation);
4382  = Name.EndLocation.getRawEncoding();
4383  return NameInfo;
4384 
4387  Name.Identifier));
4388  NameInfo.setLoc(Name.StartLocation);
4390  return NameInfo;
4391 
4393  TypeSourceInfo *TInfo;
4394  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4395  if (Ty.isNull())
4396  return DeclarationNameInfo();
4398  Context.getCanonicalType(Ty)));
4399  NameInfo.setLoc(Name.StartLocation);
4400  NameInfo.setNamedTypeInfo(TInfo);
4401  return NameInfo;
4402  }
4403 
4405  TypeSourceInfo *TInfo;
4406  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4407  if (Ty.isNull())
4408  return DeclarationNameInfo();
4410  Context.getCanonicalType(Ty)));
4411  NameInfo.setLoc(Name.StartLocation);
4412  NameInfo.setNamedTypeInfo(TInfo);
4413  return NameInfo;
4414  }
4415 
4417  // In well-formed code, we can only have a constructor
4418  // template-id that refers to the current context, so go there
4419  // to find the actual type being constructed.
4420  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4421  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4422  return DeclarationNameInfo();
4423 
4424  // Determine the type of the class being constructed.
4425  QualType CurClassType = Context.getTypeDeclType(CurClass);
4426 
4427  // FIXME: Check two things: that the template-id names the same type as
4428  // CurClassType, and that the template-id does not occur when the name
4429  // was qualified.
4430 
4432  Context.getCanonicalType(CurClassType)));
4433  NameInfo.setLoc(Name.StartLocation);
4434  // FIXME: should we retrieve TypeSourceInfo?
4435  NameInfo.setNamedTypeInfo(nullptr);
4436  return NameInfo;
4437  }
4438 
4440  TypeSourceInfo *TInfo;
4441  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4442  if (Ty.isNull())
4443  return DeclarationNameInfo();
4445  Context.getCanonicalType(Ty)));
4446  NameInfo.setLoc(Name.StartLocation);
4447  NameInfo.setNamedTypeInfo(TInfo);
4448  return NameInfo;
4449  }
4450 
4452  TemplateName TName = Name.TemplateId->Template.get();
4453  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4454  return Context.getNameForTemplate(TName, TNameLoc);
4455  }
4456 
4457  } // switch (Name.getKind())
4458 
4459  llvm_unreachable("Unknown name kind");
4460 }
4461 
4463  do {
4464  if (Ty->isPointerType() || Ty->isReferenceType())
4465  Ty = Ty->getPointeeType();
4466  else if (Ty->isArrayType())
4467  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4468  else
4469  return Ty.withoutLocalFastQualifiers();
4470  } while (true);
4471 }
4472 
4473 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4474 /// and Definition have "nearly" matching parameters. This heuristic is
4475 /// used to improve diagnostics in the case where an out-of-line function
4476 /// definition doesn't match any declaration within the class or namespace.
4477 /// Also sets Params to the list of indices to the parameters that differ
4478 /// between the declaration and the definition. If hasSimilarParameters
4479 /// returns true and Params is empty, then all of the parameters match.
4481  FunctionDecl *Declaration,
4482  FunctionDecl *Definition,
4483  SmallVectorImpl<unsigned> &Params) {
4484  Params.clear();
4485  if (Declaration->param_size() != Definition->param_size())
4486  return false;
4487  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4488  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4489  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4490 
4491  // The parameter types are identical
4492  if (Context.hasSameType(DefParamTy, DeclParamTy))
4493  continue;
4494 
4495  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4496  QualType DefParamBaseTy = getCoreType(DefParamTy);
4497  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4498  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4499 
4500  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4501  (DeclTyName && DeclTyName == DefTyName))
4502  Params.push_back(Idx);
4503  else // The two parameters aren't even close
4504  return false;
4505  }
4506 
4507  return true;
4508 }
4509 
4510 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4511 /// declarator needs to be rebuilt in the current instantiation.
4512 /// Any bits of declarator which appear before the name are valid for
4513 /// consideration here. That's specifically the type in the decl spec
4514 /// and the base type in any member-pointer chunks.
4516  DeclarationName Name) {
4517  // The types we specifically need to rebuild are:
4518  // - typenames, typeofs, and decltypes
4519  // - types which will become injected class names
4520  // Of course, we also need to rebuild any type referencing such a
4521  // type. It's safest to just say "dependent", but we call out a
4522  // few cases here.
4523 
4524  DeclSpec &DS = D.getMutableDeclSpec();
4525  switch (DS.getTypeSpecType()) {
4529  case DeclSpec::TST_atomic: {
4530  // Grab the type from the parser.
4531  TypeSourceInfo *TSI = nullptr;
4532  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4533  if (T.isNull() || !T->isDependentType()) break;
4534 
4535  // Make sure there's a type source info. This isn't really much
4536  // of a waste; most dependent types should have type source info
4537  // attached already.
4538  if (!TSI)
4540 
4541  // Rebuild the type in the current instantiation.
4542  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4543  if (!TSI) return true;
4544 
4545  // Store the new type back in the decl spec.
4546  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4547  DS.UpdateTypeRep(LocType);
4548  break;
4549  }
4550 
4552  case DeclSpec::TST_typeofExpr: {
4553  Expr *E = DS.getRepAsExpr();
4555  if (Result.isInvalid()) return true;
4556  DS.UpdateExprRep(Result.get());
4557  break;
4558  }
4559 
4560  default:
4561  // Nothing to do for these decl specs.
4562  break;
4563  }
4564 
4565  // It doesn't matter what order we do this in.
4566  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4567  DeclaratorChunk &Chunk = D.getTypeObject(I);
4568 
4569  // The only type information in the declarator which can come
4570  // before the declaration name is the base type of a member
4571  // pointer.
4572  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4573  continue;
4574 
4575  // Rebuild the scope specifier in-place.
4576  CXXScopeSpec &SS = Chunk.Mem.Scope();
4578  return true;
4579  }
4580 
4581  return false;
4582 }
4583 
4586  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4587 
4588  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4589  Dcl && Dcl->getDeclContext()->isFileContext())
4591 
4592  return Dcl;
4593 }
4594 
4595 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4596 /// If T is the name of a class, then each of the following shall have a
4597 /// name different from T:
4598 /// - every static data member of class T;
4599 /// - every member function of class T
4600 /// - every member of class T that is itself a type;
4601 /// \returns true if the declaration name violates these rules.
4603  DeclarationNameInfo NameInfo) {
4604  DeclarationName Name = NameInfo.getName();
4605 
4606  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4607  if (Record->getIdentifier() && Record->getDeclName() == Name) {
4608  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4609  return true;
4610  }
4611 
4612  return false;
4613 }
4614 
4615 /// \brief Diagnose a declaration whose declarator-id has the given
4616 /// nested-name-specifier.
4617 ///
4618 /// \param SS The nested-name-specifier of the declarator-id.
4619 ///
4620 /// \param DC The declaration context to which the nested-name-specifier
4621 /// resolves.
4622 ///
4623 /// \param Name The name of the entity being declared.
4624 ///
4625 /// \param Loc The location of the name of the entity being declared.
4626 ///
4627 /// \returns true if we cannot safely recover from this error, false otherwise.
4629  DeclarationName Name,
4630  SourceLocation Loc) {
4631  DeclContext *Cur = CurContext;
4632  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4633  Cur = Cur->getParent();
4634 
4635  // If the user provided a superfluous scope specifier that refers back to the
4636  // class in which the entity is already declared, diagnose and ignore it.
4637  //
4638  // class X {
4639  // void X::f();
4640  // };
4641  //
4642  // Note, it was once ill-formed to give redundant qualification in all
4643  // contexts, but that rule was removed by DR482.
4644  if (Cur->Equals(DC)) {
4645  if (Cur->isRecord()) {
4646  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4647  : diag::err_member_extra_qualification)
4648  << Name << FixItHint::CreateRemoval(SS.getRange());
4649  SS.clear();
4650  } else {
4651  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4652  }
4653  return false;
4654  }
4655 
4656  // Check whether the qualifying scope encloses the scope of the original
4657  // declaration.
4658  if (!Cur->Encloses(DC)) {
4659  if (Cur->isRecord())
4660  Diag(Loc, diag::err_member_qualification)
4661  << Name << SS.getRange();
4662  else if (isa<TranslationUnitDecl>(DC))
4663  Diag(Loc, diag::err_invalid_declarator_global_scope)
4664  << Name << SS.getRange();
4665  else if (isa<FunctionDecl>(Cur))
4666  Diag(Loc, diag::err_invalid_declarator_in_function)
4667  << Name << SS.getRange();
4668  else if (isa<BlockDecl>(Cur))
4669  Diag(Loc, diag::err_invalid_declarator_in_block)
4670  << Name << SS.getRange();
4671  else
4672  Diag(Loc, diag::err_invalid_declarator_scope)
4673  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4674 
4675  return true;
4676  }
4677 
4678  if (Cur->isRecord()) {
4679  // Cannot qualify members within a class.
4680  Diag(Loc, diag::err_member_qualification)
4681  << Name << SS.getRange();
4682  SS.clear();
4683 
4684  // C++ constructors and destructors with incorrect scopes can break
4685  // our AST invariants by having the wrong underlying types. If
4686  // that's the case, then drop this declaration entirely.
4690  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4691  return true;
4692 
4693  return false;
4694  }
4695 
4696  // C++11 [dcl.meaning]p1:
4697  // [...] "The nested-name-specifier of the qualified declarator-id shall
4698  // not begin with a decltype-specifer"
4699  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4700  while (SpecLoc.getPrefix())
4701  SpecLoc = SpecLoc.getPrefix();
4702  if (dyn_cast_or_null<DecltypeType>(
4703  SpecLoc.getNestedNameSpecifier()->getAsType()))
4704  Diag(Loc, diag::err_decltype_in_declarator)
4705  << SpecLoc.getTypeLoc().getSourceRange();
4706 
4707  return false;
4708 }
4709 
4711  MultiTemplateParamsArg TemplateParamLists) {
4712  // TODO: consider using NameInfo for diagnostic.
4713  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4714  DeclarationName Name = NameInfo.getName();
4715 
4716  // All of these full declarators require an identifier. If it doesn't have
4717  // one, the ParsedFreeStandingDeclSpec action should be used.
4718  if (!Name) {
4719  if (!D.isInvalidType()) // Reject this if we think it is valid.
4721  diag::err_declarator_need_ident)
4722  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4723  return nullptr;
4724  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4725  return nullptr;
4726 
4727  // The scope passed in may not be a decl scope. Zip up the scope tree until
4728  // we find one that is.
4729  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4730  (S->getFlags() & Scope::TemplateParamScope) != 0)
4731  S = S->getParent();
4732 
4733  DeclContext *DC = CurContext;
4734  if (D.getCXXScopeSpec().isInvalid())
4735  D.setInvalidType();
4736  else if (D.getCXXScopeSpec().isSet()) {
4737  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4738  UPPC_DeclarationQualifier))
4739  return nullptr;
4740 
4741  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4742  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4743  if (!DC || isa<EnumDecl>(DC)) {
4744  // If we could not compute the declaration context, it's because the
4745  // declaration context is dependent but does not refer to a class,
4746  // class template, or class template partial specialization. Complain
4747  // and return early, to avoid the coming semantic disaster.
4748  Diag(D.getIdentifierLoc(),
4749  diag::err_template_qualified_declarator_no_match)
4750  << D.getCXXScopeSpec().getScopeRep()
4751  << D.getCXXScopeSpec().getRange();
4752  return nullptr;
4753  }
4754  bool IsDependentContext = DC->isDependentContext();
4755 
4756  if (!IsDependentContext &&
4757  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4758  return nullptr;
4759 
4760  // If a class is incomplete, do not parse entities inside it.
4761  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4762  Diag(D.getIdentifierLoc(),
4763  diag::err_member_def_undefined_record)
4764  << Name << DC << D.getCXXScopeSpec().getRange();
4765  return nullptr;
4766  }
4767  if (!D.getDeclSpec().isFriendSpecified()) {
4768  if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4769  Name, D.getIdentifierLoc())) {
4770  if (DC->isRecord())
4771  return nullptr;
4772 
4773  D.setInvalidType();
4774  }
4775  }
4776 
4777  // Check whether we need to rebuild the type of the given
4778  // declaration in the current instantiation.
4779  if (EnteringContext && IsDependentContext &&
4780  TemplateParamLists.size() != 0) {
4781  ContextRAII SavedContext(*this, DC);
4782  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4783  D.setInvalidType();
4784  }
4785  }
4786 
4787  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4788  QualType R = TInfo->getType();
4789 
4790  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4791  // If this is a typedef, we'll end up spewing multiple diagnostics.
4792  // Just return early; it's safer. If this is a function, let the
4793  // "constructor cannot have a return type" diagnostic handle it.
4795  return nullptr;
4796 
4797  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4798  UPPC_DeclarationType))
4799  D.setInvalidType();
4800 
4801  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4802  ForRedeclaration);
4803 
4804  // See if this is a redefinition of a variable in the same scope.
4805  if (!D.getCXXScopeSpec().isSet()) {
4806  bool IsLinkageLookup = false;
4807  bool CreateBuiltins = false;
4808 
4809  // If the declaration we're planning to build will be a function
4810  // or object with linkage, then look for another declaration with
4811  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4812  //
4813  // If the declaration we're planning to build will be declared with
4814  // external linkage in the translation unit, create any builtin with
4815  // the same name.
4817  /* Do nothing*/;
4818  else if (CurContext->isFunctionOrMethod() &&
4820  R->isFunctionType())) {
4821  IsLinkageLookup = true;
4822  CreateBuiltins =
4823  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4824  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4826  CreateBuiltins = true;
4827 
4828  if (IsLinkageLookup)
4829  Previous.clear(LookupRedeclarationWithLinkage);
4830 
4831  LookupName(Previous, S, CreateBuiltins);
4832  } else { // Something like "int foo::x;"
4833  LookupQualifiedName(Previous, DC);
4834 
4835  // C++ [dcl.meaning]p1:
4836  // When the declarator-id is qualified, the declaration shall refer to a
4837  // previously declared member of the class or namespace to which the
4838  // qualifier refers (or, in the case of a namespace, of an element of the
4839  // inline namespace set of that namespace (7.3.1)) or to a specialization
4840  // thereof; [...]
4841  //
4842  // Note that we already checked the context above, and that we do not have
4843  // enough information to make sure that Previous contains the declaration
4844  // we want to match. For example, given:
4845  //
4846  // class X {
4847  // void f();
4848  // void f(float);
4849  // };
4850  //
4851  // void X::f(int) { } // ill-formed
4852  //
4853  // In this case, Previous will point to the overload set
4854  // containing the two f's declared in X, but neither of them
4855  // matches.
4856 
4857  // C++ [dcl.meaning]p1:
4858  // [...] the member shall not merely have been introduced by a
4859  // using-declaration in the scope of the class or namespace nominated by
4860  // the nested-name-specifier of the declarator-id.
4861  RemoveUsingDecls(Previous);
4862  }
4863 
4864  if (Previous.isSingleResult() &&
4865  Previous.getFoundDecl()->isTemplateParameter()) {
4866  // Maybe we will complain about the shadowed template parameter.
4867  if (!D.isInvalidType())
4868  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4869  Previous.getFoundDecl());
4870 
4871  // Just pretend that we didn't see the previous declaration.
4872  Previous.clear();
4873  }
4874 
4875  // In C++, the previous declaration we find might be a tag type
4876  // (class or enum). In this case, the new declaration will hide the
4877  // tag type. Note that this does does not apply if we're declaring a
4878  // typedef (C++ [dcl.typedef]p4).
4879  if (Previous.isSingleTagDecl() &&
4881  Previous.clear();
4882 
4883  // Check that there are no default arguments other than in the parameters
4884  // of a function declaration (C++ only).
4885  if (getLangOpts().CPlusPlus)
4886  CheckExtraCXXDefaultArguments(D);
4887 
4888  NamedDecl *New;
4889 
4890  bool AddToScope = true;
4892  if (TemplateParamLists.size()) {
4893  Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4894  return nullptr;
4895  }
4896 
4897  New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4898  } else if (R->isFunctionType()) {
4899  New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4900  TemplateParamLists,
4901  AddToScope);
4902  } else {
4903  New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4904  AddToScope);
4905  }
4906 
4907  if (!New)
4908  return nullptr;
4909 
4910  // If this has an identifier and is not an invalid redeclaration or
4911  // function template specialization, add it to the scope stack.
4912  if (New->getDeclName() && AddToScope &&
4913  !(D.isRedeclaration() && New->isInvalidDecl())) {
4914  // Only make a locally-scoped extern declaration visible if it is the first
4915  // declaration of this entity. Qualified lookup for such an entity should
4916  // only find this declaration if there is no visible declaration of it.
4917  bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4918  PushOnScopeChains(New, S, AddToContext);
4919  if (!AddToContext)
4920  CurContext->addHiddenDecl(New);
4921  }
4922 
4923  return New;
4924 }
4925 
4926 /// Helper method to turn variable array types into constant array
4927 /// types in certain situations which would otherwise be errors (for
4928 /// GCC compatibility).
4931  bool &SizeIsNegative,
4932  llvm::APSInt &Oversized) {
4933  // This method tries to turn a variable array into a constant
4934  // array even when the size isn't an ICE. This is necessary
4935  // for compatibility with code that depends on gcc's buggy
4936  // constant expression folding, like struct {char x[(int)(char*)2];}
4937  SizeIsNegative = false;
4938  Oversized = 0;
4939 
4940  if (T->isDependentType())
4941  return QualType();
4942 
4943  QualifierCollector Qs;
4944  const Type *Ty = Qs.strip(T);
4945 
4946  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4947  QualType Pointee = PTy->getPointeeType();
4948  QualType FixedType =
4949  TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4950  Oversized);
4951  if (FixedType.isNull()) return FixedType;
4952  FixedType = Context.getPointerType(FixedType);
4953  return Qs.apply(Context, FixedType);
4954  }
4955  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4956  QualType Inner = PTy->getInnerType();
4957  QualType FixedType =
4958  TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4959  Oversized);
4960  if (FixedType.isNull()) return FixedType;
4961  FixedType = Context.getParenType(FixedType);
4962  return Qs.apply(Context, FixedType);
4963  }
4964 
4965  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4966  if (!VLATy)
4967  return QualType();
4968  // FIXME: We should probably handle this case
4969  if (VLATy->getElementType()->isVariablyModifiedType())
4970  return QualType();
4971 
4972  llvm::APSInt Res;
4973  if (!VLATy->getSizeExpr() ||
4974  !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4975  return QualType();
4976 
4977  // Check whether the array size is negative.
4978  if (Res.isSigned() && Res.isNegative()) {
4979  SizeIsNegative = true;
4980  return QualType();
4981  }
4982 
4983  // Check whether the array is too large to be addressed.
4984  unsigned ActiveSizeBits
4986  Res);
4987  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4988  Oversized = Res;
4989  return QualType();
4990  }
4991 
4992  return Context.getConstantArrayType(VLATy->getElementType(),
4993  Res, ArrayType::Normal, 0);
4994 }
4995 
4996 static void
4998  SrcTL = SrcTL.getUnqualifiedLoc();
4999  DstTL = DstTL.getUnqualifiedLoc();
5000  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5001  PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5002  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5003  DstPTL.getPointeeLoc());
5004  DstPTL.setStarLoc(SrcPTL.getStarLoc());
5005  return;
5006  }
5007  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5008  ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5009  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5010  DstPTL.getInnerLoc());
5011  DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5012  DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5013  return;
5014  }
5015  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5016  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5017  TypeLoc SrcElemTL = SrcATL.getElementLoc();
5018  TypeLoc DstElemTL = DstATL.getElementLoc();
5019  DstElemTL.initializeFullCopy(SrcElemTL);
5020  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5021  DstATL.setSizeExpr(SrcATL.getSizeExpr());
5022  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5023 }
5024 
5025 /// Helper method to turn variable array types into constant array
5026 /// types in certain situations which would otherwise be errors (for
5027 /// GCC compatibility).
5028 static TypeSourceInfo*
5031  bool &SizeIsNegative,
5032  llvm::APSInt &Oversized) {
5033  QualType FixedTy
5035  SizeIsNegative, Oversized);
5036  if (FixedTy.isNull())
5037  return nullptr;
5038  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5040  FixedTInfo->getTypeLoc());
5041  return FixedTInfo;
5042 }
5043 
5044 /// \brief Register the given locally-scoped extern "C" declaration so
5045 /// that it can be found later for redeclarations. We include any extern "C"
5046 /// declaration that is not visible in the translation unit here, not just
5047 /// function-scope declarations.
5048 void
5050  if (!getLangOpts().CPlusPlus &&
5052  // Don't need to track declarations in the TU in C.
5053  return;
5054 
5055  // Note that we have a locally-scoped external with this name.
5057 }
5058 
5060  // FIXME: We can have multiple results via __attribute__((overloadable)).
5061  auto Result = Context.getExternCContextDecl()->lookup(Name);
5062  return Result.empty() ? nullptr : *Result.begin();
5063 }
5064 
5065 /// \brief Diagnose function specifiers on a declaration of an identifier that
5066 /// does not identify a function.
5068  // FIXME: We should probably indicate the identifier in question to avoid
5069  // confusion for constructs like "inline int a(), b;"
5070  if (DS.isInlineSpecified())
5071  Diag(DS.getInlineSpecLoc(),
5072  diag::err_inline_non_function);
5073 
5074  if (DS.isVirtualSpecified())
5075  Diag(DS.getVirtualSpecLoc(),
5076  diag::err_virtual_non_function);
5077 
5078  if (DS.isExplicitSpecified())
5079  Diag(DS.getExplicitSpecLoc(),
5080  diag::err_explicit_non_function);
5081 
5082  if (DS.isNoreturnSpecified())
5083  Diag(DS.getNoreturnSpecLoc(),
5084  diag::err_noreturn_non_function);
5085 }
5086 
5087 NamedDecl*
5090  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5091  if (D.getCXXScopeSpec().isSet()) {
5092  Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5093  << D.getCXXScopeSpec().getRange();
5094  D.setInvalidType();
5095  // Pretend we didn't see the scope specifier.
5096  DC = CurContext;
5097  Previous.clear();
5098  }
5099 
5100  DiagnoseFunctionSpecifiers(D.getDeclSpec());
5101 
5103  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5104  << 1;
5105 
5107  Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5108  << D.getName().getSourceRange();
5109  return nullptr;
5110  }
5111 
5112  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5113  if (!NewTD) return nullptr;
5114 
5115  // Handle attributes prior to checking for duplicates in MergeVarDecl
5116  ProcessDeclAttributes(S, NewTD, D);
5117 
5118  CheckTypedefForVariablyModifiedType(S, NewTD);
5119 
5120  bool Redeclaration = D.isRedeclaration();
5121  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5122  D.setRedeclaration(Redeclaration);
5123  return ND;
5124 }
5125 
5126 void
5128  // C99 6.7.7p2: If a typedef name specifies a variably modified type
5129  // then it shall have block scope.
5130  // Note that variably modified types must be fixed before merging the decl so
5131  // that redeclarations will match.
5132  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5133  QualType T = TInfo->getType();
5134  if (T->isVariablyModifiedType()) {
5135  getCurFunction()->setHasBranchProtectedScope();
5136 
5137  if (S->getFnParent() == nullptr) {
5138  bool SizeIsNegative;
5139  llvm::APSInt Oversized;
5140  TypeSourceInfo *FixedTInfo =
5142  SizeIsNegative,
5143  Oversized);
5144  if (FixedTInfo) {
5145  Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5146  NewTD->setTypeSourceInfo(FixedTInfo);
5147  } else {
5148  if (SizeIsNegative)
5149  Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5150  else if (T->isVariableArrayType())
5151  Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5152  else if (Oversized.getBoolValue())
5153  Diag(NewTD->getLocation(), diag::err_array_too_large)
5154  << Oversized.toString(10);
5155  else
5156  Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5157  NewTD->setInvalidDecl();
5158  }
5159  }
5160  }
5161 }
5162 
5163 
5164 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5165 /// declares a typedef-name, either using the 'typedef' type specifier or via
5166 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5167 NamedDecl*
5169  LookupResult &Previous, bool &Redeclaration) {
5170  // Merge the decl with the existing one if appropriate. If the decl is
5171  // in an outer scope, it isn't the same thing.
5172  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5173  /*AllowInlineNamespace*/false);
5174  filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5175  if (!Previous.empty()) {
5176  Redeclaration = true;
5177  MergeTypedefNameDecl(NewTD, Previous);
5178  }
5179 
5180  // If this is the C FILE type, notify the AST context.
5181  if (IdentifierInfo *II = NewTD->getIdentifier())
5182  if (!NewTD->isInvalidDecl() &&
5184  if (II->isStr("FILE"))
5185  Context.setFILEDecl(NewTD);
5186  else if (II->isStr("jmp_buf"))
5187  Context.setjmp_bufDecl(NewTD);
5188  else if (II->isStr("sigjmp_buf"))
5189  Context.setsigjmp_bufDecl(NewTD);
5190  else if (II->isStr("ucontext_t"))
5191  Context.setucontext_tDecl(NewTD);
5192  }
5193 
5194  return NewTD;
5195 }
5196 
5197 /// \brief Determines whether the given declaration is an out-of-scope
5198 /// previous declaration.
5199 ///
5200 /// This routine should be invoked when name lookup has found a
5201 /// previous declaration (PrevDecl) that is not in the scope where a
5202 /// new declaration by the same name is being introduced. If the new
5203 /// declaration occurs in a local scope, previous declarations with
5204 /// linkage may still be considered previous declarations (C99
5205 /// 6.2.2p4-5, C++ [basic.link]p6).
5206 ///
5207 /// \param PrevDecl the previous declaration found by name
5208 /// lookup
5209 ///
5210 /// \param DC the context in which the new declaration is being
5211 /// declared.
5212 ///
5213 /// \returns true if PrevDecl is an out-of-scope previous declaration
5214 /// for a new delcaration with the same name.
5215 static bool
5217  ASTContext &Context) {
5218  if (!PrevDecl)
5219  return false;
5220 
5221  if (!PrevDecl->hasLinkage())
5222  return false;
5223 
5224  if (Context.getLangOpts().CPlusPlus) {
5225  // C++ [basic.link]p6:
5226  // If there is a visible declaration of an entity with linkage
5227  // having the same name and type, ignoring entities declared
5228  // outside the innermost enclosing namespace scope, the block
5229  // scope declaration declares that same entity and receives the
5230  // linkage of the previous declaration.
5231  DeclContext *OuterContext = DC->getRedeclContext();
5232  if (!OuterContext->isFunctionOrMethod())
5233  // This rule only applies to block-scope declarations.
5234  return false;
5235 
5236  DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5237  if (PrevOuterContext->isRecord())
5238  // We found a member function: ignore it.
5239  return false;
5240 
5241  // Find the innermost enclosing namespace for the new and
5242  // previous declarations.
5243  OuterContext = OuterContext->getEnclosingNamespaceContext();
5244  PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5245 
5246  // The previous declaration is in a different namespace, so it
5247  // isn't the same function.
5248  if (!OuterContext->Equals(PrevOuterContext))
5249  return false;
5250  }
5251 
5252  return true;
5253 }
5254 
5256  CXXScopeSpec &SS = D.getCXXScopeSpec();
5257  if (!SS.isSet()) return;
5259 }
5260 
5262  QualType type = decl->getType();
5263  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5264  if (lifetime == Qualifiers::OCL_Autoreleasing) {
5265  // Various kinds of declaration aren't allowed to be __autoreleasing.
5266  unsigned kind = -1U;
5267  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5268  if (var->hasAttr<BlocksAttr>())
5269  kind = 0; // __block
5270  else if (!var->hasLocalStorage())
5271  kind = 1; // global
5272  } else if (isa<ObjCIvarDecl>(decl)) {
5273  kind = 3; // ivar
5274  } else if (isa<FieldDecl>(decl)) {
5275  kind = 2; // field
5276  }
5277 
5278  if (kind != -1U) {
5279  Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5280  << kind;
5281  }
5282  } else if (lifetime == Qualifiers::OCL_None) {
5283  // Try to infer lifetime.
5284  if (!type->isObjCLifetimeType())
5285  return false;
5286 
5287  lifetime = type->getObjCARCImplicitLifetime();
5288  type = Context.getLifetimeQualifiedType(type, lifetime);
5289  decl->setType(type);
5290  }
5291 
5292  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5293  // Thread-local variables cannot have lifetime.
5294  if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5295  var->getTLSKind()) {
5296  Diag(var->getLocation(), diag::err_arc_thread_ownership)
5297  << var->getType();
5298  return true;
5299  }
5300  }
5301 
5302  return false;
5303 }
5304 
5306  // Ensure that an auto decl is deduced otherwise the checks below might cache
5307  // the wrong linkage.
5308  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5309 
5310  // 'weak' only applies to declarations with external linkage.
5311  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5312  if (!ND.isExternallyVisible()) {
5313  S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5314  ND.dropAttr<WeakAttr>();
5315  }
5316  }
5317  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5318  if (ND.isExternallyVisible()) {
5319  S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5320  ND.dropAttr<WeakRefAttr>();
5321  ND.dropAttr<AliasAttr>();
5322  }
5323  }
5324 
5325  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5326  if (VD->hasInit()) {
5327  if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5328  assert(VD->isThisDeclarationADefinition() &&
5329  !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5330  S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5331  VD->dropAttr<AliasAttr>();
5332  }
5333  }
5334  }
5335 
5336  // 'selectany' only applies to externally visible variable declarations.
5337  // It does not apply to functions.
5338  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5339  if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5340  S.Diag(Attr->getLocation(),
5341  diag::err_attribute_selectany_non_extern_data);
5342  ND.dropAttr<SelectAnyAttr>();
5343  }
5344  }
5345 
5346  // dll attributes require external linkage.
5347  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5348  if (!ND.isExternallyVisible()) {
5349  S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5350  << &ND << Attr;
5351  ND.setInvalidDecl();
5352  }
5353  }
5354 }
5355 
5357  NamedDecl *NewDecl,
5358  bool IsSpecialization) {
5359  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5360  OldDecl = OldTD->getTemplatedDecl();
5361  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5362  NewDecl = NewTD->getTemplatedDecl();
5363 
5364  if (!OldDecl || !NewDecl)
5365  return;
5366 
5367  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5368  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5369  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5370  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5371 
5372  // dllimport and dllexport are inheritable attributes so we have to exclude
5373  // inherited attribute instances.
5374  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5375  (NewExportAttr && !NewExportAttr->isInherited());
5376 
5377  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5378  // the only exception being explicit specializations.
5379  // Implicitly generated declarations are also excluded for now because there
5380  // is no other way to switch these to use dllimport or dllexport.
5381  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5382 
5383  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5384  // Allow with a warning for free functions and global variables.
5385  bool JustWarn = false;
5386  if (!OldDecl->isCXXClassMember()) {
5387  auto *VD = dyn_cast<VarDecl>(OldDecl);
5388  if (VD && !VD->getDescribedVarTemplate())
5389  JustWarn = true;
5390  auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5391  if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5392  JustWarn = true;
5393  }
5394 
5395  // We cannot change a declaration that's been used because IR has already
5396  // been emitted. Dllimported functions will still work though (modulo
5397  // address equality) as they can use the thunk.
5398  if (OldDecl->isUsed())
5399  if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5400  JustWarn = false;
5401 
5402  unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5403  : diag::err_attribute_dll_redeclaration;
5404  S.Diag(NewDecl->getLocation(), DiagID)
5405  << NewDecl
5406  << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5407  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5408  if (!JustWarn) {
5409  NewDecl->setInvalidDecl();
5410  return;
5411  }
5412  }
5413 
5414  // A redeclaration is not allowed to drop a dllimport attribute, the only
5415  // exceptions being inline function definitions, local extern declarations,
5416  // and qualified friend declarations.
5417  // NB: MSVC converts such a declaration to dllexport.
5418  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5419  if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5420  // Ignore static data because out-of-line definitions are diagnosed
5421  // separately.
5422  IsStaticDataMember = VD->isStaticDataMember();
5423  else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5424  IsInline = FD->isInlined();
5425  IsQualifiedFriend = FD->getQualifier() &&
5426  FD->getFriendObjectKind() == Decl::FOK_Declared;
5427  }
5428 
5429  if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5430  !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5431  S.Diag(NewDecl->getLocation(),
5432  diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5433  << NewDecl << OldImportAttr;
5434  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5435  S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5436  OldDecl->dropAttr<DLLImportAttr>();
5437  NewDecl->dropAttr<DLLImportAttr>();
5438  } else if (IsInline && OldImportAttr &&
5440  // In MinGW, seeing a function declared inline drops the dllimport attribute.
5441  OldDecl->dropAttr<DLLImportAttr>();
5442  NewDecl->dropAttr<DLLImportAttr>();
5443  S.Diag(NewDecl->getLocation(),
5444  diag::warn_dllimport_dropped_from_inline_function)
5445  << NewDecl << OldImportAttr;
5446  }
5447 }
5448 
5449 /// Given that we are within the definition of the given function,
5450 /// will that definition behave like C99's 'inline', where the
5451 /// definition is discarded except for optimization purposes?
5453  // Try to avoid calling GetGVALinkageForFunction.
5454 
5455  // All cases of this require the 'inline' keyword.
5456  if (!FD->isInlined()) return false;
5457 
5458  // This is only possible in C++ with the gnu_inline attribute.
5459  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5460  return false;
5461 
5462  // Okay, go ahead and call the relatively-more-expensive function.
5463 
5464 #ifndef NDEBUG
5465  // AST quite reasonably asserts that it's working on a function
5466  // definition. We don't really have a way to tell it that we're
5467  // currently defining the function, so just lie to it in +Asserts
5468  // builds. This is an awful hack.
5469  FD->setLazyBody(1);
5470 #endif
5471 
5472  bool isC99Inline =
5474 
5475 #ifndef NDEBUG
5476  FD->setLazyBody(0);
5477 #endif
5478 
5479  return isC99Inline;
5480 }
5481 
5482 /// Determine whether a variable is extern "C" prior to attaching
5483 /// an initializer. We can't just call isExternC() here, because that
5484 /// will also compute and cache whether the declaration is externally
5485 /// visible, which might change when we attach the initializer.
5486 ///
5487 /// This can only be used if the declaration is known to not be a
5488 /// redeclaration of an internal linkage declaration.
5489 ///
5490 /// For instance:
5491 ///
5492 /// auto x = []{};
5493 ///
5494 /// Attaching the initializer here makes this declaration not externally
5495 /// visible, because its type has internal linkage.
5496 ///
5497 /// FIXME: This is a hack.
5498 template<typename T>
5499 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5500  if (S.getLangOpts().CPlusPlus) {
5501  // In C++, the overloadable attribute negates the effects of extern "C".
5502  if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5503  return false;
5504  }
5505  return D->isExternC();
5506 }
5507 
5508 static bool shouldConsiderLinkage(const VarDecl *VD) {
5509  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5510  if (DC->isFunctionOrMethod())
5511  return VD->hasExternalStorage();
5512  if (DC->isFileContext())
5513  return true;
5514  if (DC->isRecord())
5515  return false;
5516  llvm_unreachable("Unexpected context");
5517 }
5518 
5519 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5520  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5521  if (DC->isFileContext() || DC->isFunctionOrMethod())
5522  return true;
5523  if (DC->isRecord())
5524  return false;
5525  llvm_unreachable("Unexpected context");
5526 }
5527 
5528 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5530  for (const AttributeList *L = AttrList; L; L = L->getNext())
5531  if (L->getKind() == Kind)
5532  return true;
5533  return false;
5534 }
5535 
5536 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5538  // Check decl attributes on the DeclSpec.
5540  return true;
5541 
5542  // Walk the declarator structure, checking decl attributes that were in a type
5543  // position to the decl itself.
5544  for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5545  if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5546  return true;
5547  }
5548 
5549  // Finally, check attributes on the decl itself.
5550  return hasParsedAttr(S, PD.getAttributes(), Kind);
5551 }
5552 
5553 /// Adjust the \c DeclContext for a function or variable that might be a
5554 /// function-local external declaration.
5556  if (!DC->isFunctionOrMethod())
5557  return false;
5558 
5559  // If this is a local extern function or variable declared within a function
5560  // template, don't add it into the enclosing namespace scope until it is
5561  // instantiated; it might have a dependent type right now.
5562  if (DC->isDependentContext())
5563  return true;
5564 
5565  // C++11 [basic.link]p7:
5566  // When a block scope declaration of an entity with linkage is not found to
5567  // refer to some other declaration, then that entity is a member of the
5568  // innermost enclosing namespace.
5569  //
5570  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5571  // semantically-enclosing namespace, not a lexically-enclosing one.
5572  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5573  DC = DC->getParent();
5574  return true;
5575 }
5576 
5577 /// \brief Returns true if given declaration is TU-scoped and externally
5578 /// visible.
5579 static bool isDeclTUScopedExternallyVisible(const Decl *D) {
5580  if (auto *FD = dyn_cast<FunctionDecl>(D))
5581  return (FD->getDeclContext()->isTranslationUnit() || FD->isExternC()) &&
5582  FD->hasExternalFormalLinkage();
5583  else if (auto *VD = dyn_cast<VarDecl>(D))
5584  return (VD->getDeclContext()->isTranslationUnit() || VD->isExternC()) &&
5585  VD->hasExternalFormalLinkage();
5586 
5587  llvm_unreachable("Unknown type of decl!");
5588 }
5589 
5590 NamedDecl *
5593  MultiTemplateParamsArg TemplateParamLists,
5594  bool &AddToScope) {
5595  QualType R = TInfo->getType();
5596  DeclarationName Name = GetNameForDeclarator(D).getName();
5597 
5600 
5601  // dllimport globals without explicit storage class are treated as extern. We
5602  // have to change the storage class this early to get the right DeclContext.
5603  if (SC == SC_None && !DC->isRecord() &&
5604  hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5605  !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5606  SC = SC_Extern;
5607 
5608  DeclContext *OriginalDC = DC;
5609  bool IsLocalExternDecl = SC == SC_Extern &&
5610  adjustContextForLocalExternDecl(DC);
5611 
5612  if (getLangOpts().OpenCL) {
5613  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5614  QualType NR = R;
5615  while (NR->isPointerType()) {
5616  if (NR->isFunctionPointerType()) {
5617  Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5618  D.setInvalidType();
5619  break;
5620  }
5621  NR = NR->getPointeeType();
5622  }
5623 
5624  if (!getOpenCLOptions().cl_khr_fp16) {
5625  // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5626  // half array type (unless the cl_khr_fp16 extension is enabled).
5628  Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5629  D.setInvalidType();
5630  }
5631  }
5632  }
5633 
5634  if (SCSpec == DeclSpec::SCS_mutable) {
5635  // mutable can only appear on non-static class members, so it's always
5636  // an error here
5637  Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5638  D.setInvalidType();
5639  SC = SC_None;
5640  }
5641 
5642  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5643  !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5645  // In C++11, the 'register' storage class specifier is deprecated.
5646  // Suppress the warning in system macros, it's used in macros in some
5647  // popular C system headers, such as in glibc's htonl() macro.
5649  diag::warn_deprecated_register)
5651  }
5652 
5653  IdentifierInfo *II = Name.getAsIdentifierInfo();
5654  if (!II) {
5655  Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5656  << Name;
5657  return nullptr;
5658  }
5659 
5660  DiagnoseFunctionSpecifiers(D.getDeclSpec());
5661 
5662  if (!DC->isRecord() && S->getFnParent() == nullptr) {
5663  // C99 6.9p2: The storage-class specifiers auto and register shall not
5664  // appear in the declaration specifiers in an external declaration.
5665  // Global Register+Asm is a GNU extension we support.
5666  if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5667  Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5668  D.setInvalidType();
5669  }
5670  }
5671 
5672  if (getLangOpts().OpenCL) {
5673  // Set up the special work-group-local storage class for variables in the
5674  // OpenCL __local address space.
5677  }
5678 
5679  // OpenCL v1.2 s6.9.b p4:
5680  // The sampler type cannot be used with the __local and __global address
5681  // space qualifiers.
5682  if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5684  Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5685  }
5686 
5687  // OpenCL 1.2 spec, p6.9 r:
5688  // The event type cannot be used to declare a program scope variable.
5689  // The event type cannot be used with the __local, __constant and __global
5690  // address space qualifiers.
5691  if (R->isEventT()) {
5692  if (S->getParent() == nullptr) {
5693  Diag(D.getLocStart(), diag::err_event_t_global_var);
5694  D.setInvalidType();
5695  }
5696 
5697  if (R.getAddressSpace()) {
5698  Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5699  D.setInvalidType();
5700  }
5701  }
5702  }
5703 
5704  bool IsExplicitSpecialization = false;
5705  bool IsVariableTemplateSpecialization = false;
5706  bool IsPartialSpecialization = false;
5707  bool IsVariableTemplate = false;
5708  VarDecl *NewVD = nullptr;
5709  VarTemplateDecl *NewTemplate = nullptr;
5710  TemplateParameterList *TemplateParams = nullptr;
5711  if (!getLangOpts().CPlusPlus) {
5712  NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5713  D.getIdentifierLoc(), II,
5714  R, TInfo, SC);
5715 
5716  if (D.isInvalidType())
5717  NewVD->setInvalidDecl();
5718  } else {
5719  bool Invalid = false;
5720 
5721  if (DC->isRecord() && !CurContext->isRecord()) {
5722  // This is an out-of-line definition of a static data member.
5723  switch (SC) {
5724  case SC_None:
5725  break;
5726  case SC_Static:
5728  diag::err_static_out_of_line)
5730  break;
5731  case SC_Auto:
5732  case SC_Register:
5733  case SC_Extern:
5734  // [dcl.stc] p2: The auto or register specifiers shall be applied only
5735  // to names of variables declared in a block or to function parameters.
5736  // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5737  // of class members
5738 
5740  diag::err_storage_class_for_static_member)
5742  break;
5743  case SC_PrivateExtern:
5744  llvm_unreachable("C storage class in c++!");
5746  llvm_unreachable("OpenCL storage class in c++!");
5747  }
5748  }
5749 
5750  if (SC == SC_Static && CurContext->isRecord()) {
5751  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5752  if (RD->isLocalClass())
5753  Diag(D.getIdentifierLoc(),
5754  diag::err_static_data_member_not_allowed_in_local_class)
5755  << Name << RD->getDeclName();
5756 
5757  // C++98 [class.union]p1: If a union contains a static data member,
5758  // the program is ill-formed. C++11 drops this restriction.
5759  if (RD->isUnion())
5760  Diag(D.getIdentifierLoc(),
5761  getLangOpts().CPlusPlus11
5762  ? diag::warn_cxx98_compat_static_data_member_in_union
5763  : diag::ext_static_data_member_in_union) << Name;
5764  // We conservatively disallow static data members in anonymous structs.
5765  else if (!RD->getDeclName())
5766  Diag(D.getIdentifierLoc(),
5767  diag::err_static_data_member_not_allowed_in_anon_struct)
5768  << Name << RD->isUnion();
5769  }
5770  }
5771 
5772  // Match up the template parameter lists with the scope specifier, then
5773  // determine whether we have a template or a template specialization.
5774  TemplateParams = MatchTemplateParametersToScopeSpecifier(
5776  D.getCXXScopeSpec(),
5778  ? D.getName().TemplateId
5779  : nullptr,
5780  TemplateParamLists,
5781  /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5782 
5783  if (TemplateParams) {
5784  if (!TemplateParams->size() &&
5786  // There is an extraneous 'template<>' for this variable. Complain
5787  // about it, but allow the declaration of the variable.
5788  Diag(TemplateParams->getTemplateLoc(),
5789  diag::err_template_variable_noparams)
5790  << II
5791  << SourceRange(TemplateParams->getTemplateLoc(),
5792  TemplateParams->getRAngleLoc());
5793  TemplateParams = nullptr;
5794  } else {
5796  // This is an explicit specialization or a partial specialization.
5797  // FIXME: Check that we can declare a specialization here.
5798  IsVariableTemplateSpecialization = true;
5799  IsPartialSpecialization = TemplateParams->size() > 0;
5800  } else { // if (TemplateParams->size() > 0)
5801  // This is a template declaration.
5802  IsVariableTemplate = true;
5803 
5804  // Check that we can declare a template here.
5805  if (CheckTemplateDeclScope(S, TemplateParams))
5806  return nullptr;
5807 
5808  // Only C++1y supports variable templates (N3651).
5809  Diag(D.getIdentifierLoc(),
5810  getLangOpts().CPlusPlus14
5811  ? diag::warn_cxx11_compat_variable_template
5812  : diag::ext_variable_template);
5813  }
5814  }
5815  } else {
5816  assert(
5817  (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5818  "should have a 'template<>' for this decl");
5819  }
5820 
5821  if (IsVariableTemplateSpecialization) {
5822  SourceLocation TemplateKWLoc =
5823  TemplateParamLists.size() > 0
5824  ? TemplateParamLists[0]->getTemplateLoc()
5825  : SourceLocation();
5826  DeclResult Res = ActOnVarTemplateSpecialization(
5827  S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5828  IsPartialSpecialization);
5829  if (Res.isInvalid())
5830  return nullptr;
5831  NewVD = cast<VarDecl>(Res.get());
5832  AddToScope = false;
5833  } else
5834  NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5835  D.getIdentifierLoc(), II, R, TInfo, SC);
5836 
5837  // If this is supposed to be a variable template, create it as such.
5838  if (IsVariableTemplate) {
5839  NewTemplate =
5841  TemplateParams, NewVD);
5842  NewVD->setDescribedVarTemplate(NewTemplate);
5843  }
5844 
5845  // If this decl has an auto type in need of deduction, make a note of the
5846  // Decl so we can diagnose uses of it in its own initializer.
5847  if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5848  ParsingInitForAutoVars.insert(NewVD);
5849 
5850  if (D.isInvalidType() || Invalid) {
5851  NewVD->setInvalidDecl();
5852  if (NewTemplate)
5853  NewTemplate->setInvalidDecl();
5854  }
5855 
5856  SetNestedNameSpecifier(NewVD, D);
5857 
5858  // If we have any template parameter lists that don't directly belong to
5859  // the variable (matching the scope specifier), store them.
5860  unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5861  if (TemplateParamLists.size() > VDTemplateParamLists)
5863  Context, TemplateParamLists.size() - VDTemplateParamLists,
5864  TemplateParamLists.data());
5865 
5867  NewVD->setConstexpr(true);
5868  }
5869 
5870  // Set the lexical context. If the declarator has a C++ scope specifier, the
5871  // lexical context will be different from the semantic context.
5872  NewVD->setLexicalDeclContext(CurContext);
5873  if (NewTemplate)
5874  NewTemplate->setLexicalDeclContext(CurContext);
5875 
5876  if (IsLocalExternDecl)
5877  NewVD->setLocalExternDecl();
5878 
5879  bool EmitTLSUnsupportedError = false;
5881  // C++11 [dcl.stc]p4:
5882  // When thread_local is applied to a variable of block scope the
5883  // storage-class-specifier static is implied if it does not appear
5884  // explicitly.
5885  // Core issue: 'static' is not implied if the variable is declared
5886  // 'extern'.
5887  if (NewVD->hasLocalStorage() &&
5888  (SCSpec != DeclSpec::SCS_unspecified ||
5889  TSCS != DeclSpec::TSCS_thread_local ||
5890  !DC->isFunctionOrMethod()))
5892  diag::err_thread_non_global)
5893  << DeclSpec::getSpecifierName(TSCS);
5894  else if (!Context.getTargetInfo().isTLSSupported()) {
5895  if (getLangOpts().CUDA) {
5896  // Postpone error emission until we've collected attributes required to
5897  // figure out whether it's a host or device variable and whether the
5898  // error should be ignored.
5899  EmitTLSUnsupportedError = true;
5900  // We still need to mark the variable as TLS so it shows up in AST with
5901  // proper storage class for other tools to use even if we're not going
5902  // to emit any code for it.
5903  NewVD->setTSCSpec(TSCS);
5904  } else
5906  diag::err_thread_unsupported);
5907  } else
5908  NewVD->setTSCSpec(TSCS);
5909  }
5910 
5911  // C99 6.7.4p3
5912  // An inline definition of a function with external linkage shall
5913  // not contain a definition of a modifiable object with static or
5914  // thread storage duration...
5915  // We only apply this when the function is required to be defined
5916  // elsewhere, i.e. when the function is not 'extern inline'. Note
5917  // that a local variable with thread storage duration still has to
5918  // be marked 'static'. Also note that it's possible to get these
5919  // semantics in C++ using __attribute__((gnu_inline)).
5920  if (SC == SC_Static && S->getFnParent() != nullptr &&
5921  !NewVD->getType().isConstQualified()) {
5922  FunctionDecl *CurFD = getCurFunctionDecl();
5923  if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5925  diag::warn_static_local_in_extern_inline);
5926  MaybeSuggestAddingStaticToDecl(CurFD);
5927  }
5928  }
5929 
5931  if (IsVariableTemplateSpecialization)
5932  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5933  << (IsPartialSpecialization ? 1 : 0)
5936  else if (IsExplicitSpecialization)
5937  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5938  << 2
5940  else if (NewVD->hasLocalStorage())
5941  Diag(NewVD->getLocation(), diag::err_module_private_local)
5942  << 0 << NewVD->getDeclName()
5945  else {
5946  NewVD->setModulePrivate();
5947  if (NewTemplate)
5948  NewTemplate->setModulePrivate();
5949  }
5950  }
5951 
5952  // Handle attributes prior to checking for duplicates in MergeVarDecl
5953  ProcessDeclAttributes(S, NewVD, D);
5954 
5955  if (getLangOpts().CUDA) {
5956  if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
5958  diag::err_thread_unsupported);
5959  // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5960  // storage [duration]."
5961  if (SC == SC_None && S->getFnParent() != nullptr &&
5962  (NewVD->hasAttr<CUDASharedAttr>() ||
5963  NewVD->hasAttr<CUDAConstantAttr>())) {
5964  NewVD->setStorageClass(SC_Static);
5965  }
5966  }
5967 
5968  // Ensure that dllimport globals without explicit storage class are treated as
5969  // extern. The storage class is set above using parsed attributes. Now we can
5970  // check the VarDecl itself.
5971  assert(!NewVD->hasAttr<DLLImportAttr>() ||
5972  NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5973  NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5974 
5975  // In auto-retain/release, infer strong retension for variables of
5976  // retainable type.
5977  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5978  NewVD->setInvalidDecl();
5979 
5980  // Handle GNU asm-label extension (encoded as an attribute).
5981  if (Expr *E = (Expr*)D.getAsmLabel()) {
5982  // The parser guarantees this is a string.
5983  StringLiteral *SE = cast<StringLiteral>(E);
5984  StringRef Label = SE->getString();
5985  if (S->getFnParent() != nullptr) {
5986  switch (SC) {
5987  case SC_None:
5988  case SC_Auto:
5989  Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5990  break;
5991  case SC_Register:
5992  // Local Named register
5994  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5995  break;
5996  case SC_Static:
5997  case SC_Extern:
5998  case SC_PrivateExtern:
6000  break;
6001  }
6002  } else if (SC == SC_Register) {
6003  // Global Named register
6005  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6006  if (!R->isIntegralType(Context) && !R->isPointerType()) {
6007  Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6008  NewVD->setInvalidDecl(true);
6009  }
6010  }
6011 
6012  NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6013  Context, Label, 0));
6014  } else if (!ExtnameUndeclaredIdentifiers.empty() &&
6016  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6017  ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6018  if (I != ExtnameUndeclaredIdentifiers.end()) {
6019  NewVD->addAttr(I->second);
6020  ExtnameUndeclaredIdentifiers.erase(I);
6021  }
6022  }
6023 
6024  // Diagnose shadowed variables before filtering for scope.
6025  if (D.getCXXScopeSpec().isEmpty())
6026  CheckShadow(S, NewVD, Previous);
6027 
6028  // Don't consider existing declarations that are in a different
6029  // scope and are out-of-semantic-context declarations (if the new
6030  // declaration has linkage).
6031  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6032  D.getCXXScopeSpec().isNotEmpty() ||
6033  IsExplicitSpecialization ||
6034  IsVariableTemplateSpecialization);
6035 
6036  // Check whether the previous declaration is in the same block scope. This
6037  // affects whether we merge types with it, per C++11 [dcl.array]p3.
6038  if (getLangOpts().CPlusPlus &&
6039  NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6041  Previous.isSingleResult() && !Previous.isShadowed() &&
6042  isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6043 
6044  if (!getLangOpts().CPlusPlus) {
6045  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6046  } else {
6047  // If this is an explicit specialization of a static data member, check it.
6048  if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6049  CheckMemberSpecialization(NewVD, Previous))
6050  NewVD->setInvalidDecl();
6051 
6052  // Merge the decl with the existing one if appropriate.
6053  if (!Previous.empty()) {
6054  if (Previous.isSingleResult() &&
6055  isa<FieldDecl>(Previous.getFoundDecl()) &&
6056  D.getCXXScopeSpec().isSet()) {
6057  // The user tried to define a non-static data member
6058  // out-of-line (C++ [dcl.meaning]p1).
6059  Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6060  << D.getCXXScopeSpec().getRange();
6061  Previous.clear();
6062  NewVD->setInvalidDecl();
6063  }
6064  } else if (D.getCXXScopeSpec().isSet()) {
6065  // No previous declaration in the qualifying scope.
6066  Diag(D.getIdentifierLoc(), diag::err_no_member)
6067  << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6068  << D.getCXXScopeSpec().getRange();
6069  NewVD->setInvalidDecl();
6070  }
6071 
6072  if (!IsVariableTemplateSpecialization)
6073  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6074 
6075  if (NewTemplate) {
6076  VarTemplateDecl *PrevVarTemplate =
6077  NewVD->getPreviousDecl()
6079  : nullptr;
6080 
6081  // Check the template parameter list of this declaration, possibly
6082  // merging in the template parameter list from the previous variable
6083  // template declaration.
6084  if (CheckTemplateParameterList(
6085  TemplateParams,
6086  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6087  : nullptr,
6088  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6089  DC->isDependentContext())
6090  ? TPC_ClassTemplateMember
6091  : TPC_VarTemplate))
6092  NewVD->setInvalidDecl();
6093 
6094  // If we are providing an explicit specialization of a static variable
6095  // template, make a note of that.
6096  if (PrevVarTemplate &&
6097  PrevVarTemplate->getInstantiatedFromMemberTemplate())
6098  PrevVarTemplate->setMemberSpecialization();
6099  }
6100  }
6101 
6102  ProcessPragmaWeak(S, NewVD);
6103 
6104  // If this is the first declaration of an extern C variable, update
6105  // the map of such variables.
6106  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6107  isIncompleteDeclExternC(*this, NewVD))
6108  RegisterLocallyScopedExternCDecl(NewVD, S);
6109 
6110  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6111  Decl *ManglingContextDecl;
6112  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6113  NewVD->getDeclContext(), ManglingContextDecl)) {
6115  NewVD, MCtx->getManglingNumber(
6116  NewVD, getMSManglingNumber(getLangOpts(), S)));
6117  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6118  }
6119  }
6120 
6121  if (D.isRedeclaration() && !Previous.empty()) {
6123  *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6124  IsExplicitSpecialization);
6125  }
6126 
6127  if (NewTemplate) {
6128  if (NewVD->isInvalidDecl())
6129  NewTemplate->setInvalidDecl();
6130  ActOnDocumentableDecl(NewTemplate);
6131  return NewTemplate;
6132  }
6133 
6134  return NewVD;
6135 }
6136 
6137 /// \brief Diagnose variable or built-in function shadowing. Implements
6138 /// -Wshadow.
6139 ///
6140 /// This method is called whenever a VarDecl is added to a "useful"
6141 /// scope.
6142 ///
6143 /// \param S the scope in which the shadowing name is being declared
6144 /// \param R the lookup of the name
6145 ///
6147  // Return if warning is ignored.
6148  if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6149  return;
6150 
6151  // Don't diagnose declarations at file scope.
6152  if (D->hasGlobalStorage())
6153  return;
6154 
6155  DeclContext *NewDC = D->getDeclContext();
6156 
6157  // Only diagnose if we're shadowing an unambiguous field or variable.
6159  return;
6160 
6161  NamedDecl* ShadowedDecl = R.getFoundDecl();
6162  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6163  return;
6164 
6165  // Fields are not shadowed by variables in C++ static methods.
6166  if (isa<FieldDecl>(ShadowedDecl))
6167  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6168  if (MD->isStatic())
6169  return;
6170 
6171  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6172  if (shadowedVar->isExternC()) {
6173  // For shadowing external vars, make sure that we point to the global
6174  // declaration, not a locally scoped extern declaration.
6175  for (auto I : shadowedVar->redecls())
6176  if (I->isFileVarDecl()) {
6177  ShadowedDecl = I;
6178  break;
6179  }
6180  }
6181 
6182  DeclContext *OldDC = ShadowedDecl->getDeclContext();
6183 
6184  // Only warn about certain kinds of shadowing for class members.
6185  if (NewDC && NewDC->isRecord()) {
6186  // In particular, don't warn about shadowing non-class members.
6187  if (!OldDC->isRecord())
6188  return;
6189 
6190  // TODO: should we warn about static data members shadowing
6191  // static data members from base classes?
6192 
6193  // TODO: don't diagnose for inaccessible shadowed members.
6194  // This is hard to do perfectly because we might friend the
6195  // shadowing context, but that's just a false negative.
6196  }
6197 
6198  // Determine what kind of declaration we're shadowing.
6199  unsigned Kind;
6200  if (isa<RecordDecl>(OldDC)) {
6201  if (isa<FieldDecl>(ShadowedDecl))
6202  Kind = 3; // field
6203  else
6204  Kind = 2; // static data member
6205  } else if (OldDC->isFileContext())
6206  Kind = 1; // global
6207  else
6208  Kind = 0; // local
6209 
6210  DeclarationName Name = R.getLookupName();
6211 
6212  // Emit warning and note.
6213  if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6214  return;
6215  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6216  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6217 }
6218 
6219 /// \brief Check -Wshadow without the advantage of a previous lookup.
6221  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6222  return;
6223 
6224  LookupResult R(*this, D->getDeclName(), D->getLocation(),
6226  LookupName(R, S);
6227  CheckShadow(S, D, R);
6228 }
6229 
6230 /// Check for conflict between this global or extern "C" declaration and
6231 /// previous global or extern "C" declarations. This is only used in C++.
6232 template<typename T>
6234  Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6235  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6236  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6237 
6238  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6239  // The common case: this global doesn't conflict with any extern "C"
6240  // declaration.
6241  return false;
6242  }
6243 
6244  if (Prev) {
6245  if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6246  // Both the old and new declarations have C language linkage. This is a
6247  // redeclaration.
6248  Previous.clear();
6249  Previous.addDecl(Prev);
6250  return true;
6251  }
6252 
6253  // This is a global, non-extern "C" declaration, and there is a previous
6254  // non-global extern "C" declaration. Diagnose if this is a variable
6255  // declaration.
6256  if (!isa<VarDecl>(ND))
6257  return false;
6258  } else {
6259  // The declaration is extern "C". Check for any declaration in the
6260  // translation unit which might conflict.
6261  if (IsGlobal) {
6262  // We have already performed the lookup into the translation unit.
6263  IsGlobal = false;
6264  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6265  I != E; ++I) {
6266  if (isa<VarDecl>(*I)) {
6267  Prev = *I;
6268  break;
6269  }
6270  }
6271  } else {
6273  S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6274  for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6275  I != E; ++I) {
6276  if (isa<VarDecl>(*I)) {
6277  Prev = *I;
6278  break;
6279  }
6280  // FIXME: If we have any other entity with this name in global scope,
6281  // the declaration is ill-formed, but that is a defect: it breaks the
6282  // 'stat' hack, for instance. Only variables can have mangled name
6283  // clashes with extern "C" declarations, so only they deserve a
6284  // diagnostic.
6285  }
6286  }
6287 
6288  if (!Prev)
6289  return false;
6290  }
6291 
6292  // Use the first declaration's location to ensure we point at something which
6293  // is lexically inside an extern "C" linkage-spec.
6294  assert(Prev && "should have found a previous declaration to diagnose");
6295  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6296  Prev = FD->getFirstDecl();
6297  else
6298  Prev = cast<VarDecl>(Prev)->getFirstDecl();
6299 
6300  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6301  << IsGlobal << ND;
6302  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6303  << IsGlobal;
6304  return false;
6305 }
6306 
6307 /// Apply special rules for handling extern "C" declarations. Returns \c true
6308 /// if we have found that this is a redeclaration of some prior entity.
6309 ///
6310 /// Per C++ [dcl.link]p6:
6311 /// Two declarations [for a function or variable] with C language linkage
6312 /// with the same name that appear in different scopes refer to the same
6313 /// [entity]. An entity with C language linkage shall not be declared with
6314 /// the same name as an entity in global scope.
6315 template<typename T>
6318  if (!S.getLangOpts().CPlusPlus) {
6319  // In C, when declaring a global variable, look for a corresponding 'extern'
6320  // variable declared in function scope. We don't need this in C++, because
6321  // we find local extern decls in the surrounding file-scope DeclContext.
6322  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6323  if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6324  Previous.clear();
6325  Previous.addDecl(Prev);
6326  return true;
6327  }
6328  }
6329  return false;
6330  }
6331 
6332  // A declaration in the translation unit can conflict with an extern "C"
6333  // declaration.
6334  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6335  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6336 
6337  // An extern "C" declaration can conflict with a declaration in the
6338  // translation unit or can be a redeclaration of an extern "C" declaration
6339  // in another scope.
6340  if (isIncompleteDeclExternC(S,ND))
6341  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6342 
6343  // Neither global nor extern "C": nothing to do.
6344  return false;
6345 }
6346 
6348  // If the decl is already known invalid, don't check it.
6349  if (NewVD->isInvalidDecl())
6350  return;
6351 
6352  TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6353  QualType T = TInfo->getType();
6354 
6355  // Defer checking an 'auto' type until its initializer is attached.
6356  if (T->isUndeducedType())
6357  return;
6358 
6359  if (NewVD->hasAttrs())
6360  CheckAlignasUnderalignment(NewVD);
6361 
6362  if (T->isObjCObjectType()) {
6363  Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6364  << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6366  NewVD->setType(T);
6367  }
6368 
6369  // Emit an error if an address space was applied to decl with local storage.
6370  // This includes arrays of objects with address space qualifiers, but not
6371  // automatic variables that point to other address spaces.
6372  // ISO/IEC TR 18037 S5.1.2
6373  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6374  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6375  NewVD->setInvalidDecl();
6376  return;
6377  }
6378 
6379  // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6380  // __constant address space.
6381  if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
6383  && !T->isSamplerT()){
6384  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
6385  NewVD->setInvalidDecl();
6386  return;
6387  }
6388 
6389  // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6390  // scope.
6391  if ((getLangOpts().OpenCLVersion >= 120)
6392  && NewVD->isStaticLocal()) {
6393  Diag(NewVD->getLocation(), diag::err_static_function_scope);
6394  NewVD->setInvalidDecl();
6395  return;
6396  }
6397 
6398  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6399  && !NewVD->hasAttr<BlocksAttr>()) {
6400  if (getLangOpts().getGC() != LangOptions::NonGC)
6401  Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6402  else {
6403  assert(!getLangOpts().ObjCAutoRefCount);
6404  Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6405  }
6406  }
6407 
6408  bool isVM = T->isVariablyModifiedType();
6409  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6410  NewVD->hasAttr<BlocksAttr>())
6411  getCurFunction()->setHasBranchProtectedScope();
6412 
6413  if ((isVM && NewVD->hasLinkage()) ||
6414  (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6415  bool SizeIsNegative;
6416  llvm::APSInt Oversized;
6417  TypeSourceInfo *FixedTInfo =
6419  SizeIsNegative, Oversized);
6420  if (!FixedTInfo && T->isVariableArrayType()) {
6422  // FIXME: This won't give the correct result for
6423  // int a[10][n];
6424  SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6425 
6426  if (NewVD->isFileVarDecl())
6427  Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6428  << SizeRange;
6429  else if (NewVD->isStaticLocal())
6430  Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6431  << SizeRange;
6432  else
6433  Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6434  << SizeRange;
6435  NewVD->setInvalidDecl();
6436  return;
6437  }
6438 
6439  if (!FixedTInfo) {
6440  if (NewVD->isFileVarDecl())
6441  Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6442  else
6443  Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6444  NewVD->setInvalidDecl();
6445  return;
6446  }
6447 
6448  Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6449  NewVD->setType(FixedTInfo->getType());
6450  NewVD->setTypeSourceInfo(FixedTInfo);
6451  }
6452 
6453  if (T->isVoidType()) {
6454  // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6455  // of objects and functions.
6456  if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6457  Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6458  << T;
6459  NewVD->setInvalidDecl();
6460  return;
6461  }
6462  }
6463 
6464  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6465  Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6466  NewVD->setInvalidDecl();
6467  return;
6468  }
6469 
6470  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6471  Diag(NewVD->getLocation(), diag::err_block_on_vm);
6472  NewVD->setInvalidDecl();
6473  return;
6474  }
6475 
6476  if (NewVD->isConstexpr() && !T->isDependentType() &&
6477  RequireLiteralType(NewVD->getLocation(), T,
6478  diag::err_constexpr_var_non_literal)) {
6479  NewVD->setInvalidDecl();
6480  return;
6481  }
6482 }
6483 
6484 /// \brief Perform semantic checking on a newly-created variable
6485 /// declaration.
6486 ///
6487 /// This routine performs all of the type-checking required for a
6488 /// variable declaration once it has been built. It is used both to
6489 /// check variables after they have been parsed and their declarators
6490 /// have been translated into a declaration, and to check variables
6491 /// that have been instantiated from a template.
6492 ///
6493 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6494 ///
6495 /// Returns true if the variable declaration is a redeclaration.
6497  CheckVariableDeclarationType(NewVD);
6498 
6499  // If the decl is already known invalid, don't check it.
6500  if (NewVD->isInvalidDecl())
6501  return false;
6502 
6503  // If we did not find anything by this name, look for a non-visible
6504  // extern "C" declaration with the same name.
6505  if (Previous.empty() &&
6506  checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6507  Previous.setShadowed();
6508 
6509  // Filter out any non-conflicting previous declarations.
6510  filterNonConflictingPreviousDecls(*this, NewVD, Previous);
6511 
6512  if (!Previous.empty()) {
6513  MergeVarDecl(NewVD, Previous);
6514  return true;
6515  }
6516  return false;
6517 }
6518 
6519 /// \brief Data used with FindOverriddenMethod
6523 };
6524 
6525 /// \brief Member lookup function that determines whether a given C++
6526 /// method overrides a method in a base class, to be used with
6527 /// CXXRecordDecl::lookupInBases().
6528 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
6529  CXXBasePath &Path,
6530  void *UserData) {
6531  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6532 
6534  = reinterpret_cast<FindOverriddenMethodData*>(UserData);
6535 
6536  DeclarationName Name = Data->Method->getDeclName();
6537 
6538  // FIXME: Do we care about other names here too?
6540  // We really want to find the base class destructor here.
6541  QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
6542  CanQualType CT = Data->S->Context.getCanonicalType(T);
6543 
6544  Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
6545  }
6546 
6547  for (Path.Decls = BaseRecord->lookup(Name);
6548  !Path.Decls.empty();
6549  Path.Decls = Path.Decls.slice(1)) {
6550  NamedDecl *D = Path.Decls.front();
6551  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6552  if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6553  return true;
6554  }
6555  }
6556 
6557  return false;
6558 }
6559 
6560 namespace {
6561  enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6562 }
6563 /// \brief Report an error regarding overriding, along with any relevant
6564 /// overriden methods.
6565 ///
6566 /// \param DiagID the primary error to report.
6567 /// \param MD the overriding method.
6568 /// \param OEK which overrides to include as notes.
6569 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6570  OverrideErrorKind OEK = OEK_All) {
6571  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6573  E = MD->end_overridden_methods();
6574  I != E; ++I) {
6575  // This check (& the OEK parameter) could be replaced by a predicate, but
6576  // without lambdas that would be overkill. This is still nicer than writing
6577  // out the diag loop 3 times.
6578  if ((OEK == OEK_All) ||
6579  (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6580  (OEK == OEK_Deleted && (*I)->isDeleted()))
6581  S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6582  }
6583 }
6584 
6585 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6586 /// and if so, check that it's a valid override and remember it.
6588  // Look for methods in base classes that this method might override.
6589  CXXBasePaths Paths;
6591  Data.Method = MD;
6592  Data.S = this;
6593  bool hasDeletedOverridenMethods = false;
6594  bool hasNonDeletedOverridenMethods = false;
6595  bool AddedAny = false;
6596  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6597  for (auto *I : Paths.found_decls()) {
6598  if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6599  MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6600  if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6601  !CheckOverridingFunctionAttributes(MD, OldMD) &&
6602  !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6603  !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6604  hasDeletedOverridenMethods |= OldMD->isDeleted();
6605  hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6606  AddedAny = true;
6607  }
6608  }
6609  }
6610  }
6611 
6612  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6613  ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6614  }
6615  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6616  ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6617  }
6618 
6619  return AddedAny;
6620 }
6621 
6622 namespace {
6623  // Struct for holding all of the extra arguments needed by
6624  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6625  struct ActOnFDArgs {
6626  Scope *S;
6627  Declarator &D;
6628  MultiTemplateParamsArg TemplateParamLists;
6629  bool AddToScope;
6630  };
6631 }
6632 
6633 namespace {
6634 
6635 // Callback to only accept typo corrections that have a non-zero edit distance.
6636 // Also only accept corrections that have the same parent decl.
6637 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6638  public:
6639  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6640  CXXRecordDecl *Parent)
6641  : Context(Context), OriginalFD(TypoFD),
6642  ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6643 
6644  bool ValidateCandidate(const TypoCorrection &candidate) override {
6645  if (candidate.getEditDistance() == 0)
6646  return false;
6647 
6648  SmallVector<unsigned, 1> MismatchedParams;
6649  for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6650  CDeclEnd = candidate.end();
6651  CDecl != CDeclEnd; ++CDecl) {
6652  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6653 
6654  if (FD && !FD->hasBody() &&
6655  hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6656  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6657  CXXRecordDecl *Parent = MD->getParent();
6658  if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6659  return true;
6660  } else if (!ExpectedParent) {
6661  return true;
6662  }
6663  }
6664  }
6665 
6666  return false;
6667  }
6668 
6669  private:
6671  FunctionDecl *OriginalFD;
6672  CXXRecordDecl *ExpectedParent;
6673 };
6674 
6675 }
6676 
6677 /// \brief Generate diagnostics for an invalid function redeclaration.
6678 ///
6679 /// This routine handles generating the diagnostic messages for an invalid
6680 /// function redeclaration, including finding possible similar declarations
6681 /// or performing typo correction if there are no previous declarations with
6682 /// the same name.
6683 ///
6684 /// Returns a NamedDecl iff typo correction was performed and substituting in
6685 /// the new declaration name does not cause new errors.
6687  Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6688  ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6689  DeclarationName Name = NewFD->getDeclName();
6690  DeclContext *NewDC = NewFD->getDeclContext();
6691  SmallVector<unsigned, 1> MismatchedParams;
6693  TypoCorrection Correction;
6694  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6695  unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6696  : diag::err_member_decl_does_not_match;
6697  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6698  IsLocalFriend ? Sema::LookupLocalFriendName
6701 
6702  NewFD->setInvalidDecl();
6703  if (IsLocalFriend)
6704  SemaRef.LookupName(Prev, S);
6705  else
6706  SemaRef.LookupQualifiedName(Prev, NewDC);
6707  assert(!Prev.isAmbiguous() &&
6708  "Cannot have an ambiguity in previous-declaration lookup");
6709  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6710  if (!Prev.empty()) {
6711  for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6712  Func != FuncEnd; ++Func) {
6713  FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6714  if (FD &&
6715  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6716  // Add 1 to the index so that 0 can mean the mismatch didn't
6717  // involve a parameter
6718  unsigned ParamNum =
6719  MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6720  NearMatches.push_back(std::make_pair(FD, ParamNum));
6721  }
6722  }
6723  // If the qualified name lookup yielded nothing, try typo correction
6724  } else if ((Correction = SemaRef.CorrectTypo(
6725  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6726  &ExtraArgs.D.getCXXScopeSpec(),
6727  llvm::make_unique<DifferentNameValidatorCCC>(
6728  SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6729  Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6730  // Set up everything for the call to ActOnFunctionDeclarator
6731  ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6732  ExtraArgs.D.getIdentifierLoc());
6733  Previous.clear();
6734  Previous.setLookupName(Correction.getCorrection());
6735  for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6736  CDeclEnd = Correction.end();
6737  CDecl != CDeclEnd; ++CDecl) {
6738  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6739  if (FD && !FD->hasBody() &&
6740  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6741  Previous.addDecl(FD);
6742  }
6743  }
6744  bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6745 
6746  NamedDecl *Result;
6747  // Retry building the function declaration with the new previous
6748  // declarations, and with errors suppressed.
6749  {
6750  // Trap errors.
6751  Sema::SFINAETrap Trap(SemaRef);
6752 
6753  // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6754  // pieces need to verify the typo-corrected C++ declaration and hopefully
6755  // eliminate the need for the parameter pack ExtraArgs.
6756  Result = SemaRef.ActOnFunctionDeclarator(
6757  ExtraArgs.S, ExtraArgs.D,
6758  Correction.getCorrectionDecl()->getDeclContext(),
6759  NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6760  ExtraArgs.AddToScope);
6761 
6762  if (Trap.hasErrorOccurred())
6763  Result = nullptr;
6764  }
6765 
6766  if (Result) {
6767  // Determine which correction we picked.
6768  Decl *Canonical = Result->getCanonicalDecl();
6769  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6770  I != E; ++I)
6771  if ((*I)->getCanonicalDecl() == Canonical)
6772  Correction.setCorrectionDecl(*I);
6773 
6774  SemaRef.diagnoseTypo(
6775  Correction,
6776  SemaRef.PDiag(IsLocalFriend
6777  ? diag::err_no_matching_local_friend_suggest
6778  : diag::err_member_decl_does_not_match_suggest)
6779  << Name << NewDC << IsDefinition);
6780  return Result;
6781  }
6782 
6783  // Pretend the typo correction never occurred
6784  ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6785  ExtraArgs.D.getIdentifierLoc());
6786  ExtraArgs.D.setRedeclaration(wasRedeclaration);
6787  Previous.clear();
6788  Previous.setLookupName(Name);
6789  }
6790 
6791  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6792  << Name << NewDC << IsDefinition << NewFD->getLocation();
6793 
6794  bool NewFDisConst = false;
6795  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6796  NewFDisConst = NewMD->isConst();
6797 
6798  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6799  NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6800  NearMatch != NearMatchEnd; ++NearMatch) {
6801  FunctionDecl *FD = NearMatch->first;
6802  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6803  bool FDisConst = MD && MD->isConst();
6804  bool IsMember = MD || !IsLocalFriend;
6805 
6806  // FIXME: These notes are poorly worded for the local friend case.
6807  if (unsigned Idx = NearMatch->second) {
6808  ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6809  SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6810  if (Loc.isInvalid()) Loc = FD->getLocation();
6811  SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6812  : diag::note_local_decl_close_param_match)
6813  << Idx << FDParam->getType()
6814  << NewFD->getParamDecl(Idx - 1)->getType();
6815  } else if (FDisConst != NewFDisConst) {
6816  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6817  << NewFDisConst << FD->getSourceRange().getEnd();
6818  } else
6819  SemaRef.Diag(FD->getLocation(),
6820  IsMember ? diag::note_member_def_close_match
6821  : diag::note_local_decl_close_match);
6822  }
6823  return nullptr;
6824 }
6825 
6827  switch (D.getDeclSpec().getStorageClassSpec()) {
6828  default: llvm_unreachable("Unknown storage class!");
6829  case DeclSpec::SCS_auto:
6831  case DeclSpec::SCS_mutable:
6832  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6833  diag::err_typecheck_sclass_func);
6834  D.setInvalidType();
6835  break;
6836  case DeclSpec::SCS_unspecified: break;
6837  case DeclSpec::SCS_extern:
6839  return SC_None;
6840  return SC_Extern;
6841  case DeclSpec::SCS_static: {
6842  if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6843  // C99 6.7.1p5:
6844  // The declaration of an identifier for a function that has
6845  // block scope shall have no explicit storage-class specifier
6846  // other than extern
6847  // See also (C++ [dcl.stc]p4).
6848  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6849  diag::err_static_block_func);
6850  break;
6851  } else
6852  return SC_Static;
6853  }
6855  }
6856 
6857  // No explicit storage class has already been returned
6858  return SC_None;
6859 }
6860 
6862  DeclContext *DC, QualType &R,
6863  TypeSourceInfo *TInfo,
6864  StorageClass SC,
6865  bool &IsVirtualOkay) {
6866  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6867  DeclarationName Name = NameInfo.getName();
6868 
6869  FunctionDecl *NewFD = nullptr;
6870  bool isInline = D.getDeclSpec().isInlineSpecified();
6871 
6872  if (!SemaRef.getLangOpts().CPlusPlus) {
6873  // Determine whether the function was written with a
6874  // prototype. This true when:
6875  // - there is a prototype in the declarator, or
6876  // - the type R of the function is some kind of typedef or other reference
6877  // to a type name (which eventually refers to a function type).
6878  bool HasPrototype =
6880  (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6881 
6882  NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6883  D.getLocStart(), NameInfo, R,
6884  TInfo, SC, isInline,
6885  HasPrototype, false);
6886  if (D.isInvalidType())
6887  NewFD->setInvalidDecl();
6888 
6889  return NewFD;
6890  }
6891 
6892  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6893  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6894 
6895  // Check that the return type is not an abstract class type.
6896  // For record types, this is done by the AbstractClassUsageDiagnoser once
6897  // the class has been completely parsed.
6898  if (!DC->isRecord() &&
6899  SemaRef.RequireNonAbstractType(
6900  D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6901  diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6902  D.setInvalidType();
6903 
6905  // This is a C++ constructor declaration.
6906  assert(DC->isRecord() &&
6907  "Constructors can only be declared in a member context");
6908 
6909  R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6910  return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6911  D.getLocStart(), NameInfo,
6912  R, TInfo, isExplicit, isInline,
6913  /*isImplicitlyDeclared=*/false,
6914  isConstexpr);
6915 
6916  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6917  // This is a C++ destructor declaration.
6918  if (DC->isRecord()) {
6919  R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6920  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6922  SemaRef.Context, Record,
6923  D.getLocStart(),
6924  NameInfo, R, TInfo, isInline,
6925  /*isImplicitlyDeclared=*/false);
6926 
6927  // If the class is complete, then we now create the implicit exception
6928  // specification. If the class is incomplete or dependent, we can't do
6929  // it yet.
6930  if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6931  Record->getDefinition() && !Record->isBeingDefined() &&
6932  R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6933  SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6934  }
6935 
6936  IsVirtualOkay = true;
6937  return NewDD;
6938 
6939  } else {
6940  SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6941  D.setInvalidType();
6942 
6943  // Create a FunctionDecl to satisfy the function definition parsing
6944  // code path.
6945  return FunctionDecl::Create(SemaRef.Context, DC,
6946  D.getLocStart(),
6947  D.getIdentifierLoc(), Name, R, TInfo,
6948  SC, isInline,
6949  /*hasPrototype=*/true, isConstexpr);
6950  }
6951 
6953  if (!DC->isRecord()) {
6954  SemaRef.Diag(D.getIdentifierLoc(),
6955  diag::err_conv_function_not_member);
6956  return nullptr;
6957  }
6958 
6959  SemaRef.CheckConversionDeclarator(D, R, SC);
6960  IsVirtualOkay = true;
6961  return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6962  D.getLocStart(), NameInfo,
6963  R, TInfo, isInline, isExplicit,
6964  isConstexpr, SourceLocation());
6965 
6966  } else if (DC->isRecord()) {
6967  // If the name of the function is the same as the name of the record,
6968  // then this must be an invalid constructor that has a return type.
6969  // (The parser checks for a return type and makes the declarator a
6970  // constructor if it has no return type).
6971  if (Name.getAsIdentifierInfo() &&
6972  Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6973  SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6975  << SourceRange(D.getIdentifierLoc());
6976  return nullptr;
6977  }
6978 
6979  // This is a C++ method declaration.
6981  cast<CXXRecordDecl>(DC),
6982  D.getLocStart(), NameInfo, R,
6983  TInfo, SC, isInline,
6984  isConstexpr, SourceLocation());
6985  IsVirtualOkay = !Ret->isStatic();
6986  return Ret;
6987  } else {
6988  bool isFriend =
6989  SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
6990  if (!isFriend && SemaRef.CurContext->isRecord())
6991  return nullptr;
6992 
6993  // Determine whether the function was written with a
6994  // prototype. This true when:
6995  // - we're in C++ (where every function has a prototype),
6996  return FunctionDecl::Create(SemaRef.Context, DC,
6997  D.getLocStart(),
6998  NameInfo, R, TInfo, SC, isInline,
6999  true/*HasPrototype*/, isConstexpr);
7000  }
7001 }
7002 
7010 };
7011 
7013  if (PT->isPointerType()) {
7014  QualType PointeeType = PT->getPointeeType();
7015  if (PointeeType->isPointerType())
7016  return PtrPtrKernelParam;
7017  return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7018  : PtrKernelParam;
7019  }
7020 
7021  // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7022  // be used as builtin types.
7023 
7024  if (PT->isImageType())
7025  return PtrKernelParam;
7026 
7027  if (PT->isBooleanType())
7028  return InvalidKernelParam;
7029 
7030  if (PT->isEventT())
7031  return InvalidKernelParam;
7032 
7033  if (PT->isHalfType())
7034  return InvalidKernelParam;
7035 
7036  if (PT->isRecordType())
7037  return RecordKernelParam;
7038 
7039  return ValidKernelParam;
7040 }
7041 
7043  Sema &S,
7044  Declarator &D,
7045  ParmVarDecl *Param,
7046  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7047  QualType PT = Param->getType();
7048 
7049  // Cache the valid types we encounter to avoid rechecking structs that are
7050  // used again
7051  if (ValidTypes.count(PT.getTypePtr()))
7052  return;
7053 
7054  switch (getOpenCLKernelParameterType(PT)) {
7055  case PtrPtrKernelParam:
7056  // OpenCL v1.2 s6.9.a:
7057  // A kernel function argument cannot be declared as a
7058  // pointer to a pointer type.
7059  S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7060  D.setInvalidType();
7061  return;
7062 
7063  case PrivatePtrKernelParam:
7064  // OpenCL v1.2 s6.9.a:
7065  // A kernel function argument cannot be declared as a
7066  // pointer to the private address space.
7067  S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7068  D.setInvalidType();
7069  return;
7070 
7071  // OpenCL v1.2 s6.9.k:
7072  // Arguments to kernel functions in a program cannot be declared with the
7073  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7074  // uintptr_t or a struct and/or union that contain fields declared to be
7075  // one of these built-in scalar types.
7076 
7077  case InvalidKernelParam:
7078  // OpenCL v1.2 s6.8 n:
7079  // A kernel function argument cannot be declared
7080  // of event_t type.
7081  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7082  D.setInvalidType();
7083  return;
7084 
7085  case PtrKernelParam:
7086  case ValidKernelParam:
7087  ValidTypes.insert(PT.getTypePtr());
7088  return;
7089 
7090  case RecordKernelParam:
7091  break;
7092  }
7093 
7094  // Track nested structs we will inspect
7095  SmallVector<const Decl *, 4> VisitStack;
7096 
7097  // Track where we are in the nested structs. Items will migrate from
7098  // VisitStack to HistoryStack as we do the DFS for bad field.
7099  SmallVector<const FieldDecl *, 4> HistoryStack;
7100  HistoryStack.push_back(nullptr);
7101 
7102  const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7103  VisitStack.push_back(PD);
7104 
7105  assert(VisitStack.back() && "First decl null?");
7106 
7107  do {
7108  const Decl *Next = VisitStack.pop_back_val();
7109  if (!Next) {
7110  assert(!HistoryStack.empty());
7111  // Found a marker, we have gone up a level
7112  if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7113  ValidTypes.insert(Hist->getType().getTypePtr());
7114 
7115  continue;
7116  }
7117 
7118  // Adds everything except the original parameter declaration (which is not a
7119  // field itself) to the history stack.
7120  const RecordDecl *RD;
7121  if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7122  HistoryStack.push_back(Field);
7123  RD = Field->getType()->castAs<RecordType>()->getDecl();
7124  } else {
7125  RD = cast<RecordDecl>(Next);
7126  }
7127 
7128  // Add a null marker so we know when we've gone back up a level
7129  VisitStack.push_back(nullptr);
7130 
7131  for (const auto *FD : RD->fields()) {
7132  QualType QT = FD->getType();
7133 
7134  if (ValidTypes.count(QT.getTypePtr()))
7135  continue;
7136 
7138  if (ParamType == ValidKernelParam)
7139  continue;
7140 
7141  if (ParamType == RecordKernelParam) {
7142  VisitStack.push_back(FD);
7143  continue;
7144  }
7145 
7146  // OpenCL v1.2 s6.9.p:
7147  // Arguments to kernel functions that are declared to be a struct or union
7148  // do not allow OpenCL objects to be passed as elements of the struct or
7149  // union.
7150  if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7151  ParamType == PrivatePtrKernelParam) {
7152  S.Diag(Param->getLocation(),
7153  diag::err_record_with_pointers_kernel_param)
7154  << PT->isUnionType()
7155  << PT;
7156  } else {
7157  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7158  }
7159 
7160  S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7161  << PD->getDeclName();
7162 
7163  // We have an error, now let's go back up through history and show where
7164  // the offending field came from
7166  I = HistoryStack.begin() + 1,
7167  E = HistoryStack.end();
7168  I != E; ++I) {
7169  const FieldDecl *OuterField = *I;
7170  S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7171  << OuterField->getType();
7172  }
7173 
7174  S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7175  << QT->isPointerType()
7176  << QT;
7177  D.setInvalidType();
7178  return;
7179  }
7180  } while (!VisitStack.empty());
7181 }
7182 
7183 NamedDecl*
7186  MultiTemplateParamsArg TemplateParamLists,
7187  bool &AddToScope) {
7188  QualType R = TInfo->getType();
7189 
7190  assert(R.getTypePtr()->isFunctionType());
7191 
7192  // TODO: consider using NameInfo for diagnostic.
7193  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7194  DeclarationName Name = NameInfo.getName();
7195  StorageClass SC = getFunctionStorageClass(*this, D);
7196 
7199  diag::err_invalid_thread)
7200  << DeclSpec::getSpecifierName(TSCS);
7201 
7203  adjustMemberFunctionCC(R, D.isStaticMember());
7204 
7205  bool isFriend = false;
7206  FunctionTemplateDecl *FunctionTemplate = nullptr;
7207  bool isExplicitSpecialization = false;
7208  bool isFunctionTemplateSpecialization = false;
7209 
7210  bool isDependentClassScopeExplicitSpecialization = false;
7211  bool HasExplicitTemplateArgs = false;
7212  TemplateArgumentListInfo TemplateArgs;
7213 
7214  bool isVirtualOkay = false;
7215 
7216  DeclContext *OriginalDC = DC;
7217  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7218 
7219  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7220  isVirtualOkay);
7221  if (!NewFD) return nullptr;
7222 
7223  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7225 
7226  // Set the lexical context. If this is a function-scope declaration, or has a
7227  // C++ scope specifier, or is the object of a friend declaration, the lexical
7228  // context will be different from the semantic context.
7229  NewFD->setLexicalDeclContext(CurContext);
7230 
7231  if (IsLocalExternDecl)
7232  NewFD->setLocalExternDecl();
7233 
7234  if (getLangOpts().CPlusPlus) {
7235  bool isInline = D.getDeclSpec().isInlineSpecified();
7236  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7237  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7238  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7239  isFriend = D.getDeclSpec().isFriendSpecified();
7240  if (isFriend && !isInline && D.isFunctionDefinition()) {
7241  // C++ [class.friend]p5
7242  // A function can be defined in a friend declaration of a
7243  // class . . . . Such a function is implicitly inline.
7244  NewFD->setImplicitlyInline();
7245  }
7246 
7247  // If this is a method defined in an __interface, and is not a constructor
7248  // or an overloaded operator, then set the pure flag (isVirtual will already
7249  // return true).
7250  if (const CXXRecordDecl *Parent =
7251  dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7252  if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7253  NewFD->setPure(true);
7254 
7255  // C++ [class.union]p2
7256  // A union can have member functions, but not virtual functions.
7257  if (isVirtual && Parent->isUnion())
7258  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7259  }
7260 
7261  SetNestedNameSpecifier(NewFD, D);
7262  isExplicitSpecialization = false;
7263  isFunctionTemplateSpecialization = false;
7264  if (D.isInvalidType())
7265  NewFD->setInvalidDecl();
7266 
7267  // Match up the template parameter lists with the scope specifier, then
7268  // determine whether we have a template or a template specialization.
7269  bool Invalid = false;
7270  if (TemplateParameterList *TemplateParams =
7271  MatchTemplateParametersToScopeSpecifier(
7273  D.getCXXScopeSpec(),
7275  ? D.getName().TemplateId
7276  : nullptr,
7277  TemplateParamLists, isFriend, isExplicitSpecialization,
7278  Invalid)) {
7279  if (TemplateParams->size() > 0) {
7280  // This is a function template
7281 
7282  // Check that we can declare a template here.
7283  if (CheckTemplateDeclScope(S, TemplateParams))
7284  NewFD->setInvalidDecl();
7285 
7286  // A destructor cannot be a template.
7288  Diag(NewFD->getLocation(), diag::err_destructor_template);
7289  NewFD->setInvalidDecl();
7290  }
7291 
7292  // If we're adding a template to a dependent context, we may need to
7293  // rebuilding some of the types used within the template parameter list,
7294  // now that we know what the current instantiation is.
7295  if (DC->isDependentContext()) {
7296  ContextRAII SavedContext(*this, DC);
7297  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7298  Invalid = true;
7299  }
7300 
7301 
7302  FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7303  NewFD->getLocation(),
7304  Name, TemplateParams,
7305  NewFD);
7306  FunctionTemplate->setLexicalDeclContext(CurContext);
7307  NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7308 
7309  // For source fidelity, store the other template param lists.
7310  if (TemplateParamLists.size() > 1) {
7312  TemplateParamLists.size() - 1,
7313  TemplateParamLists.data());
7314  }
7315  } else {
7316  // This is a function template specialization.
7317  isFunctionTemplateSpecialization = true;
7318  // For source fidelity, store all the template param lists.
7319  if (TemplateParamLists.size() > 0)
7321  TemplateParamLists.size(),
7322  TemplateParamLists.data());
7323 
7324  // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7325  if (isFriend) {
7326  // We want to remove the "template<>", found here.
7327  SourceRange RemoveRange = TemplateParams->getSourceRange();
7328 
7329  // If we remove the template<> and the name is not a
7330  // template-id, we're actually silently creating a problem:
7331  // the friend declaration will refer to an untemplated decl,
7332  // and clearly the user wants a template specialization. So
7333  // we need to insert '<>' after the name.
7334  SourceLocation InsertLoc;
7336  InsertLoc = D.getName().getSourceRange().getEnd();
7337  InsertLoc = getLocForEndOfToken(InsertLoc);
7338  }
7339 
7340  Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7341  << Name << RemoveRange
7342  << FixItHint::CreateRemoval(RemoveRange)
7343  << FixItHint::CreateInsertion(InsertLoc, "<>");
7344  }
7345  }
7346  }
7347  else {
7348  // All template param lists were matched against the scope specifier:
7349  // this is NOT (an explicit specialization of) a template.
7350  if (TemplateParamLists.size() > 0)
7351  // For source fidelity, store all the template param lists.
7353  TemplateParamLists.size(),
7354  TemplateParamLists.data());
7355  }
7356 
7357  if (Invalid) {
7358  NewFD->setInvalidDecl();
7359  if (FunctionTemplate)
7360  FunctionTemplate->setInvalidDecl();
7361  }
7362 
7363  // C++ [dcl.fct.spec]p5:
7364  // The virtual specifier shall only be used in declarations of
7365  // nonstatic class member functions that appear within a
7366  // member-specification of a class declaration; see 10.3.
7367  //
7368  if (isVirtual && !NewFD->isInvalidDecl()) {
7369  if (!isVirtualOkay) {
7371  diag::err_virtual_non_function);
7372  } else if (!CurContext->isRecord()) {
7373  // 'virtual' was specified outside of the class.
7375  diag::err_virtual_out_of_class)
7377  } else if (NewFD->getDescribedFunctionTemplate()) {
7378  // C++ [temp.mem]p3:
7379  // A member function template shall not be virtual.
7381  diag::err_virtual_member_function_template)
7383  } else {
7384  // Okay: Add virtual to the method.
7385  NewFD->setVirtualAsWritten(true);
7386  }
7387 
7388  if (getLangOpts().CPlusPlus14 &&
7389  NewFD->getReturnType()->isUndeducedType())
7390  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7391  }
7392 
7393  if (getLangOpts().CPlusPlus14 &&
7394  (NewFD->isDependentContext() ||
7395  (isFriend && CurContext->isDependentContext())) &&
7396  NewFD->getReturnType()->isUndeducedType()) {
7397  // If the function template is referenced directly (for instance, as a
7398  // member of the current instantiation), pretend it has a dependent type.
7399  // This is not really justified by the standard, but is the only sane
7400  // thing to do.
7401  // FIXME: For a friend function, we have not marked the function as being
7402  // a friend yet, so 'isDependentContext' on the FD doesn't work.
7403  const FunctionProtoType *FPT =
7404  NewFD->getType()->castAs<FunctionProtoType>();
7405  QualType Result =
7406  SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7407  NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7408  FPT->getExtProtoInfo()));
7409  }
7410 
7411  // C++ [dcl.fct.spec]p3:
7412  // The inline specifier shall not appear on a block scope function
7413  // declaration.
7414  if (isInline && !NewFD->isInvalidDecl()) {
7415  if (CurContext->isFunctionOrMethod()) {
7416  // 'inline' is not allowed on block scope function declaration.
7418  diag::err_inline_declaration_block_scope) << Name
7420  }
7421  }
7422 
7423  // C++ [dcl.fct.spec]p6:
7424  // The explicit specifier shall be used only in the declaration of a
7425  // constructor or conversion function within its class definition;
7426  // see 12.3.1 and 12.3.2.
7427  if (isExplicit && !NewFD->isInvalidDecl()) {
7428  if (!CurContext->isRecord()) {
7429  // 'explicit' was specified outside of the class.
7431  diag::err_explicit_out_of_class)
7433  } else if (!isa<CXXConstructorDecl>(NewFD) &&
7434  !isa<CXXConversionDecl>(NewFD)) {
7435  // 'explicit' was specified on a function that wasn't a constructor
7436  // or conversion function.
7438  diag::err_explicit_non_ctor_or_conv_function)
7440  }
7441  }
7442 
7443  if (isConstexpr) {
7444  // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7445  // are implicitly inline.
7446  NewFD->setImplicitlyInline();
7447 
7448  // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7449  // be either constructors or to return a literal type. Therefore,
7450  // destructors cannot be declared constexpr.
7451  if (isa<CXXDestructorDecl>(NewFD))
7452  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7453  }
7454 
7455  // If __module_private__ was specified, mark the function accordingly.
7457  if (isFunctionTemplateSpecialization) {
7458  SourceLocation ModulePrivateLoc
7460  Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7461  << 0
7462  << FixItHint::CreateRemoval(ModulePrivateLoc);
7463  } else {
7464  NewFD->setModulePrivate();
7465  if (FunctionTemplate)
7466  FunctionTemplate->setModulePrivate();
7467  }
7468  }
7469 
7470  if (isFriend) {
7471  if (FunctionTemplate) {
7472  FunctionTemplate->setObjectOfFriendDecl();
7473  FunctionTemplate->setAccess(AS_public);
7474  }
7475  NewFD->setObjectOfFriendDecl();
7476  NewFD->setAccess(AS_public);
7477  }
7478 
7479  // If a function is defined as defaulted or deleted, mark it as such now.
7480  // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7481  // definition kind to FDK_Definition.
7482  switch (D.getFunctionDefinitionKind()) {
7483  case FDK_Declaration:
7484  case FDK_Definition:
7485  break;
7486 
7487  case FDK_Defaulted:
7488  NewFD->setDefaulted();
7489  break;
7490 
7491  case FDK_Deleted:
7492  NewFD->setDeletedAsWritten();
7493  break;
7494  }
7495 
7496  if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7497  D.isFunctionDefinition()) {
7498  // C++ [class.mfct]p2:
7499  // A member function may be defined (8.4) in its class definition, in
7500  // which case it is an inline member function (7.1.2)
7501  NewFD->setImplicitlyInline();
7502  }
7503 
7504  if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7505  !CurContext->isRecord()) {
7506  // C++ [class.static]p1:
7507  // A data or function member of a class may be declared static
7508  // in a class definition, in which case it is a static member of
7509  // the class.
7510 
7511  // Complain about the 'static' specifier if it's on an out-of-line
7512  // member function definition.
7514  diag::err_static_out_of_line)
7516  }
7517 
7518  // C++11 [except.spec]p15:
7519  // A deallocation function with no exception-specification is treated
7520  // as if it were specified with noexcept(true).
7521  const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7522  if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7523  Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7524  getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7526  FPT->getReturnType(), FPT->getParamTypes(),
7528  }
7529 
7530  // Filter out previous declarations that don't match the scope.
7531  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7532  D.getCXXScopeSpec().isNotEmpty() ||
7533  isExplicitSpecialization ||
7534  isFunctionTemplateSpecialization);
7535 
7536  // Handle GNU asm-label extension (encoded as an attribute).
7537  if (Expr *E = (Expr*) D.getAsmLabel()) {
7538  // The parser guarantees this is a string.
7539  StringLiteral *SE = cast<StringLiteral>(E);
7540  NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7541  SE->getString(), 0));
7542  } else if (!ExtnameUndeclaredIdentifiers.empty() &&
7544  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7545  ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7546  if (I != ExtnameUndeclaredIdentifiers.end()) {
7547  NewFD->addAttr(I->second);
7548  ExtnameUndeclaredIdentifiers.erase(I);
7549  }
7550  }
7551 
7552  // Copy the parameter declarations from the declarator D to the function
7553  // declaration NewFD, if they are available. First scavenge them into Params.
7555  if (D.isFunctionDeclarator()) {
7557 
7558  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7559  // function that takes no arguments, not a function that takes a
7560  // single void argument.
7561  // We let through "const void" here because Sema::GetTypeForDeclarator
7562  // already checks for that case.
7563  if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7564  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7565  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7566  assert(Param->getDeclContext() != NewFD && "Was set before ?");
7567  Param->setDeclContext(NewFD);
7568  Params.push_back(Param);
7569 
7570  if (Param->isInvalidDecl())
7571  NewFD->setInvalidDecl();
7572  }
7573  }
7574 
7575  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7576  // When we're declaring a function with a typedef, typeof, etc as in the
7577  // following example, we'll need to synthesize (unnamed)
7578  // parameters for use in the declaration.
7579  //
7580  // @code
7581  // typedef void fn(int);
7582  // fn f;
7583  // @endcode
7584 
7585  // Synthesize a parameter for each argument type.
7586  for (const auto &AI : FT->param_types()) {
7587  ParmVarDecl *Param =
7588  BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7589  Param->setScopeInfo(0, Params.size());
7590  Params.push_back(Param);
7591  }
7592  } else {
7593  assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7594  "Should not need args for typedef of non-prototype fn");
7595  }
7596 
7597  // Finally, we know we have the right number of parameters, install them.
7598  NewFD->setParams(Params);
7599 
7600  // Find all anonymous symbols defined during the declaration of this function
7601  // and add to NewFD. This lets us track decls such 'enum Y' in:
7602  //
7603  // void f(enum Y {AA} x) {}
7604  //
7605  // which would otherwise incorrectly end up in the translation unit scope.
7606  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7607  DeclsInPrototypeScope.clear();
7608 
7609  if (D.getDeclSpec().isNoreturnSpecified())
7610  NewFD->addAttr(
7611  ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7612  Context, 0));
7613 
7614  // Functions returning a variably modified type violate C99 6.7.5.2p2
7615  // because all functions have linkage.
7616  if (!NewFD->isInvalidDecl() &&
7617  NewFD->getReturnType()->isVariablyModifiedType()) {
7618  Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7619  NewFD->setInvalidDecl();
7620  }
7621 
7622  // Apply an implicit SectionAttr if #pragma code_seg is active.
7623  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7624  !NewFD->hasAttr<SectionAttr>()) {
7625  NewFD->addAttr(
7626  SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7627  CodeSegStack.CurrentValue->getString(),
7628  CodeSegStack.CurrentPragmaLocation));
7629  if (UnifySection(CodeSegStack.CurrentValue->getString(),
7632  NewFD))
7633  NewFD->dropAttr<SectionAttr>();
7634  }
7635 
7636  // Handle attributes.
7637  ProcessDeclAttributes(S, NewFD, D);
7638 
7639  if (getLangOpts().OpenCL) {
7640  // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7641  // type declaration will generate a compilation error.
7642  unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7643  if (AddressSpace == LangAS::opencl_local ||
7644  AddressSpace == LangAS::opencl_global ||
7645  AddressSpace == LangAS::opencl_constant) {
7646  Diag(NewFD->getLocation(),
7647  diag::err_opencl_return_value_with_address_space);
7648  NewFD->setInvalidDecl();
7649  }
7650  }
7651 
7652  if (!getLangOpts().CPlusPlus) {
7653  // Perform semantic checking on the function declaration.
7654  bool isExplicitSpecialization=false;
7655  if (!NewFD->isInvalidDecl() && NewFD->isMain())
7656  CheckMain(NewFD, D.getDeclSpec());
7657 
7658  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7659  CheckMSVCRTEntryPoint(NewFD);
7660 
7661  if (!NewFD->isInvalidDecl())
7662  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7663  isExplicitSpecialization));
7664  else if (!Previous.empty())
7665  // Recover gracefully from an invalid redeclaration.
7666  D.setRedeclaration(true);
7667  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7669  "previous declaration set still overloaded");
7670 
7671  // Diagnose no-prototype function declarations with calling conventions that
7672  // don't support variadic calls. Only do this in C and do it after merging
7673  // possibly prototyped redeclarations.
7674  const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7675  if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7676  CallingConv CC = FT->getExtInfo().getCC();
7677  if (!supportsVariadicCall(CC)) {
7678  // Windows system headers sometimes accidentally use stdcall without
7679  // (void) parameters, so we relax this to a warning.
7680  int DiagID =
7681  CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7682  Diag(NewFD->getLocation(), DiagID)
7684  }
7685  }
7686  } else {
7687  // C++11 [replacement.functions]p3:
7688  // The program's definitions shall not be specified as inline.
7689  //
7690  // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7691  //
7692  // Suppress the diagnostic if the function is __attribute__((used)), since
7693  // that forces an external definition to be emitted.
7694  if (D.getDeclSpec().isInlineSpecified() &&
7696  !NewFD->hasAttr<UsedAttr>())
7698  diag::ext_operator_new_delete_declared_inline)
7699  << NewFD->getDeclName();
7700 
7701  // If the declarator is a template-id, translate the parser's template
7702  // argument list into our AST format.
7704  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7705  TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7706  TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7707  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7708  TemplateId->NumArgs);
7709  translateTemplateArguments(TemplateArgsPtr,
7710  TemplateArgs);
7711 
7712  HasExplicitTemplateArgs = true;
7713 
7714  if (NewFD->isInvalidDecl()) {
7715  HasExplicitTemplateArgs = false;
7716  } else if (FunctionTemplate) {
7717  // Function template with explicit template arguments.
7718  Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7719  << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7720 
7721  HasExplicitTemplateArgs = false;
7722  } else {
7723  assert((isFunctionTemplateSpecialization ||
7724  D.getDeclSpec().isFriendSpecified()) &&
7725  "should have a 'template<>' for this decl");
7726  // "friend void foo<>(int);" is an implicit specialization decl.
7727  isFunctionTemplateSpecialization = true;
7728  }
7729  } else if (isFriend && isFunctionTemplateSpecialization) {
7730  // This combination is only possible in a recovery case; the user
7731  // wrote something like:
7732  // template <> friend void foo(int);
7733  // which we're recovering from as if the user had written:
7734  // friend void foo<>(int);
7735  // Go ahead and fake up a template id.
7736  HasExplicitTemplateArgs = true;
7737  TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7738  TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7739  }
7740 
7741  // If it's a friend (and only if it's a friend), it's possible
7742  // that either the specialized function type or the specialized
7743  // template is dependent, and therefore matching will fail. In
7744  // this case, don't check the specialization yet.
7745  bool InstantiationDependent = false;
7746  if (isFunctionTemplateSpecialization && isFriend &&
7747  (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7749  TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7750  InstantiationDependent))) {
7751  assert(HasExplicitTemplateArgs &&
7752  "friend function specialization without template args");
7753  if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7754  Previous))
7755  NewFD->setInvalidDecl();
7756  } else if (isFunctionTemplateSpecialization) {
7757  if (CurContext->isDependentContext() && CurContext->isRecord()
7758  && !isFriend) {
7759  isDependentClassScopeExplicitSpecialization = true;
7760  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7761  diag::ext_function_specialization_in_class :
7762  diag::err_function_specialization_in_class)
7763  << NewFD->getDeclName();
7764  } else if (CheckFunctionTemplateSpecialization(NewFD,
7765  (HasExplicitTemplateArgs ? &TemplateArgs
7766  : nullptr),
7767  Previous))
7768  NewFD->setInvalidDecl();
7769 
7770  // C++ [dcl.stc]p1:
7771  // A storage-class-specifier shall not be specified in an explicit
7772  // specialization (14.7.3)
7775  if (Info && SC != SC_None) {
7776  if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7777  Diag(NewFD->getLocation(),
7778  diag::err_explicit_specialization_inconsistent_storage_class)
7779  << SC
7782 
7783  else
7784  Diag(NewFD->getLocation(),
7785  diag::ext_explicit_specialization_storage_class)
7788  }
7789 
7790  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7791  if (CheckMemberSpecialization(NewFD, Previous))
7792  NewFD->setInvalidDecl();
7793  }
7794 
7795  // Perform semantic checking on the function declaration.
7796  if (!isDependentClassScopeExplicitSpecialization) {
7797  if (!NewFD->isInvalidDecl() && NewFD->isMain())
7798  CheckMain(NewFD, D.getDeclSpec());
7799 
7800  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7801  CheckMSVCRTEntryPoint(NewFD);
7802 
7803  if (!NewFD->isInvalidDecl())
7804  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7805  isExplicitSpecialization));
7806  else if (!Previous.empty())
7807  // Recover gracefully from an invalid redeclaration.
7808  D.setRedeclaration(true);
7809  }
7810 
7811  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7813  "previous declaration set still overloaded");
7814 
7815  NamedDecl *PrincipalDecl = (FunctionTemplate
7816  ? cast<NamedDecl>(FunctionTemplate)
7817  : NewFD);
7818 
7819  if (isFriend && D.isRedeclaration()) {
7820  AccessSpecifier Access = AS_public;
7821  if (!NewFD->isInvalidDecl())
7822  Access = NewFD->getPreviousDecl()->getAccess();
7823 
7824  NewFD->setAccess(Access);
7825  if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7826  }
7827 
7828  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7830  PrincipalDecl->setNonMemberOperator();
7831 
7832  // If we have a function template, check the template parameter
7833  // list. This will check and merge default template arguments.
7834  if (FunctionTemplate) {
7835  FunctionTemplateDecl *PrevTemplate =
7836  FunctionTemplate->getPreviousDecl();
7837  CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7838  PrevTemplate ? PrevTemplate->getTemplateParameters()
7839  : nullptr,
7841  ? (D.isFunctionDefinition()
7842  ? TPC_FriendFunctionTemplateDefinition
7843  : TPC_FriendFunctionTemplate)
7844  : (D.getCXXScopeSpec().isSet() &&
7845  DC && DC->isRecord() &&
7846  DC->isDependentContext())
7847  ? TPC_ClassTemplateMember
7848  : TPC_FunctionTemplate);
7849  }
7850 
7851  if (NewFD->isInvalidDecl()) {
7852  // Ignore all the rest of this.
7853  } else if (!D.isRedeclaration()) {
7854  struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7855  AddToScope };
7856  // Fake up an access specifier if it's supposed to be a class member.
7857  if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7858  NewFD->setAccess(AS_public);
7859 
7860  // Qualified decls generally require a previous declaration.
7861  if (D.getCXXScopeSpec().isSet()) {
7862  // ...with the major exception of templated-scope or
7863  // dependent-scope friend declarations.
7864 
7865  // TODO: we currently also suppress this check in dependent
7866  // contexts because (1) the parameter depth will be off when
7867  // matching friend templates and (2) we might actually be
7868  // selecting a friend based on a dependent factor. But there
7869  // are situations where these conditions don't apply and we
7870  // can actually do this check immediately.
7871  if (isFriend &&
7872  (TemplateParamLists.size() ||
7874  CurContext->isDependentContext())) {
7875  // ignore these
7876  } else {
7877  // The user tried to provide an out-of-line definition for a
7878  // function that is a member of a class or namespace, but there
7879  // was no such member function declared (C++ [class.mfct]p2,
7880  // C++ [namespace.memdef]p2). For example:
7881  //
7882  // class X {
7883  // void f() const;
7884  // };
7885  //
7886  // void X::f() { } // ill-formed
7887  //
7888  // Complain about this problem, and attempt to suggest close
7889  // matches (e.g., those that differ only in cv-qualifiers and
7890  // whether the parameter types are references).
7891 
7893  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
7894  AddToScope = ExtraArgs.AddToScope;
7895  return Result;
7896  }
7897  }
7898 
7899  // Unqualified local friend declarations are required to resolve
7900  // to something.
7901  } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7903  *this, Previous, NewFD, ExtraArgs, true, S)) {
7904  AddToScope = ExtraArgs.AddToScope;
7905  return Result;
7906  }
7907  }
7908 
7909  } else if (!D.isFunctionDefinition() &&
7910  isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7911  !isFriend && !isFunctionTemplateSpecialization &&
7912  !isExplicitSpecialization) {
7913  // An out-of-line member function declaration must also be a
7914  // definition (C++ [class.mfct]p2).
7915  // Note that this is not the case for explicit specializations of
7916  // function templates or member functions of class templates, per
7917  // C++ [temp.expl.spec]p2. We also allow these declarations as an
7918  // extension for compatibility with old SWIG code which likes to
7919  // generate them.
7920  Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7921  << D.getCXXScopeSpec().getRange();
7922  }
7923  }
7924 
7925  ProcessPragmaWeak(S, NewFD);
7926  checkAttributesAfterMerging(*this, *NewFD);
7927 
7928  AddKnownFunctionAttributes(NewFD);
7929 
7930  if (NewFD->hasAttr<OverloadableAttr>() &&
7931  !NewFD->getType()->getAs<FunctionProtoType>()) {
7932  Diag(NewFD->getLocation(),
7933  diag::err_attribute_overloadable_no_prototype)
7934  << NewFD;
7935 
7936  // Turn this into a variadic function with no parameters.
7937  const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7939  Context.getDefaultCallingConvention(true, false));
7940  EPI.Variadic = true;
7941  EPI.ExtInfo = FT->getExtInfo();
7942 
7943  QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7944  NewFD->setType(R);
7945  }
7946 
7947  // If there's a #pragma GCC visibility in scope, and this isn't a class
7948  // member, set the visibility of this function.
7949  if (!DC->isRecord() && NewFD->isExternallyVisible())
7950  AddPushedVisibilityAttribute(NewFD);
7951 
7952  // If there's a #pragma clang arc_cf_code_audited in scope, consider
7953  // marking the function.
7954  AddCFAuditedAttribute(NewFD);
7955 
7956  // If this is a function definition, check if we have to apply optnone due to
7957  // a pragma.
7958  if(D.isFunctionDefinition())
7959  AddRangeBasedOptnone(NewFD);
7960 
7961  // If this is the first declaration of an extern C variable, update
7962  // the map of such variables.
7963  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7964  isIncompleteDeclExternC(*this, NewFD))
7965  RegisterLocallyScopedExternCDecl(NewFD, S);
7966 
7967  // Set this FunctionDecl's range up to the right paren.
7968  NewFD->setRangeEnd(D.getSourceRange().getEnd());
7969 
7970  if (D.isRedeclaration() && !Previous.empty()) {
7972  *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7973  isExplicitSpecialization || isFunctionTemplateSpecialization);
7974  }
7975 
7976  if (getLangOpts().CPlusPlus) {
7977  if (FunctionTemplate) {
7978  if (NewFD->isInvalidDecl())
7979  FunctionTemplate->setInvalidDecl();
7980  return FunctionTemplate;
7981  }
7982  }
7983 
7984  if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7985  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7986  if ((getLangOpts().OpenCLVersion >= 120)
7987  && (SC == SC_Static)) {
7988  Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7989  D.setInvalidType();
7990  }
7991 
7992  // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7993  if (!NewFD->getReturnType()->isVoidType()) {
7994  SourceRange RTRange = NewFD->getReturnTypeSourceRange();
7995  Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
7996  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
7997  : FixItHint());
7998  D.setInvalidType();
7999  }
8000 
8001  llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8002  for (auto Param : NewFD->params())
8003  checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8004  }
8005 
8006  MarkUnusedFileScopedDecl(NewFD);
8007 
8008  if (getLangOpts().CUDA)
8009  if (IdentifierInfo *II = NewFD->getIdentifier())
8010  if (!NewFD->isInvalidDecl() &&
8012  if (II->isStr("cudaConfigureCall")) {
8013  if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8014  Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8015 
8017  }
8018  }
8019 
8020  // Here we have an function template explicit specialization at class scope.
8021  // The actually specialization will be postponed to template instatiation
8022  // time via the ClassScopeFunctionSpecializationDecl node.
8023  if (isDependentClassScopeExplicitSpecialization) {
8026  Context, CurContext, SourceLocation(),
8027  cast<CXXMethodDecl>(NewFD),
8028  HasExplicitTemplateArgs, TemplateArgs);
8029  CurContext->addDecl(NewSpec);
8030  AddToScope = false;
8031  }
8032 
8033  return NewFD;
8034 }
8035 
8036 /// \brief Perform semantic checking of a new function declaration.
8037 ///
8038 /// Performs semantic analysis of the new function declaration
8039 /// NewFD. This routine performs all semantic checking that does not
8040 /// require the actual declarator involved in the declaration, and is
8041 /// used both for the declaration of functions as they are parsed
8042 /// (called via ActOnDeclarator) and for the declaration of functions
8043 /// that have been instantiated via C++ template instantiation (called
8044 /// via InstantiateDecl).
8045 ///
8046 /// \param IsExplicitSpecialization whether this new function declaration is
8047 /// an explicit specialization of the previous declaration.
8048 ///
8049 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8050 ///
8051 /// \returns true if the function declaration is a redeclaration.
8054  bool IsExplicitSpecialization) {
8055  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8056  "Variably modified return types are not handled here");
8057 
8058  // Determine whether the type of this function should be merged with
8059  // a previous visible declaration. This never happens for functions in C++,
8060  // and always happens in C if the previous declaration was visible.
8061  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8062  !Previous.isShadowed();
8063 
8064  // Filter out any non-conflicting previous declarations.
8065  filterNonConflictingPreviousDecls(*this, NewFD, Previous);
8066 
8067  bool Redeclaration = false;
8068  NamedDecl *OldDecl = nullptr;
8069 
8070  // Merge or overload the declaration with an existing declaration of
8071  // the same name, if appropriate.
8072  if (!Previous.empty()) {
8073  // Determine whether NewFD is an overload of PrevDecl or
8074  // a declaration that requires merging. If it's an overload,
8075  // there's no more work to do here; we'll just add the new
8076  // function to the scope.
8077  if (!AllowOverloadingOfFunction(Previous, Context)) {
8078  NamedDecl *Candidate = Previous.getFoundDecl();
8079  if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8080  Redeclaration = true;
8081  OldDecl = Candidate;
8082  }
8083  } else {
8084  switch (CheckOverload(S, NewFD, Previous, OldDecl,
8085  /*NewIsUsingDecl*/ false)) {
8086  case Ovl_Match:
8087  Redeclaration = true;
8088  break;
8089 
8090  case Ovl_NonFunction:
8091  Redeclaration = true;
8092  break;
8093 
8094  case Ovl_Overload:
8095  Redeclaration = false;
8096  break;
8097  }
8098 
8099  if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8100  // If a function name is overloadable in C, then every function
8101  // with that name must be marked "overloadable".
8102  Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8103  << Redeclaration << NewFD;
8104  NamedDecl *OverloadedDecl = nullptr;
8105  if (Redeclaration)
8106  OverloadedDecl = OldDecl;
8107  else if (!Previous.empty())
8108  OverloadedDecl = Previous.getRepresentativeDecl();
8109  if (OverloadedDecl)
8110  Diag(OverloadedDecl->getLocation(),
8111  diag::note_attribute_overloadable_prev_overload);
8112  NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8113  }
8114  }
8115  }
8116 
8117  // Check for a previous extern "C" declaration with this name.
8118  if (!Redeclaration &&
8119  checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8120  filterNonConflictingPreviousDecls(*this, NewFD, Previous);
8121  if (!Previous.empty()) {
8122  // This is an extern "C" declaration with the same name as a previous
8123  // declaration, and thus redeclares that entity...
8124  Redeclaration = true;
8125  OldDecl = Previous.getFoundDecl();
8126  MergeTypeWithPrevious = false;
8127 
8128  // ... except in the presence of __attribute__((overloadable)).
8129  if (OldDecl->hasAttr<OverloadableAttr>()) {
8130  if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8131  Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8132  << Redeclaration << NewFD;
8133  Diag(Previous.getFoundDecl()->getLocation(),
8134  diag::note_attribute_overloadable_prev_overload);
8135  NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8136  }
8137  if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8138  Redeclaration = false;
8139  OldDecl = nullptr;
8140  }
8141  }
8142  }
8143  }
8144 
8145  // C++11 [dcl.constexpr]p8:
8146  // A constexpr specifier for a non-static member function that is not
8147  // a constructor declares that member function to be const.
8148  //
8149  // This needs to be delayed until we know whether this is an out-of-line
8150  // definition of a static member function.
8151  //
8152  // This rule is not present in C++1y, so we produce a backwards
8153  // compatibility warning whenever it happens in C++11.
8154  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8155  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8156  !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8157  (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8158  CXXMethodDecl *OldMD = nullptr;
8159  if (OldDecl)
8160  OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8161  if (!OldMD || !OldMD->isStatic()) {
8162  const FunctionProtoType *FPT =
8163  MD->getType()->castAs<FunctionProtoType>();
8167  FPT->getParamTypes(), EPI));
8168 
8169  // Warn that we did this, if we're not performing template instantiation.
8170  // In that case, we'll have warned already when the template was defined.
8171  if (ActiveTemplateInstantiations.empty()) {
8172  SourceLocation AddConstLoc;
8173  if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8175  AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8176 
8177  Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8178  << FixItHint::CreateInsertion(AddConstLoc, " const");
8179  }
8180  }
8181  }
8182 
8183  if (Redeclaration) {
8184  // NewFD and OldDecl represent declarations that need to be
8185  // merged.
8186  if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8187  NewFD->setInvalidDecl();
8188  return Redeclaration;
8189  }
8190 
8191  Previous.clear();
8192  Previous.addDecl(OldDecl);
8193 
8194  if (FunctionTemplateDecl *OldTemplateDecl
8195  = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8196  NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8197  FunctionTemplateDecl *NewTemplateDecl
8198  = NewFD->getDescribedFunctionTemplate();
8199  assert(NewTemplateDecl && "Template/non-template mismatch");
8200  if (CXXMethodDecl *Method
8201  = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8202  Method->setAccess(OldTemplateDecl->getAccess());
8203  NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8204  }
8205 
8206  // If this is an explicit specialization of a member that is a function
8207  // template, mark it as a member specialization.
8208  if (IsExplicitSpecialization &&
8209  NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8210  NewTemplateDecl->setMemberSpecialization();
8211  assert(OldTemplateDecl->isMemberSpecialization());
8212  }
8213 
8214  } else {
8215  // This needs to happen first so that 'inline' propagates.
8216  NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8217 
8218  if (isa<CXXMethodDecl>(NewFD))
8219  NewFD->setAccess(OldDecl->getAccess());
8220  }
8221  }
8222 
8223  // Semantic checking for this function declaration (in isolation).
8224 
8225  if (getLangOpts().CPlusPlus) {
8226  // C++-specific checks.
8227  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8228  CheckConstructor(Constructor);
8229  } else if (CXXDestructorDecl *Destructor =
8230  dyn_cast<CXXDestructorDecl>(NewFD)) {
8231  CXXRecordDecl *Record = Destructor->getParent();
8232  QualType ClassType = Context.getTypeDeclType(Record);
8233 
8234  // FIXME: Shouldn't we be able to perform this check even when the class
8235  // type is dependent? Both gcc and edg can handle that.
8236  if (!ClassType->isDependentType()) {
8237  DeclarationName Name
8239  Context.getCanonicalType(ClassType));
8240  if (NewFD->getDeclName() != Name) {
8241  Diag(NewFD->getLocation(), diag::err_destructor_name);
8242  NewFD->setInvalidDecl();
8243  return Redeclaration;
8244  }
8245  }
8246  } else if (CXXConversionDecl *Conversion
8247  = dyn_cast<CXXConversionDecl>(NewFD)) {
8248  ActOnConversionDeclarator(Conversion);
8249  }
8250 
8251  // Find any virtual functions that this function overrides.
8252  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8253  if (!Method->isFunctionTemplateSpecialization() &&
8254  !Method->getDescribedFunctionTemplate() &&
8255  Method->isCanonicalDecl()) {
8256  if (AddOverriddenMethods(Method->getParent(), Method)) {
8257  // If the function was marked as "static", we have a problem.
8258  if (NewFD->getStorageClass() == SC_Static) {
8259  ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8260  }
8261  }
8262  }
8263 
8264  if (Method->isStatic())
8265  checkThisInStaticMemberFunctionType(Method);
8266  }
8267 
8268  // Extra checking for C++ overloaded operators (C++ [over.oper]).
8269  if (NewFD->isOverloadedOperator() &&
8270  CheckOverloadedOperatorDeclaration(NewFD)) {
8271  NewFD->setInvalidDecl();
8272  return Redeclaration;
8273  }
8274 
8275  // Extra checking for C++0x literal operators (C++0x [over.literal]).
8276  if (NewFD->getLiteralIdentifier() &&
8277  CheckLiteralOperatorDeclaration(NewFD)) {
8278  NewFD->setInvalidDecl();
8279  return Redeclaration;
8280  }
8281 
8282  // In C++, check default arguments now that we have merged decls. Unless
8283  // the lexical context is the class, because in this case this is done
8284  // during delayed parsing anyway.
8285  if (!CurContext->isRecord())
8286  CheckCXXDefaultArguments(NewFD);
8287 
8288  // If this function declares a builtin function, check the type of this
8289  // declaration against the expected type for the builtin.
8290  if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8292  LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8293  QualType T = Context.GetBuiltinType(BuiltinID, Error);
8294  if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8295  // The type of this function differs from the type of the builtin,
8296  // so forget about the builtin entirely.
8298  }
8299  }
8300 
8301  // If this function is declared as being extern "C", then check to see if
8302  // the function returns a UDT (class, struct, or union type) that is not C
8303  // compatible, and if it does, warn the user.
8304  // But, issue any diagnostic on the first declaration only.
8305  if (Previous.empty() && NewFD->isExternC()) {
8306  QualType R = NewFD->getReturnType();
8307  if (R->isIncompleteType() && !R->isVoidType())
8308  Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8309  << NewFD << R;
8310  else if (!R.isPODType(Context) && !R->isVoidType() &&
8312  Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8313  }
8314  }
8315  return Redeclaration;
8316 }
8317 
8318 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8319  // C++11 [basic.start.main]p3:
8320  // A program that [...] declares main to be inline, static or
8321  // constexpr is ill-formed.
8322  // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8323  // appear in a declaration of main.
8324  // static main is not an error under C99, but we should warn about it.
8325  // We accept _Noreturn main as an extension.
8326  if (FD->getStorageClass() == SC_Static)
8327  Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8328  ? diag::err_static_main : diag::warn_static_main)
8330  if (FD->isInlineSpecified())
8331  Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8333  if (DS.isNoreturnSpecified()) {
8334  SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8335  SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8336  Diag(NoreturnLoc, diag::ext_noreturn_main);
8337  Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8338  << FixItHint::CreateRemoval(NoreturnRange);
8339  }
8340  if (FD->isConstexpr()) {
8341  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8343  FD->setConstexpr(false);
8344  }
8345 
8346  if (getLangOpts().OpenCL) {
8347  Diag(FD->getLocation(), diag::err_opencl_no_main)
8348  << FD->hasAttr<OpenCLKernelAttr>();
8349  FD->setInvalidDecl();
8350  return;
8351  }
8352 
8353  QualType T = FD->getType();
8354  assert(T->isFunctionType() && "function decl is not of function type");
8355  const FunctionType* FT = T->castAs<FunctionType>();
8356 
8357  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8358  // In C with GNU extensions we allow main() to have non-integer return
8359  // type, but we should warn about the extension, and we disable the
8360  // implicit-return-zero rule.
8361 
8362  // GCC in C mode accepts qualified 'int'.
8363  if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8364  FD->setHasImplicitReturnZero(true);
8365  else {
8366  Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8367  SourceRange RTRange = FD->getReturnTypeSourceRange();
8368  if (RTRange.isValid())
8369  Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8370  << FixItHint::CreateReplacement(RTRange, "int");
8371  }
8372  } else {
8373  // In C and C++, main magically returns 0 if you fall off the end;
8374  // set the flag which tells us that.
8375  // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8376 
8377  // All the standards say that main() should return 'int'.
8378  if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8379  FD->setHasImplicitReturnZero(true);
8380  else {
8381  // Otherwise, this is just a flat-out error.
8382  SourceRange RTRange = FD->getReturnTypeSourceRange();
8383  Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8384  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8385  : FixItHint());
8386  FD->setInvalidDecl(true);
8387  }
8388  }
8389 
8390  // Treat protoless main() as nullary.
8391  if (isa<FunctionNoProtoType>(FT)) return;
8392 
8393  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8394  unsigned nparams = FTP->getNumParams();
8395  assert(FD->getNumParams() == nparams);
8396 
8397  bool HasExtraParameters = (nparams > 3);
8398 
8399  if (FTP->isVariadic()) {
8400  Diag(FD->getLocation(), diag::ext_variadic_main);
8401  // FIXME: if we had information about the location of the ellipsis, we
8402  // could add a FixIt hint to remove it as a parameter.
8403  }
8404 
8405  // Darwin passes an undocumented fourth argument of type char**. If
8406  // other platforms start sprouting these, the logic below will start
8407  // getting shifty.
8408  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8409  HasExtraParameters = false;
8410 
8411  if (HasExtraParameters) {
8412  Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8413  FD->setInvalidDecl(true);
8414  nparams = 3;
8415  }
8416 
8417  // FIXME: a lot of the following diagnostics would be improved
8418  // if we had some location information about types.
8419 
8420  QualType CharPP =
8422  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8423 
8424  for (unsigned i = 0; i < nparams; ++i) {
8425  QualType AT = FTP->getParamType(i);
8426 
8427  bool mismatch = true;
8428 
8429  if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8430  mismatch = false;
8431  else if (Expected[i] == CharPP) {
8432  // As an extension, the following forms are okay:
8433  // char const **
8434  // char const * const *
8435  // char * const *
8436 
8437  QualifierCollector qs;
8438  const PointerType* PT;
8439  if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8440  (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8442  Context.CharTy)) {
8443  qs.removeConst();
8444  mismatch = !qs.empty();
8445  }
8446  }
8447 
8448  if (mismatch) {
8449  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8450  // TODO: suggest replacing given type with expected type
8451  FD->setInvalidDecl(true);
8452  }
8453  }
8454 
8455  if (nparams == 1 && !FD->isInvalidDecl()) {
8456  Diag(FD->getLocation(), diag::warn_main_one_arg);
8457  }
8458 
8459  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8460  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8461  FD->setInvalidDecl();
8462  }
8463 }
8464 
8466  QualType T = FD->getType();
8467  assert(T->isFunctionType() && "function decl is not of function type");
8468  const FunctionType *FT = T->castAs<FunctionType>();
8469 
8470  // Set an implicit return of 'zero' if the function can return some integral,
8471  // enumeration, pointer or nullptr type.
8472  if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8473  FT->getReturnType()->isAnyPointerType() ||
8474  FT->getReturnType()->isNullPtrType())
8475  // DllMain is exempt because a return value of zero means it failed.
8476  if (FD->getName() != "DllMain")
8477  FD->setHasImplicitReturnZero(true);
8478 
8479  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8480  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8481  FD->setInvalidDecl();
8482  }
8483 }
8484 
8486  // FIXME: Need strict checking. In C89, we need to check for
8487  // any assignment, increment, decrement, function-calls, or
8488  // commas outside of a sizeof. In C99, it's the same list,
8489  // except that the aforementioned are allowed in unevaluated
8490  // expressions. Everything else falls under the
8491  // "may accept other forms of constant expressions" exception.
8492  // (We never end up here for C++, so the constant expression
8493  // rules there don't matter.)
8494  const Expr *Culprit;
8495  if (Init->isConstantInitializer(Context, false, &Culprit))
8496  return false;
8497  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8498  << Culprit->getSourceRange();
8499  return true;
8500 }
8501 
8502 namespace {
8503  // Visits an initialization expression to see if OrigDecl is evaluated in
8504  // its own initialization and throws a warning if it does.
8505  class SelfReferenceChecker
8506  : public EvaluatedExprVisitor<SelfReferenceChecker> {
8507  Sema &S;
8508  Decl *OrigDecl;
8509  bool isRecordType;
8510  bool isPODType;
8511  bool isReferenceType;
8512 
8513  bool isInitList;
8514  llvm::SmallVector<unsigned, 4> InitFieldIndex;
8515  public:
8517 
8518  SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8519  S(S), OrigDecl(OrigDecl) {
8520  isPODType = false;
8521  isRecordType = false;
8522  isReferenceType = false;
8523  isInitList = false;
8524  if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8525  isPODType = VD->getType().isPODType(S.Context);
8526  isRecordType = VD->getType()->isRecordType();
8527  isReferenceType = VD->getType()->isReferenceType();
8528  }
8529  }
8530 
8531  // For most expressions, just call the visitor. For initializer lists,
8532  // track the index of the field being initialized since fields are
8533  // initialized in order allowing use of previously initialized fields.
8534  void CheckExpr(Expr *E) {
8535  InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8536  if (!InitList) {
8537  Visit(E);
8538  return;
8539  }
8540 
8541  // Track and increment the index here.
8542  isInitList = true;
8543  InitFieldIndex.push_back(0);
8544  for (auto Child : InitList->children()) {
8545  CheckExpr(cast<Expr>(Child));
8546  ++InitFieldIndex.back();
8547  }
8548  InitFieldIndex.pop_back();
8549  }
8550 
8551  // Returns true if MemberExpr is checked and no futher checking is needed.
8552  // Returns false if additional checking is required.
8553  bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8555  Expr *Base = E;
8556  bool ReferenceField = false;
8557 
8558  // Get the field memebers used.
8559  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8560  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8561  if (!FD)
8562  return false;
8563  Fields.push_back(FD);
8564  if (FD->getType()->isReferenceType())
8565  ReferenceField = true;
8566  Base = ME->getBase()->IgnoreParenImpCasts();
8567  }
8568 
8569  // Keep checking only if the base Decl is the same.
8570  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8571  if (!DRE || DRE->getDecl() != OrigDecl)
8572  return false;
8573 
8574  // A reference field can be bound to an unininitialized field.
8575  if (CheckReference && !ReferenceField)
8576  return true;
8577 
8578  // Convert FieldDecls to their index number.
8579  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8580  for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) {
8581  UsedFieldIndex.push_back((*I)->getFieldIndex());
8582  }
8583 
8584  // See if a warning is needed by checking the first difference in index
8585  // numbers. If field being used has index less than the field being
8586  // initialized, then the use is safe.
8587  for (auto UsedIter = UsedFieldIndex.begin(),
8588  UsedEnd = UsedFieldIndex.end(),
8589  OrigIter = InitFieldIndex.begin(),
8590  OrigEnd = InitFieldIndex.end();
8591  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8592  if (*UsedIter < *OrigIter)
8593  return true;
8594  if (*UsedIter > *OrigIter)
8595  break;
8596  }
8597 
8598  // TODO: Add a different warning which will print the field names.
8599  HandleDeclRefExpr(DRE);
8600  return true;
8601  }
8602 
8603  // For most expressions, the cast is directly above the DeclRefExpr.
8604  // For conditional operators, the cast can be outside the conditional
8605  // operator if both expressions are DeclRefExpr's.
8606  void HandleValue(Expr *E) {
8607  E = E->IgnoreParens();
8608  if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8609  HandleDeclRefExpr(DRE);
8610  return;
8611  }
8612 
8613  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8614  Visit(CO->getCond());
8615  HandleValue(CO->getTrueExpr());
8616  HandleValue(CO->getFalseExpr());
8617  return;
8618  }
8619 
8620  if (BinaryConditionalOperator *BCO =
8621  dyn_cast<BinaryConditionalOperator>(E)) {
8622  Visit(BCO->getCond());
8623  HandleValue(BCO->getFalseExpr());
8624  return;
8625  }
8626 
8627  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8628  HandleValue(OVE->getSourceExpr());
8629  return;
8630  }
8631 
8632  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8633  if (BO->getOpcode() == BO_Comma) {
8634  Visit(BO->getLHS());
8635  HandleValue(BO->getRHS());
8636  return;
8637  }
8638  }
8639 
8640  if (isa<MemberExpr>(E)) {
8641  if (isInitList) {
8642  if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8643  false /*CheckReference*/))
8644  return;
8645  }
8646 
8647  Expr *Base = E->IgnoreParenImpCasts();
8648  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8649  // Check for static member variables and don't warn on them.
8650  if (!isa<FieldDecl>(ME->getMemberDecl()))
8651  return;
8652  Base = ME->getBase()->IgnoreParenImpCasts();
8653  }
8654  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8655  HandleDeclRefExpr(DRE);
8656  return;
8657  }
8658 
8659  Visit(E);
8660  }
8661 
8662  // Reference types not handled in HandleValue are handled here since all
8663  // uses of references are bad, not just r-value uses.
8664  void VisitDeclRefExpr(DeclRefExpr *E) {
8665  if (isReferenceType)
8666  HandleDeclRefExpr(E);
8667  }
8668 
8669  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8670  if (E->getCastKind() == CK_LValueToRValue) {
8671  HandleValue(E->getSubExpr());
8672  return;
8673  }
8674 
8675  Inherited::VisitImplicitCastExpr(E);
8676  }
8677 
8678  void VisitMemberExpr(MemberExpr *E) {
8679  if (isInitList) {
8680  if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8681  return;
8682  }
8683 
8684  // Don't warn on arrays since they can be treated as pointers.
8685  if (E->getType()->canDecayToPointerType()) return;
8686 
8687  // Warn when a non-static method call is followed by non-static member
8688  // field accesses, which is followed by a DeclRefExpr.
8689  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8690  bool Warn = (MD && !MD->isStatic());
8691  Expr *Base = E->getBase()->IgnoreParenImpCasts();
8692  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8693  if (!isa<FieldDecl>(ME->getMemberDecl()))
8694  Warn = false;
8695  Base = ME->getBase()->IgnoreParenImpCasts();
8696  }
8697 
8698  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8699  if (Warn)
8700  HandleDeclRefExpr(DRE);
8701  return;
8702  }
8703 
8704  // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8705  // Visit that expression.
8706  Visit(Base);
8707  }
8708 
8709  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8710  Expr *Callee = E->getCallee();
8711 
8712  if (isa<UnresolvedLookupExpr>(Callee))
8713  return Inherited::VisitCXXOperatorCallExpr(E);
8714 
8715  Visit(Callee);
8716  for (auto Arg: E->arguments())
8717  HandleValue(Arg->IgnoreParenImpCasts());
8718  }
8719 
8720  void VisitUnaryOperator(UnaryOperator *E) {
8721  // For POD record types, addresses of its own members are well-defined.
8722  if (E->getOpcode() == UO_AddrOf && isRecordType &&
8723  isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8724  if (!isPODType)
8725  HandleValue(E->getSubExpr());
8726  return;
8727  }
8728 
8729  if (E->isIncrementDecrementOp()) {
8730  HandleValue(E->getSubExpr());
8731  return;
8732  }
8733 
8734  Inherited::VisitUnaryOperator(E);
8735  }
8736 
8737  void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8738 
8739  void VisitCXXConstructExpr(CXXConstructExpr *E) {
8740  if (E->getConstructor()->isCopyConstructor()) {
8741  Expr *ArgExpr = E->getArg(0);
8742  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8743  if (ILE->getNumInits() == 1)
8744  ArgExpr = ILE->getInit(0);
8745  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8746  if (ICE->getCastKind() == CK_NoOp)
8747  ArgExpr = ICE->getSubExpr();
8748  HandleValue(ArgExpr);
8749  return;
8750  }
8751  Inherited::VisitCXXConstructExpr(E);
8752  }
8753 
8754  void VisitCallExpr(CallExpr *E) {
8755  // Treat std::move as a use.
8756  if (E->getNumArgs() == 1) {
8757  if (FunctionDecl *FD = E->getDirectCallee()) {
8758  if (FD->isInStdNamespace() && FD->getIdentifier() &&
8759  FD->getIdentifier()->isStr("move")) {
8760  HandleValue(E->getArg(0));
8761  return;
8762  }
8763  }
8764  }
8765 
8766  Inherited::VisitCallExpr(E);
8767  }
8768 
8769  void VisitBinaryOperator(BinaryOperator *E) {
8770  if (E->isCompoundAssignmentOp()) {
8771  HandleValue(E->getLHS());
8772  Visit(E->getRHS());
8773  return;
8774  }
8775 
8776  Inherited::VisitBinaryOperator(E);
8777  }
8778 
8779  // A custom visitor for BinaryConditionalOperator is needed because the
8780  // regular visitor would check the condition and true expression separately
8781  // but both point to the same place giving duplicate diagnostics.
8782  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8783  Visit(E->getCond());
8784  Visit(E->getFalseExpr());
8785  }
8786 
8787  void HandleDeclRefExpr(DeclRefExpr *DRE) {
8788  Decl* ReferenceDecl = DRE->getDecl();
8789  if (OrigDecl != ReferenceDecl) return;
8790  unsigned diag;
8791  if (isReferenceType) {
8792  diag = diag::warn_uninit_self_reference_in_reference_init;
8793  } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8794  diag = diag::warn_static_self_reference_in_init;
8795  } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
8796  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
8797  DRE->getDecl()->getType()->isRecordType()) {
8798  diag = diag::warn_uninit_self_reference_in_init;
8799  } else {
8800  // Local variables will be handled by the CFG analysis.
8801  return;
8802  }
8803 
8804  S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8805  S.PDiag(diag)
8806  << DRE->getNameInfo().getName()
8807  << OrigDecl->getLocation()
8808  << DRE->getSourceRange());
8809  }
8810  };
8811 
8812  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8813  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8814  bool DirectInit) {
8815  // Parameters arguments are occassionially constructed with itself,
8816  // for instance, in recursive functions. Skip them.
8817  if (isa<ParmVarDecl>(OrigDecl))
8818  return;
8819 
8820  E = E->IgnoreParens();
8821 
8822  // Skip checking T a = a where T is not a record or reference type.
8823  // Doing so is a way to silence uninitialized warnings.
8824  if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8825  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8826  if (ICE->getCastKind() == CK_LValueToRValue)
8827  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8828  if (DRE->getDecl() == OrigDecl)
8829  return;
8830 
8831  SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
8832  }
8833 }
8834 
8835 /// AddInitializerToDecl - Adds the initializer Init to the
8836 /// declaration dcl. If DirectInit is true, this is C++ direct
8837 /// initialization rather than copy initialization.
8838 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8839  bool DirectInit, bool TypeMayContainAuto) {
8840  // If there is no declaration, there was an error parsing it. Just ignore
8841  // the initializer.
8842  if (!RealDecl || RealDecl->isInvalidDecl()) {
8843  CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
8844  return;
8845  }
8846 
8847  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8848  // Pure-specifiers are handled in ActOnPureSpecifier.
8849  Diag(Method->getLocation(), diag::err_member_function_initialization)
8850  << Method->getDeclName() << Init->getSourceRange();
8851  Method->setInvalidDecl();
8852  return;
8853  }
8854 
8855  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8856  if (!VDecl) {
8857  assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8858  Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8859  RealDecl->setInvalidDecl();
8860  return;
8861  }
8862  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8863 
8864  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8865  if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8866  // Attempt typo correction early so that the type of the init expression can
8867  // be deduced based on the chosen correction:if the original init contains a
8868  // TypoExpr.
8869  ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
8870  if (!Res.isUsable()) {
8871  RealDecl->setInvalidDecl();
8872  return;
8873  }
8874 
8875  if (Res.get() != Init) {
8876  Init = Res.get();
8877  if (CXXDirectInit)
8878  CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8879  }
8880 
8881  Expr *DeduceInit = Init;
8882  // Initializer could be a C++ direct-initializer. Deduction only works if it
8883  // contains exactly one expression.
8884  if (CXXDirectInit) {
8885  if (CXXDirectInit->getNumExprs() == 0) {
8886  // It isn't possible to write this directly, but it is possible to
8887  // end up in this situation with "auto x(some_pack...);"
8888  Diag(CXXDirectInit->getLocStart(),
8889  VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8890  : diag::err_auto_var_init_no_expression)
8891  << VDecl->getDeclName() << VDecl->getType()
8892  << VDecl->getSourceRange();
8893  RealDecl->setInvalidDecl();
8894  return;
8895  } else if (CXXDirectInit->getNumExprs() > 1) {
8896  Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8897  VDecl->isInitCapture()
8898  ? diag::err_init_capture_multiple_expressions
8899  : diag::err_auto_var_init_multiple_expressions)
8900  << VDecl->getDeclName() << VDecl->getType()
8901  << VDecl->getSourceRange();
8902  RealDecl->setInvalidDecl();
8903  return;
8904  } else {
8905  DeduceInit = CXXDirectInit->getExpr(0);
8906  if (isa<InitListExpr>(DeduceInit))
8907  Diag(CXXDirectInit->getLocStart(),
8908  diag::err_auto_var_init_paren_braces)
8909  << VDecl->getDeclName() << VDecl->getType()
8910  << VDecl->getSourceRange();
8911  }
8912  }
8913 
8914  // Expressions default to 'id' when we're in a debugger.
8915  bool DefaultedToAuto = false;
8916  if (getLangOpts().DebuggerCastResultToId &&
8917  Init->getType() == Context.UnknownAnyTy) {
8918  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8919  if (Result.isInvalid()) {
8920  VDecl->setInvalidDecl();
8921  return;
8922  }
8923  Init = Result.get();
8924  DefaultedToAuto = true;
8925  }
8926 
8927  QualType DeducedType;
8928  if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8929  DAR_Failed)
8930  DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8931  if (DeducedType.isNull()) {
8932  RealDecl->setInvalidDecl();
8933  return;
8934  }
8935  VDecl->setType(DeducedType);
8936  assert(VDecl->isLinkageValid());
8937 
8938  // In ARC, infer lifetime.
8939  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8940  VDecl->setInvalidDecl();
8941 
8942  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8943  // 'id' instead of a specific object type prevents most of our usual checks.
8944  // We only want to warn outside of template instantiations, though:
8945  // inside a template, the 'id' could have come from a parameter.
8946  if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8947  DeducedType->isObjCIdType()) {
8948  SourceLocation Loc =
8950  Diag(Loc, diag::warn_auto_var_is_id)
8951  << VDecl->getDeclName() << DeduceInit->getSourceRange();
8952  }
8953 
8954  // If this is a redeclaration, check that the type we just deduced matches
8955  // the previously declared type.
8956  if (VarDecl *Old = VDecl->getPreviousDecl()) {
8957  // We never need to merge the type, because we cannot form an incomplete
8958  // array of auto, nor deduce such a type.
8959  MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8960  }
8961 
8962  // Check the deduced type is valid for a variable declaration.
8963  CheckVariableDeclarationType(VDecl);
8964  if (VDecl->isInvalidDecl())
8965  return;
8966 
8967  // If all looks well, warn if this is a case that will change meaning when
8968  // we implement N3922.
8969  if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) {
8970  Diag(Init->getLocStart(),
8971  diag::warn_auto_var_direct_list_init)
8972  << FixItHint::CreateInsertion(Init->getLocStart(), "=");
8973  }
8974  }
8975 
8976  // dllimport cannot be used on variable definitions.
8977  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8978  Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8979  VDecl->setInvalidDecl();
8980  return;
8981  }
8982 
8983  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8984  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8985  Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8986  VDecl->setInvalidDecl();
8987  return;
8988  }
8989 
8990  if (!VDecl->getType()->isDependentType()) {
8991  // A definition must end up with a complete type, which means it must be
8992  // complete with the restriction that an array type might be completed by
8993  // the initializer; note that later code assumes this restriction.
8994  QualType BaseDeclType = VDecl->getType();
8995  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8996  BaseDeclType = Array->getElementType();
8997  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8998  diag::err_typecheck_decl_incomplete_type)) {
8999  RealDecl->setInvalidDecl();
9000  return;
9001  }
9002 
9003  // The variable can not have an abstract class type.
9004  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9005  diag::err_abstract_type_in_decl,
9006  AbstractVariableType))
9007  VDecl->setInvalidDecl();
9008  }
9009 
9010  VarDecl *Def;
9011  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9012  NamedDecl *Hidden = nullptr;
9013  if (!hasVisibleDefinition(Def, &Hidden) &&
9014  (VDecl->getFormalLinkage() == InternalLinkage ||
9015  VDecl->getDescribedVarTemplate() ||
9016  VDecl->getNumTemplateParameterLists() ||
9017  VDecl->getDeclContext()->isDependentContext())) {
9018  // The previous definition is hidden, and multiple definitions are
9019  // permitted (in separate TUs). Form another definition of it.
9020  } else {
9021  Diag(VDecl->getLocation(), diag::err_redefinition)
9022  << VDecl->getDeclName();
9023  Diag(Def->getLocation(), diag::note_previous_definition);
9024  VDecl->setInvalidDecl();
9025  return;
9026  }
9027  }
9028 
9029  if (getLangOpts().CPlusPlus) {
9030  // C++ [class.static.data]p4
9031  // If a static data member is of const integral or const
9032  // enumeration type, its declaration in the class definition can
9033  // specify a constant-initializer which shall be an integral
9034  // constant expression (5.19). In that case, the member can appear
9035  // in integral constant expressions. The member shall still be
9036  // defined in a namespace scope if it is used in the program and the
9037  // namespace scope definition shall not contain an initializer.
9038  //
9039  // We already performed a redefinition check above, but for static
9040  // data members we also need to check whether there was an in-class
9041  // declaration with an initializer.
9042  if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9043  Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9044  << VDecl->getDeclName();
9045  Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9046  diag::note_previous_initializer)
9047  << 0;
9048  return;
9049  }
9050 
9051  if (VDecl->hasLocalStorage())
9052  getCurFunction()->setHasBranchProtectedScope();
9053 
9054  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9055  VDecl->setInvalidDecl();
9056  return;
9057  }
9058  }
9059 
9060  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9061  // a kernel function cannot be initialized."
9062  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
9063  Diag(VDecl->getLocation(), diag::err_local_cant_init);
9064  VDecl->setInvalidDecl();
9065  return;
9066  }
9067 
9068  // Get the decls type and save a reference for later, since
9069  // CheckInitializerTypes may change it.
9070  QualType DclT = VDecl->getType(), SavT = DclT;
9071 
9072  // Expressions default to 'id' when we're in a debugger
9073  // and we are assigning it to a variable of Objective-C pointer type.
9074  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9075  Init->getType() == Context.UnknownAnyTy) {
9076  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9077  if (Result.isInvalid()) {
9078  VDecl->setInvalidDecl();
9079  return;
9080  }
9081  Init = Result.get();
9082  }
9083 
9084  // Perform the initialization.
9085  if (!VDecl->isInvalidDecl()) {
9088  = DirectInit ?
9089  CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
9090  Init->getLocStart(),
9091  Init->getLocEnd())
9093  VDecl->getLocation())
9095  Init->getLocStart());
9096 
9097  MultiExprArg Args = Init;
9098  if (CXXDirectInit)
9099  Args = MultiExprArg(CXXDirectInit->getExprs(),
9100  CXXDirectInit->getNumExprs());
9101 
9102  // Try to correct any TypoExprs in the initialization arguments.
9103  for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9104  ExprResult Res = CorrectDelayedTyposInExpr(
9105  Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9106  InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9107  return Init.Failed() ? ExprError() : E;
9108  });
9109  if (Res.isInvalid()) {
9110  VDecl->setInvalidDecl();
9111  } else if (Res.get() != Args[Idx]) {
9112  Args[Idx] = Res.get();
9113  }
9114  }
9115  if (VDecl->isInvalidDecl())
9116  return;
9117 
9118  InitializationSequence InitSeq(*this, Entity, Kind, Args);
9119  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9120  if (Result.isInvalid()) {
9121  VDecl->setInvalidDecl();
9122  return;
9123  }
9124 
9125  Init = Result.getAs<Expr>();
9126  }
9127 
9128  // Check for self-references within variable initializers.
9129  // Variables declared within a function/method body (except for references)
9130  // are handled by a dataflow analysis.
9131  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9132  VDecl->getType()->isReferenceType()) {
9133  CheckSelfReference(*this, RealDecl, Init, DirectInit);
9134  }
9135 
9136  // If the type changed, it means we had an incomplete type that was
9137  // completed by the initializer. For example:
9138  // int ary[] = { 1, 3, 5 };
9139  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9140  if (!VDecl->isInvalidDecl() && (DclT != SavT))
9141  VDecl->setType(DclT);
9142 
9143  if (!VDecl->isInvalidDecl()) {
9144  checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9145 
9146  if (VDecl->hasAttr<BlocksAttr>())
9147  checkRetainCycles(VDecl, Init);
9148 
9149  // It is safe to assign a weak reference into a strong variable.
9150  // Although this code can still have problems:
9151  // id x = self.weakProp;
9152  // id y = self.weakProp;
9153  // we do not warn to warn spuriously when 'x' and 'y' are on separate
9154  // paths through the function. This should be revisited if
9155  // -Wrepeated-use-of-weak is made flow-sensitive.
9156  if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9157  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9158  Init->getLocStart()))
9159  getCurFunction()->markSafeWeakUse(Init);
9160  }
9161 
9162  // The initialization is usually a full-expression.
9163  //
9164  // FIXME: If this is a braced initialization of an aggregate, it is not
9165  // an expression, and each individual field initializer is a separate
9166  // full-expression. For instance, in:
9167  //
9168  // struct Temp { ~Temp(); };
9169  // struct S { S(Temp); };
9170  // struct T { S a, b; } t = { Temp(), Temp() }
9171  //
9172  // we should destroy the first Temp before constructing the second.
9173  ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9174  false,
9175  VDecl->isConstexpr());
9176  if (Result.isInvalid()) {
9177  VDecl->setInvalidDecl();
9178  return;
9179  }
9180  Init = Result.get();
9181 
9182  // Attach the initializer to the decl.
9183  VDecl->setInit(Init);
9184 
9185  if (VDecl->isLocalVarDecl()) {
9186  // C99 6.7.8p4: All the expressions in an initializer for an object that has
9187  // static storage duration shall be constant expressions or string literals.
9188  // C++ does not have this restriction.
9189  if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9190  const Expr *Culprit;
9191  if (VDecl->getStorageClass() == SC_Static)
9192  CheckForConstantInitializer(Init, DclT);
9193  // C89 is stricter than C99 for non-static aggregate types.
9194  // C89 6.5.7p3: All the expressions [...] in an initializer list
9195  // for an object that has aggregate or union type shall be
9196  // constant expressions.
9197  else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9198  isa<InitListExpr>(Init) &&
9199  !Init->isConstantInitializer(Context, false, &Culprit))
9200  Diag(Culprit->getExprLoc(),
9201  diag::ext_aggregate_init_not_constant)
9202  << Culprit->getSourceRange();
9203  }
9204  } else if (VDecl->isStaticDataMember() &&
9205  VDecl->getLexicalDeclContext()->isRecord()) {
9206  // This is an in-class initialization for a static data member, e.g.,
9207  //
9208  // struct S {
9209  // static const int value = 17;
9210  // };
9211 
9212  // C++ [class.mem]p4:
9213  // A member-declarator can contain a constant-initializer only
9214  // if it declares a static member (9.4) of const integral or
9215  // const enumeration type, see 9.4.2.
9216  //
9217  // C++11 [class.static.data]p3:
9218  // If a non-volatile const static data member is of integral or
9219  // enumeration type, its declaration in the class definition can
9220  // specify a brace-or-equal-initializer in which every initalizer-clause
9221  // that is an assignment-expression is a constant expression. A static
9222  // data member of literal type can be declared in the class definition
9223  // with the constexpr specifier; if so, its declaration shall specify a
9224  // brace-or-equal-initializer in which every initializer-clause that is
9225  // an assignment-expression is a constant expression.
9226 
9227  // Do nothing on dependent types.
9228  if (DclT->isDependentType()) {
9229 
9230  // Allow any 'static constexpr' members, whether or not they are of literal
9231  // type. We separately check that every constexpr variable is of literal
9232  // type.
9233  } else if (VDecl->isConstexpr()) {
9234 
9235  // Require constness.
9236  } else if (!DclT.isConstQualified()) {
9237  Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9238  << Init->getSourceRange();
9239  VDecl->setInvalidDecl();
9240 
9241  // We allow integer constant expressions in all cases.
9242  } else if (DclT->isIntegralOrEnumerationType()) {
9243  // Check whether the expression is a constant expression.
9244  SourceLocation Loc;
9245  if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9246  // In C++11, a non-constexpr const static data member with an
9247  // in-class initializer cannot be volatile.
9248  Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9249  else if (Init->isValueDependent())
9250  ; // Nothing to check.
9251  else if (Init->isIntegerConstantExpr(Context, &Loc))
9252  ; // Ok, it's an ICE!
9253  else if (Init->isEvaluatable(Context)) {
9254  // If we can constant fold the initializer through heroics, accept it,
9255  // but report this as a use of an extension for -pedantic.
9256  Diag(Loc, diag::ext_in_class_initializer_non_constant)
9257  << Init->getSourceRange();
9258  } else {
9259  // Otherwise, this is some crazy unknown case. Report the issue at the
9260  // location provided by the isIntegerConstantExpr failed check.
9261  Diag(Loc, diag::err_in_class_initializer_non_constant)
9262  << Init->getSourceRange();
9263  VDecl->setInvalidDecl();
9264  }
9265 
9266  // We allow foldable floating-point constants as an extension.
9267  } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9268  // In C++98, this is a GNU extension. In C++11, it is not, but we support
9269  // it anyway and provide a fixit to add the 'constexpr'.
9270  if (getLangOpts().CPlusPlus11) {
9271  Diag(VDecl->getLocation(),
9272  diag::ext_in_class_initializer_float_type_cxx11)
9273  << DclT << Init->getSourceRange();
9274  Diag(VDecl->getLocStart(),
9275  diag::note_in_class_initializer_float_type_cxx11)
9276  << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9277  } else {
9278  Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9279  << DclT << Init->getSourceRange();
9280 
9281  if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9282  Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9283  << Init->getSourceRange();
9284  VDecl->setInvalidDecl();
9285  }
9286  }
9287 
9288  // Suggest adding 'constexpr' in C++11 for literal types.
9289  } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9290  Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9291  << DclT << Init->getSourceRange()
9292  << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9293  VDecl->setConstexpr(true);
9294 
9295  } else {
9296  Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9297  << DclT << Init->getSourceRange();
9298  VDecl->setInvalidDecl();
9299  }
9300  } else if (VDecl->isFileVarDecl()) {
9301  if (VDecl->getStorageClass() == SC_Extern &&
9302  (!getLangOpts().CPlusPlus ||
9303  !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9304  VDecl->isExternC())) &&
9306  Diag(VDecl->getLocation(), diag::warn_extern_init);
9307 
9308  // C99 6.7.8p4. All file scoped initializers need to be constant.
9309  if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9310  CheckForConstantInitializer(Init, DclT);
9311  }
9312 
9313  // We will represent direct-initialization similarly to copy-initialization:
9314  // int x(1); -as-> int x = 1;
9315  // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9316  //
9317  // Clients that want to distinguish between the two forms, can check for
9318  // direct initializer using VarDecl::getInitStyle().
9319  // A major benefit is that clients that don't particularly care about which
9320  // exactly form was it (like the CodeGen) can handle both cases without
9321  // special case code.
9322 
9323  // C++ 8.5p11:
9324  // The form of initialization (using parentheses or '=') is generally
9325  // insignificant, but does matter when the entity being initialized has a
9326  // class type.
9327  if (CXXDirectInit) {
9328  assert(DirectInit && "Call-style initializer must be direct init.");
9330  } else if (DirectInit) {
9331  // This must be list-initialization. No other way is direct-initialization.
9333  }
9334 
9335  CheckCompleteVariableDeclaration(VDecl);
9336 }
9337 
9338 /// ActOnInitializerError - Given that there was an error parsing an
9339 /// initializer for the given declaration, try to return to some form
9340 /// of sanity.
9342  // Our main concern here is re-establishing invariants like "a
9343  // variable's type is either dependent or complete".
9344  if (!D || D->isInvalidDecl()) return;
9345 
9346  VarDecl *VD = dyn_cast<VarDecl>(D);
9347  if (!VD) return;
9348 
9349  // Auto types are meaningless if we can't make sense of the initializer.
9350  if (ParsingInitForAutoVars.count(D)) {
9351  D->setInvalidDecl();
9352  return;
9353  }
9354 
9355  QualType Ty = VD->getType();
9356  if (Ty->isDependentType()) return;
9357 
9358  // Require a complete type.
9359  if (RequireCompleteType(VD->getLocation(),
9361  diag::err_typecheck_decl_incomplete_type)) {
9362  VD->setInvalidDecl();
9363  return;
9364  }
9365 
9366  // Require a non-abstract type.
9367  if (RequireNonAbstractType(VD->getLocation(), Ty,
9368  diag::err_abstract_type_in_decl,
9369  AbstractVariableType)) {
9370  VD->setInvalidDecl();
9371  return;
9372  }
9373 
9374  // Don't bother complaining about constructors or destructors,
9375  // though.
9376 }
9377 
9379  bool TypeMayContainAuto) {
9380  // If there is no declaration, there was an error parsing it. Just ignore it.
9381  if (!RealDecl)
9382  return;
9383 
9384  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9385  QualType Type = Var->getType();
9386 
9387  // C++11 [dcl.spec.auto]p3
9388  if (TypeMayContainAuto && Type->getContainedAutoType()) {
9389  Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9390  << Var->getDeclName() << Type;
9391  Var->setInvalidDecl();
9392  return;
9393  }
9394 
9395  // C++11 [class.static.data]p3: A static data member can be declared with
9396  // the constexpr specifier; if so, its declaration shall specify
9397  // a brace-or-equal-initializer.
9398  // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9399  // the definition of a variable [...] or the declaration of a static data
9400  // member.
9401  if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9402  if (Var->isStaticDataMember())
9403  Diag(Var->getLocation(),
9404  diag::err_constexpr_static_mem_var_requires_init)
9405  << Var->getDeclName();
9406  else
9407  Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9408  Var->setInvalidDecl();
9409  return;
9410  }
9411 
9412  // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9413  // be initialized.
9414  if (!Var->isInvalidDecl() &&
9415  Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9416  Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9417  Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9418  Var->setInvalidDecl();
9419  return;
9420  }
9421 
9422  switch (Var->isThisDeclarationADefinition()) {
9423  case VarDecl::Definition:
9424  if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9425  break;
9426 
9427  // We have an out-of-line definition of a static data member
9428  // that has an in-class initializer, so we type-check this like
9429  // a declaration.
9430  //
9431  // Fall through
9432 
9434  // It's only a declaration.
9435 
9436  // Block scope. C99 6.7p7: If an identifier for an object is
9437  // declared with no linkage (C99 6.2.2p6), the type for the
9438  // object shall be complete.
9439  if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9440  !Var->hasLinkage() && !Var->isInvalidDecl() &&
9441  RequireCompleteType(Var->getLocation(), Type,
9442  diag::err_typecheck_decl_incomplete_type))
9443  Var->setInvalidDecl();
9444 
9445  // Make sure that the type is not abstract.
9446  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9447  RequireNonAbstractType(Var->getLocation(), Type,
9448  diag::err_abstract_type_in_decl,
9449  AbstractVariableType))
9450  Var->setInvalidDecl();
9451  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9452  Var->getStorageClass() == SC_PrivateExtern) {
9453  Diag(Var->getLocation(), diag::warn_private_extern);
9454  Diag(Var->getLocation(), diag::note_private_extern);
9455  }
9456 
9457  return;
9458 
9460  // File scope. C99 6.9.2p2: A declaration of an identifier for an
9461  // object that has file scope without an initializer, and without a
9462  // storage-class specifier or with the storage-class specifier "static",
9463  // constitutes a tentative definition. Note: A tentative definition with
9464  // external linkage is valid (C99 6.2.2p5).
9465  if (!Var->isInvalidDecl()) {
9466  if (const IncompleteArrayType *ArrayT
9468  if (RequireCompleteType(Var->getLocation(),
9469  ArrayT->getElementType(),
9470  diag::err_illegal_decl_array_incomplete_type))
9471  Var->setInvalidDecl();
9472  } else if (Var->getStorageClass() == SC_Static) {
9473  // C99 6.9.2p3: If the declaration of an identifier for an object is
9474  // a tentative definition and has internal linkage (C99 6.2.2p3), the
9475  // declared type shall not be an incomplete type.
9476  // NOTE: code such as the following
9477  // static struct s;
9478  // struct s { int a; };
9479  // is accepted by gcc. Hence here we issue a warning instead of
9480  // an error and we do not invalidate the static declaration.
9481  // NOTE: to avoid multiple warnings, only check the first declaration.
9482  if (Var->isFirstDecl())
9483  RequireCompleteType(Var->getLocation(), Type,
9484  diag::ext_typecheck_decl_incomplete_type);
9485  }
9486  }
9487 
9488  // Record the tentative definition; we're done.
9489  if (!Var->isInvalidDecl())
9490  TentativeDefinitions.push_back(Var);
9491  return;
9492  }
9493 
9494  // Provide a specific diagnostic for uninitialized variable
9495  // definitions with incomplete array type.
9496  if (Type->isIncompleteArrayType()) {
9497  Diag(Var->getLocation(),
9498  diag::err_typecheck_incomplete_array_needs_initializer);
9499  Var->setInvalidDecl();
9500  return;
9501  }
9502 
9503  // Provide a specific diagnostic for uninitialized variable
9504  // definitions with reference type.
9505  if (Type->isReferenceType()) {
9506  Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9507  << Var->getDeclName()
9508  << SourceRange(Var->getLocation(), Var->getLocation());
9509  Var->setInvalidDecl();
9510  return;
9511  }
9512 
9513  // Do not attempt to type-check the default initializer for a
9514  // variable with dependent type.
9515  if (Type->isDependentType())
9516  return;
9517 
9518  if (Var->isInvalidDecl())
9519  return;
9520 
9521  if (!Var->hasAttr<AliasAttr>()) {
9522  if (RequireCompleteType(Var->getLocation(),
9524  diag::err_typecheck_decl_incomplete_type)) {
9525  Var->setInvalidDecl();
9526  return;
9527  }
9528  } else {
9529  return;
9530  }
9531 
9532  // The variable can not have an abstract class type.
9533  if (RequireNonAbstractType(Var->getLocation(), Type,
9534  diag::err_abstract_type_in_decl,
9535  AbstractVariableType)) {
9536  Var->setInvalidDecl();
9537  return;
9538  }
9539 
9540  // Check for jumps past the implicit initializer. C++0x
9541  // clarifies that this applies to a "variable with automatic
9542  // storage duration", not a "local variable".
9543  // C++11 [stmt.dcl]p3
9544  // A program that jumps from a point where a variable with automatic
9545  // storage duration is not in scope to a point where it is in scope is
9546  // ill-formed unless the variable has scalar type, class type with a
9547  // trivial default constructor and a trivial destructor, a cv-qualified
9548  // version of one of these types, or an array of one of the preceding
9549  // types and is declared without an initializer.
9550  if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9551  if (const RecordType *Record
9553  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9554  // Mark the function for further checking even if the looser rules of
9555  // C++11 do not require such checks, so that we can diagnose
9556  // incompatibilities with C++98.
9557  if (!CXXRecord->isPOD())
9558  getCurFunction()->setHasBranchProtectedScope();
9559  }
9560  }
9561 
9562  // C++03 [dcl.init]p9:
9563  // If no initializer is specified for an object, and the
9564  // object is of (possibly cv-qualified) non-POD class type (or
9565  // array thereof), the object shall be default-initialized; if
9566  // the object is of const-qualified type, the underlying class
9567  // type shall have a user-declared default
9568  // constructor. Otherwise, if no initializer is specified for
9569  // a non- static object, the object and its subobjects, if
9570  // any, have an indeterminate initial value); if the object
9571  // or any of its subobjects are of const-qualified type, the
9572  // program is ill-formed.
9573  // C++0x [dcl.init]p11:
9574  // If no initializer is specified for an object, the object is
9575  // default-initialized; [...].
9578  = InitializationKind::CreateDefault(Var->getLocation());
9579 
9580  InitializationSequence InitSeq(*this, Entity, Kind, None);
9581  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9582  if (Init.isInvalid())
9583  Var->setInvalidDecl();
9584  else if (Init.get()) {
9585  Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9586  // This is important for template substitution.
9587  Var->setInitStyle(VarDecl::CallInit);
9588  }
9589 
9590  CheckCompleteVariableDeclaration(Var);
9591  }
9592 }
9593 
9595  VarDecl *VD = dyn_cast<VarDecl>(D);
9596  if (!VD) {
9597  Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9598  D->setInvalidDecl();
9599  return;
9600  }
9601 
9602  VD->setCXXForRangeDecl(true);
9603 
9604  // for-range-declaration cannot be given a storage class specifier.
9605  int Error = -1;
9606  switch (VD->getStorageClass()) {
9607  case SC_None:
9608  break;
9609  case SC_Extern:
9610  Error = 0;
9611  break;
9612  case SC_Static:
9613  Error = 1;
9614  break;
9615  case SC_PrivateExtern:
9616  Error = 2;
9617  break;
9618  case SC_Auto:
9619  Error = 3;
9620  break;
9621  case SC_Register:
9622  Error = 4;
9623  break;
9625  llvm_unreachable("Unexpected storage class");
9626  }
9627  if (Error != -1) {
9628  Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9629  << VD->getDeclName() << Error;
9630  D->setInvalidDecl();
9631  }
9632 }
9633 
9634 StmtResult
9636  IdentifierInfo *Ident,
9637  ParsedAttributes &Attrs,
9638  SourceLocation AttrEnd) {
9639  // C++1y [stmt.iter]p1:
9640  // A range-based for statement of the form
9641  // for ( for-range-identifier : for-range-initializer ) statement
9642  // is equivalent to
9643  // for ( auto&& for-range-identifier : for-range-initializer ) statement
9644  DeclSpec DS(Attrs.getPool().getFactory());
9645 
9646  const char *PrevSpec;
9647  unsigned DiagID;
9648  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9649  getPrintingPolicy());
9650 
9652  D.SetIdentifier(Ident, IdentLoc);
9653  D.takeAttributes(Attrs, AttrEnd);
9654 
9655  ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9656  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9657  EmptyAttrs, IdentLoc);
9658  Decl *Var = ActOnDeclarator(S, D);
9659  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9660  FinalizeDeclaration(Var);
9661  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9662  AttrEnd.isValid() ? AttrEnd : IdentLoc);
9663 }
9664 
9666  if (var->isInvalidDecl()) return;
9667 
9668  // In ARC, don't allow jumps past the implicit initialization of a
9669  // local retaining variable.
9670  if (getLangOpts().ObjCAutoRefCount &&
9671  var->hasLocalStorage()) {
9672  switch (var->getType().getObjCLifetime()) {
9673  case Qualifiers::OCL_None:
9676  break;
9677 
9678  case Qualifiers::OCL_Weak:
9680  getCurFunction()->setHasBranchProtectedScope();
9681  break;
9682  }
9683  }
9684 
9685  // Warn about externally-visible variables being defined without a
9686  // prior declaration. We only want to do this for global
9687  // declarations, but we also specifically need to avoid doing it for
9688  // class members because the linkage of an anonymous class can
9689  // change if it's later given a typedef name.
9690  if (var->isThisDeclarationADefinition() &&
9692  var->isExternallyVisible() && var->hasLinkage() &&
9693  !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9694  var->getLocation())) {
9695  // Find a previous declaration that's not a definition.
9696  VarDecl *prev = var->getPreviousDecl();
9697  while (prev && prev->isThisDeclarationADefinition())
9698  prev = prev->getPreviousDecl();
9699 
9700  if (!prev)
9701  Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9702  }
9703 
9704  if (var->getTLSKind() == VarDecl::TLS_Static) {
9705  const Expr *Culprit;
9706  if (var->getType().isDestructedType()) {
9707  // GNU C++98 edits for __thread, [basic.start.term]p3:
9708  // The type of an object with thread storage duration shall not
9709  // have a non-trivial destructor.
9710  Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9711  if (getLangOpts().CPlusPlus11)
9712  Diag(var->getLocation(), diag::note_use_thread_local);
9713  } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9714  !var->getInit()->isConstantInitializer(
9715  Context, var->getType()->isReferenceType(), &Culprit)) {
9716  // GNU C++98 edits for __thread, [basic.start.init]p4:
9717  // An object of thread storage duration shall not require dynamic
9718  // initialization.
9719  // FIXME: Need strict checking here.
9720  Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9721  << Culprit->getSourceRange();
9722  if (getLangOpts().CPlusPlus11)
9723  Diag(var->getLocation(), diag::note_use_thread_local);
9724  }
9725 
9726  }
9727 
9728  // Apply section attributes and pragmas to global variables.
9729  bool GlobalStorage = var->hasGlobalStorage();
9730  if (GlobalStorage && var->isThisDeclarationADefinition() &&
9731  ActiveTemplateInstantiations.empty()) {
9733  int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9734  if (var->getType().isConstQualified())
9735  Stack = &ConstSegStack;
9736  else if (!var->getInit()) {
9737  Stack = &BSSSegStack;
9738  SectionFlags |= ASTContext::PSF_Write;
9739  } else {
9740  Stack = &DataSegStack;
9741  SectionFlags |= ASTContext::PSF_Write;
9742  }
9743  if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
9744  var->addAttr(SectionAttr::CreateImplicit(
9745  Context, SectionAttr::Declspec_allocate,
9746  Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
9747  }
9748  if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9749  if (UnifySection(SA->getName(), SectionFlags, var))
9750  var->dropAttr<SectionAttr>();
9751 
9752  // Apply the init_seg attribute if this has an initializer. If the
9753  // initializer turns out to not be dynamic, we'll end up ignoring this
9754  // attribute.
9755  if (CurInitSeg && var->getInit())
9756  var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9757  CurInitSegLoc));
9758  }
9759 
9760  // All the following checks are C++ only.
9761  if (!getLangOpts().CPlusPlus) return;
9762 
9763  QualType type = var->getType();
9764  if (type->isDependentType()) return;
9765 
9766  // __block variables might require us to capture a copy-initializer.
9767  if (var->hasAttr<BlocksAttr>()) {
9768  // It's currently invalid to ever have a __block variable with an
9769  // array type; should we diagnose that here?
9770 
9771  // Regardless, we don't want to ignore array nesting when
9772  // constructing this copy.
9773  if (type->isStructureOrClassType()) {
9774  EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
9775  SourceLocation poi = var->getLocation();
9776  Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
9777  ExprResult result
9778  = PerformMoveOrCopyInitialization(
9779  InitializedEntity::InitializeBlock(poi, type, false),
9780  var, var->getType(), varRef, /*AllowNRVO=*/true);
9781  if (!result.isInvalid()) {
9782  result = MaybeCreateExprWithCleanups(result);
9783  Expr *init = result.getAs<Expr>();
9784  Context.setBlockVarCopyInits(var, init);
9785  }
9786  }
9787  }
9788 
9789  Expr *Init = var->getInit();
9790  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
9791  QualType baseType = Context.getBaseElementType(type);
9792 
9793  if (!var->getDeclContext()->isDependentContext() &&
9794  Init && !Init->isValueDependent()) {
9795  if (IsGlobal && !var->isConstexpr() &&
9796  !getDiagnostics().isIgnored(diag::warn_global_constructor,
9797  var->getLocation())) {
9798  // Warn about globals which don't have a constant initializer. Don't
9799  // warn about globals with a non-trivial destructor because we already
9800  // warned about them.
9801  CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
9802  if (!(RD && !RD->hasTrivialDestructor()) &&
9803  !Init->isConstantInitializer(Context, baseType->isReferenceType()))
9804  Diag(var->getLocation(), diag::warn_global_constructor)
9805  << Init->getSourceRange();
9806  }
9807 
9808  if (var->isConstexpr()) {
9810  if (!var->evaluateValue(Notes) || !var->isInitICE()) {
9811  SourceLocation DiagLoc = var->getLocation();
9812  // If the note doesn't add any useful information other than a source
9813  // location, fold it into the primary diagnostic.
9814  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9815  diag::note_invalid_subexpr_in_const_expr) {
9816  DiagLoc = Notes[0].first;
9817  Notes.clear();
9818  }
9819  Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
9820  << var << Init->getSourceRange();
9821  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9822  Diag(Notes[I].first, Notes[I].second);
9823  }
9824  } else if (var->isUsableInConstantExpressions(Context)) {
9825  // Check whether the initializer of a const variable of integral or
9826  // enumeration type is an ICE now, since we can't tell whether it was
9827  // initialized by a constant expression if we check later.
9828  var->checkInitIsICE();
9829  }
9830  }
9831 
9832  // Require the destructor.
9833  if (const RecordType *recordType = baseType->getAs<RecordType>())
9834  FinalizeVarWithDestructor(var, recordType);
9835 }
9836 
9837 /// \brief Determines if a variable's alignment is dependent.
9838 static bool hasDependentAlignment(VarDecl *VD) {
9839  if (VD->getType()->isDependentType())
9840  return true;
9841  for (auto *I : VD->specific_attrs<AlignedAttr>())
9842  if (I->isAlignmentDependent())
9843  return true;
9844  return false;
9845 }
9846 
9847 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9848 /// any semantic actions necessary after any initializer has been attached.
9849 void
9851  // Note that we are no longer parsing the initializer for this declaration.
9852  ParsingInitForAutoVars.erase(ThisDecl);
9853 
9854  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9855  if (!VD)
9856  return;
9857 
9858  checkAttributesAfterMerging(*this, *VD);
9859 
9860  // Perform TLS alignment check here after attributes attached to the variable
9861  // which may affect the alignment have been processed. Only perform the check
9862  // if the target has a maximum TLS alignment (zero means no constraints).
9863  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
9864  // Protect the check so that it's not performed on dependent types and
9865  // dependent alignments (we can't determine the alignment in that case).
9866  if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
9867  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
9868  if (Context.getDeclAlign(VD) > MaxAlignChars) {
9869  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
9870  << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
9871  << (unsigned)MaxAlignChars.getQuantity();
9872  }
9873  }
9874  }
9875 
9876  // Static locals inherit dll attributes from their function.
9877  if (VD->isStaticLocal()) {
9878  if (FunctionDecl *FD =
9879  dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
9880  if (Attr *A = getDLLAttr(FD)) {
9881  auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
9882  NewAttr->setInherited(true);
9883  VD->addAttr(NewAttr);
9884  }
9885  }
9886  }
9887 
9888  // Grab the dllimport or dllexport attribute off of the VarDecl.
9889  const InheritableAttr *DLLAttr = getDLLAttr(VD);
9890 
9891  // Imported static data members cannot be defined out-of-line.
9892  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
9893  if (VD->isStaticDataMember() && VD->isOutOfLine() &&
9895  // We allow definitions of dllimport class template static data members
9896  // with a warning.
9898  cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
9899  bool IsClassTemplateMember =
9900  isa<ClassTemplatePartialSpecializationDecl>(Context) ||
9901  Context->getDescribedClassTemplate();
9902 
9903  Diag(VD->getLocation(),
9904  IsClassTemplateMember
9905  ? diag::warn_attribute_dllimport_static_field_definition
9906  : diag::err_attribute_dllimport_static_field_definition);
9907  Diag(IA->getLocation(), diag::note_attribute);
9908  if (!IsClassTemplateMember)
9909  VD->setInvalidDecl();
9910  }
9911  }
9912 
9913  // dllimport/dllexport variables cannot be thread local, their TLS index
9914  // isn't exported with the variable.
9915  if (DLLAttr && VD->getTLSKind()) {
9916  Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
9917  << DLLAttr;
9918  VD->setInvalidDecl();
9919  }
9920 
9921  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9922  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9923  Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9924  VD->dropAttr<UsedAttr>();
9925  }
9926  }
9927 
9928  const DeclContext *DC = VD->getDeclContext();
9929  // If there's a #pragma GCC visibility in scope, and this isn't a class
9930  // member, set the visibility of this variable.
9931  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9932  AddPushedVisibilityAttribute(VD);
9933 
9934  // FIXME: Warn on unused templates.
9935  if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
9936  !isa<VarTemplatePartialSpecializationDecl>(VD))
9937  MarkUnusedFileScopedDecl(VD);
9938 
9939  // Now we have parsed the initializer and can update the table of magic
9940  // tag values.
9941  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9943  return;
9944 
9945  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9946  const Expr *MagicValueExpr = VD->getInit();
9947  if (!MagicValueExpr) {
9948  continue;
9949  }
9950  llvm::APSInt MagicValueInt;
9951  if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9952  Diag(I->getRange().getBegin(),
9953  diag::err_type_tag_for_datatype_not_ice)
9954  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9955  continue;
9956  }
9957  if (MagicValueInt.getActiveBits() > 64) {
9958  Diag(I->getRange().getBegin(),
9959  diag::err_type_tag_for_datatype_too_large)
9960  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9961  continue;
9962  }
9963  uint64_t MagicValue = MagicValueInt.getZExtValue();
9964  RegisterTypeTagForDatatype(I->getArgumentKind(),
9965  MagicValue,
9966  I->getMatchingCType(),
9967  I->getLayoutCompatible(),
9968  I->getMustBeNull());
9969  }
9970 }
9971 
9973  ArrayRef<Decl *> Group) {
9974  SmallVector<Decl*, 8> Decls;
9975 
9976  if (DS.isTypeSpecOwned())
9977  Decls.push_back(DS.getRepAsDecl());
9978 
9979  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
9980  for (unsigned i = 0, e = Group.size(); i != e; ++i)
9981  if (Decl *D = Group[i]) {
9982  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9983  if (!FirstDeclaratorInGroup)
9984  FirstDeclaratorInGroup = DD;
9985  Decls.push_back(D);
9986  }
9987 
9989  if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9990  handleTagNumbering(Tag, S);
9991  if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9992  Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9993  }
9994  }
9995 
9996  return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9997 }
9998 
9999 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10000 /// group, performing any necessary semantic checking.
10003  bool TypeMayContainAuto) {
10004  // C++0x [dcl.spec.auto]p7:
10005  // If the type deduced for the template parameter U is not the same in each
10006  // deduction, the program is ill-formed.
10007  // FIXME: When initializer-list support is added, a distinction is needed
10008  // between the deduced type U and the deduced type which 'auto' stands for.
10009  // auto a = 0, b = { 1, 2, 3 };
10010  // is legal because the deduced type U is 'int' in both cases.
10011  if (TypeMayContainAuto && Group.size() > 1) {
10012  QualType Deduced;
10013  CanQualType DeducedCanon;
10014  VarDecl *DeducedDecl = nullptr;
10015  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10016  if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10017  AutoType *AT = D->getType()->getContainedAutoType();
10018  // Don't reissue diagnostics when instantiating a template.
10019  if (AT && D->isInvalidDecl())
10020  break;
10021  QualType U = AT ? AT->getDeducedType() : QualType();
10022  if (!U.isNull()) {
10023  CanQualType UCanon = Context.getCanonicalType(U);
10024  if (Deduced.isNull()) {
10025  Deduced = U;
10026  DeducedCanon = UCanon;
10027  DeducedDecl = D;
10028  } else if (DeducedCanon != UCanon) {
10030  diag::err_auto_different_deductions)
10031  << (AT->isDecltypeAuto() ? 1 : 0)
10032  << Deduced << DeducedDecl->getDeclName()
10033  << U << D->getDeclName()
10034  << DeducedDecl->getInit()->getSourceRange()
10035  << D->getInit()->getSourceRange();
10036  D->setInvalidDecl();
10037  break;
10038  }
10039  }
10040  }
10041  }
10042  }
10043 
10044  ActOnDocumentableDecls(Group);
10045 
10046  return DeclGroupPtrTy::make(
10047  DeclGroupRef::Create(Context, Group.data(), Group.size()));
10048 }
10049 
10051  ActOnDocumentableDecls(D);
10052 }
10053 
10055  // Don't parse the comment if Doxygen diagnostics are ignored.
10056  if (Group.empty() || !Group[0])
10057  return;
10058 
10059  if (Diags.isIgnored(diag::warn_doc_param_not_found,
10060  Group[0]->getLocation()) &&
10061  Diags.isIgnored(diag::warn_unknown_comment_command_name,
10062  Group[0]->getLocation()))
10063  return;
10064 
10065  if (Group.size() >= 2) {
10066  // This is a decl group. Normally it will contain only declarations
10067  // produced from declarator list. But in case we have any definitions or
10068  // additional declaration references:
10069  // 'typedef struct S {} S;'
10070  // 'typedef struct S *S;'
10071  // 'struct S *pS;'
10072  // FinalizeDeclaratorGroup adds these as separate declarations.
10073  Decl *MaybeTagDecl = Group[0];
10074  if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10075  Group = Group.slice(1);
10076  }
10077  }
10078 
10079  // See if there are any new comments that are not attached to a decl.
10081  if (!Comments.empty() &&
10082  !Comments.back()->isAttached()) {
10083  // There is at least one comment that not attached to a decl.
10084  // Maybe it should be attached to one of these decls?
10085  //
10086  // Note that this way we pick up not only comments that precede the
10087  // declaration, but also comments that *follow* the declaration -- thanks to
10088  // the lookahead in the lexer: we've consumed the semicolon and looked
10089  // ahead through comments.
10090  for (unsigned i = 0, e = Group.size(); i != e; ++i)
10091  Context.getCommentForDecl(Group[i], &PP);
10092  }
10093 }
10094 
10095 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10096 /// to introduce parameters into function prototype scope.
10098  const DeclSpec &DS = D.getDeclSpec();
10099 
10100  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10101 
10102  // C++03 [dcl.stc]p2 also permits 'auto'.
10103  StorageClass SC = SC_None;
10105  SC = SC_Register;
10106  } else if (getLangOpts().CPlusPlus &&
10108  SC = SC_Auto;
10109  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10111  diag::err_invalid_storage_class_in_func_decl);
10113  }
10114 
10115  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10116  Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10117  << DeclSpec::getSpecifierName(TSCS);
10118  if (DS.isConstexprSpecified())
10119  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10120  << 0;
10121 
10122  DiagnoseFunctionSpecifiers(DS);
10123 
10124  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10125  QualType parmDeclType = TInfo->getType();
10126 
10127  if (getLangOpts().CPlusPlus) {
10128  // Check that there are no default arguments inside the type of this
10129  // parameter.
10130  CheckExtraCXXDefaultArguments(D);
10131 
10132  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10133  if (D.getCXXScopeSpec().isSet()) {
10134  Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10135  << D.getCXXScopeSpec().getRange();
10136  D.getCXXScopeSpec().clear();
10137  }
10138  }
10139 
10140  // Ensure we have a valid name
10141  IdentifierInfo *II = nullptr;
10142  if (D.hasName()) {
10143  II = D.getIdentifier();
10144  if (!II) {
10145  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10146  << GetNameForDeclarator(D).getName();
10147  D.setInvalidType(true);
10148  }
10149  }
10150 
10151  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10152  if (II) {
10153  LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10154  ForRedeclaration);
10155  LookupName(R, S);
10156  if (R.isSingleResult()) {
10157  NamedDecl *PrevDecl = R.getFoundDecl();
10158  if (PrevDecl->isTemplateParameter()) {
10159  // Maybe we will complain about the shadowed template parameter.
10160  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10161  // Just pretend that we didn't see the previous declaration.
10162  PrevDecl = nullptr;
10163  } else if (S->isDeclScope(PrevDecl)) {
10164  Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10165  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10166 
10167  // Recover by removing the name
10168  II = nullptr;
10169  D.SetIdentifier(nullptr, D.getIdentifierLoc());
10170  D.setInvalidType(true);
10171  }
10172  }
10173  }
10174 
10175  // Temporarily put parameter variables in the translation unit, not
10176  // the enclosing context. This prevents them from accidentally
10177  // looking like class members in C++.
10178  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10179  D.getLocStart(),
10180  D.getIdentifierLoc(), II,
10181  parmDeclType, TInfo,
10182  SC);
10183 
10184  if (D.isInvalidType())
10185  New->setInvalidDecl();
10186 
10187  assert(S->isFunctionPrototypeScope());
10188  assert(S->getFunctionPrototypeDepth() >= 1);
10191 
10192  // Add the parameter declaration into this scope.
10193  S->AddDecl(New);
10194  if (II)
10195  IdResolver.AddDecl(New);
10196 
10197  ProcessDeclAttributes(S, New, D);
10198 
10200  Diag(New->getLocation(), diag::err_module_private_local)
10201  << 1 << New->getDeclName()
10204 
10205  if (New->hasAttr<BlocksAttr>()) {
10206  Diag(New->getLocation(), diag::err_block_on_nonlocal);
10207  }
10208  return New;
10209 }
10210 
10211 /// \brief Synthesizes a variable for a parameter arising from a
10212 /// typedef.
10214  SourceLocation Loc,
10215  QualType T) {
10216  /* FIXME: setting StartLoc == Loc.
10217  Would it be worth to modify callers so as to provide proper source
10218  location for the unnamed parameters, embedding the parameter's type? */
10219  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10220  T, Context.getTrivialTypeSourceInfo(T, Loc),
10221  SC_None, nullptr);
10222  Param->setImplicit();
10223  return Param;
10224 }
10225 
10227  ParmVarDecl * const *ParamEnd) {
10228  // Don't diagnose unused-parameter errors in template instantiations; we
10229  // will already have done so in the template itself.
10230  if (!ActiveTemplateInstantiations.empty())
10231  return;
10232 
10233  for (; Param != ParamEnd; ++Param) {
10234  if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10235  !(*Param)->hasAttr<UnusedAttr>()) {
10236  Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10237  << (*Param)->getDeclName();
10238  }
10239  }
10240 }
10241 
10243  ParmVarDecl * const *ParamEnd,
10244  QualType ReturnTy,
10245  NamedDecl *D) {
10246  if (LangOpts.NumLargeByValueCopy == 0) // No check.
10247  return;
10248 
10249  // Warn if the return value is pass-by-value and larger than the specified
10250  // threshold.
10251  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10252  unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10253  if (Size > LangOpts.NumLargeByValueCopy)
10254  Diag(D->getLocation(), diag::warn_return_value_size)
10255  << D->getDeclName() << Size;
10256  }
10257 
10258  // Warn if any parameter is pass-by-value and larger than the specified
10259  // threshold.
10260  for (; Param != ParamEnd; ++Param) {
10261  QualType T = (*Param)->getType();
10262  if (T->isDependentType() || !T.isPODType(Context))
10263  continue;
10264  unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10265  if (Size > LangOpts.NumLargeByValueCopy)
10266  Diag((*Param)->getLocation(), diag::warn_parameter_size)
10267  << (*Param)->getDeclName() << Size;
10268  }
10269 }
10270 
10272  SourceLocation NameLoc, IdentifierInfo *Name,
10273  QualType T, TypeSourceInfo *TSInfo,
10274  StorageClass SC) {
10275  // In ARC, infer a lifetime qualifier for appropriate parameter types.
10276  if (getLangOpts().ObjCAutoRefCount &&
10278  T->isObjCLifetimeType()) {
10279 
10280  Qualifiers::ObjCLifetime lifetime;
10281 
10282  // Special cases for arrays:
10283  // - if it's const, use __unsafe_unretained
10284  // - otherwise, it's an error
10285  if (T->isArrayType()) {
10286  if (!T.isConstQualified()) {
10289  NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10290  }
10291  lifetime = Qualifiers::OCL_ExplicitNone;
10292  } else {
10293  lifetime = T->getObjCARCImplicitLifetime();
10294  }
10295  T = Context.getLifetimeQualifiedType(T, lifetime);
10296  }
10297 
10298  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10300  TSInfo, SC, nullptr);
10301 
10302  // Parameters can not be abstract class types.
10303  // For record types, this is done by the AbstractClassUsageDiagnoser once
10304  // the class has been completely parsed.
10305  if (!CurContext->isRecord() &&
10306  RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10307  AbstractParamType))
10308  New->setInvalidDecl();
10309 
10310  // Parameter declarators cannot be interface types. All ObjC objects are
10311  // passed by reference.
10312  if (T->isObjCObjectType()) {
10313  SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10314  Diag(NameLoc,
10315  diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10316  << FixItHint::CreateInsertion(TypeEndLoc, "*");
10318  New->setType(T);
10319  }
10320 
10321  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10322  // duration shall not be qualified by an address-space qualifier."
10323  // Since all parameters have automatic store duration, they can not have
10324  // an address space.
10325  if (T.getAddressSpace() != 0) {
10326  // OpenCL allows function arguments declared to be an array of a type
10327  // to be qualified with an address space.
10328  if (!(getLangOpts().OpenCL && T->isArrayType())) {
10329  Diag(NameLoc, diag::err_arg_with_address_space);
10330  New->setInvalidDecl();
10331  }
10332  }
10333 
10334  return New;
10335 }
10336 
10338  SourceLocation LocAfterDecls) {
10340 
10341  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10342  // for a K&R function.
10343  if (!FTI.hasPrototype) {
10344  for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10345  --i;
10346  if (FTI.Params[i].Param == nullptr) {
10347  SmallString<256> Code;
10348  llvm::raw_svector_ostream(Code)
10349  << " int " << FTI.Params[i].Ident->getName() << ";\n";
10350  Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10351  << FTI.Params[i].Ident
10352  << FixItHint::CreateInsertion(LocAfterDecls, Code);
10353 
10354  // Implicitly declare the argument as type 'int' for lack of a better
10355  // type.
10356  AttributeFactory attrs;
10357  DeclSpec DS(attrs);
10358  const char* PrevSpec; // unused
10359  unsigned DiagID; // unused
10360  DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10361  DiagID, Context.getPrintingPolicy());
10362  // Use the identifier location for the type source range.
10363  DS.SetRangeStart(FTI.Params[i].IdentLoc);
10364  DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10366  ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10367  FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10368  }
10369  }
10370  }
10371 }
10372 
10374  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10375  assert(D.isFunctionDeclarator() && "Not a function declarator!");
10376  Scope *ParentScope = FnBodyScope->getParent();
10377 
10379  Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
10380  return ActOnStartOfFunctionDef(FnBodyScope, DP);
10381 }
10382 
10384  Consumer.HandleInlineMethodDefinition(D);
10385 }
10386 
10388  const FunctionDecl*& PossibleZeroParamPrototype) {
10389  // Don't warn about invalid declarations.
10390  if (FD->isInvalidDecl())
10391  return false;
10392 
10393  // Or declarations that aren't global.
10394  if (!FD->isGlobal())
10395  return false;
10396 
10397  // Don't warn about C++ member functions.
10398  if (isa<CXXMethodDecl>(FD))
10399  return false;
10400 
10401  // Don't warn about 'main'.
10402  if (FD->isMain())
10403  return false;
10404 
10405  // Don't warn about inline functions.
10406  if (FD->isInlined())
10407  return false;
10408 
10409  // Don't warn about function templates.
10410  if (FD->getDescribedFunctionTemplate())
10411  return false;
10412 
10413  // Don't warn about function template specializations.
10415  return false;
10416 
10417  // Don't warn for OpenCL kernels.
10418  if (FD->hasAttr<OpenCLKernelAttr>())
10419  return false;
10420 
10421  // Don't warn on explicitly deleted functions.
10422  if (FD->isDeleted())
10423  return false;
10424 
10425  bool MissingPrototype = true;
10426  for (const FunctionDecl *Prev = FD->getPreviousDecl();
10427  Prev; Prev = Prev->getPreviousDecl()) {
10428  // Ignore any declarations that occur in function or method
10429  // scope, because they aren't visible from the header.
10430  if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10431  continue;
10432 
10433  MissingPrototype = !Prev->getType()->isFunctionProtoType();
10434  if (FD->getNumParams() == 0)
10435  PossibleZeroParamPrototype = Prev;
10436  break;
10437  }
10438 
10439  return MissingPrototype;
10440 }
10441 
10442 void
10444  const FunctionDecl *EffectiveDefinition) {
10445  // Don't complain if we're in GNU89 mode and the previous definition
10446  // was an extern inline function.
10447  const FunctionDecl *Definition = EffectiveDefinition;
10448  if (!Definition)
10449  if (!FD->isDefined(Definition))
10450  return;
10451 
10452  if (canRedefineFunction(Definition, getLangOpts()))
10453  return;
10454 
10455  // If we don't have a visible definition of the function, and it's inline or
10456  // a template, it's OK to form another definition of it.
10457  //
10458  // FIXME: Should we skip the body of the function and use the old definition
10459  // in this case? That may be necessary for functions that return local types
10460  // through a deduced return type, or instantiate templates with local types.
10461  if (!hasVisibleDefinition(Definition) &&
10462  (Definition->getFormalLinkage() == InternalLinkage ||
10463  Definition->isInlined() ||
10464  Definition->getDescribedFunctionTemplate() ||
10465  Definition->getNumTemplateParameterLists()))
10466  return;
10467 
10468  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10469  Definition->getStorageClass() == SC_Extern)
10470  Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10471  << FD->getDeclName() << getLangOpts().CPlusPlus;
10472  else
10473  Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10474 
10475  Diag(Definition->getLocation(), diag::note_previous_definition);
10476  FD->setInvalidDecl();
10477 }
10478 
10479 
10480 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10481  Sema &S) {
10482  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10483 
10484  LambdaScopeInfo *LSI = S.PushLambdaScope();
10485  LSI->CallOperator = CallOperator;
10486  LSI->Lambda = LambdaClass;
10487  LSI->ReturnType = CallOperator->getReturnType();
10488  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10489 
10490  if (LCD == LCD_None)
10492  else if (LCD == LCD_ByCopy)
10494  else if (LCD == LCD_ByRef)
10496  DeclarationNameInfo DNI = CallOperator->getNameInfo();
10497 
10499  LSI->Mutable = !CallOperator->isConst();
10500 
10501  // Add the captures to the LSI so they can be noted as already
10502  // captured within tryCaptureVar.
10503  auto I = LambdaClass->field_begin();
10504  for (const auto &C : LambdaClass->captures()) {
10505  if (C.capturesVariable()) {
10506  VarDecl *VD = C.getCapturedVar();
10507  if (VD->isInitCapture())
10509  QualType CaptureType = VD->getType();
10510  const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10511  LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10512  /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10513  /*EllipsisLoc*/C.isPackExpansion()
10514  ? C.getEllipsisLoc() : SourceLocation(),
10515  CaptureType, /*Expr*/ nullptr);
10516 
10517  } else if (C.capturesThis()) {
10518  LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10519  S.getCurrentThisType(), /*Expr*/ nullptr);
10520  } else {
10521  LSI->addVLATypeCapture(C.getLocation(), I->getType());
10522  }
10523  ++I;
10524  }
10525 }
10526 
10528  // Clear the last template instantiation error context.
10529  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10530 
10531  if (!D)
10532  return D;
10533  FunctionDecl *FD = nullptr;
10534 
10535  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10536  FD = FunTmpl->getTemplatedDecl();
10537  else
10538  FD = cast<FunctionDecl>(D);
10539  // If we are instantiating a generic lambda call operator, push
10540  // a LambdaScopeInfo onto the function stack. But use the information
10541  // that's already been calculated (ActOnLambdaExpr) to prime the current
10542  // LambdaScopeInfo.
10543  // When the template operator is being specialized, the LambdaScopeInfo,
10544  // has to be properly restored so that tryCaptureVariable doesn't try
10545  // and capture any new variables. In addition when calculating potential
10546  // captures during transformation of nested lambdas, it is necessary to
10547  // have the LSI properly restored.
10549  assert(ActiveTemplateInstantiations.size() &&
10550  "There should be an active template instantiation on the stack "
10551  "when instantiating a generic lambda!");
10552  RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10553  }
10554  else
10555  // Enter a new function scope
10556  PushFunctionScope();
10557 
10558  // See if this is a redefinition.
10559  if (!FD->isLateTemplateParsed())
10560  CheckForFunctionRedefinition(FD);
10561 
10562  // Builtin functions cannot be defined.
10563  if (unsigned BuiltinID = FD->getBuiltinID()) {
10564  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10566  Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10567  FD->setInvalidDecl();
10568  }
10569  }
10570 
10571  // The return type of a function definition must be complete
10572  // (C99 6.9.1p3, C++ [dcl.fct]p6).
10573  QualType ResultType = FD->getReturnType();
10574  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10575  !FD->isInvalidDecl() &&
10576  RequireCompleteType(FD->getLocation(), ResultType,
10577  diag::err_func_def_incomplete_result))
10578  FD->setInvalidDecl();
10579 
10580  if (FnBodyScope)
10581  PushDeclContext(FnBodyScope, FD);
10582 
10583  // Check the validity of our function parameters
10584  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10585  /*CheckParameterNames=*/true);
10586 
10587  // Introduce our parameters into the function scope
10588  for (auto Param : FD->params()) {
10589  Param->setOwningFunction(FD);
10590 
10591  // If this has an identifier, add it to the scope stack.
10592  if (Param->getIdentifier() && FnBodyScope) {
10593  CheckShadow(FnBodyScope, Param);
10594 
10595  PushOnScopeChains(Param, FnBodyScope);
10596  }
10597  }
10598 
10599  // If we had any tags defined in the function prototype,
10600  // introduce them into the function scope.
10601  if (FnBodyScope) {
10603  I = FD->getDeclsInPrototypeScope().begin(),
10604  E = FD->getDeclsInPrototypeScope().end();
10605  I != E; ++I) {
10606  NamedDecl *D = *I;
10607 
10608  // Some of these decls (like enums) may have been pinned to the
10609  // translation unit for lack of a real context earlier. If so, remove
10610  // from the translation unit and reattach to the current context.
10612  // Is the decl actually in the context?
10613  for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10614  if (DI == D) {
10616  break;
10617  }
10618  }
10619  // Either way, reassign the lexical decl context to our FunctionDecl.
10620  D->setLexicalDeclContext(CurContext);
10621  }
10622 
10623  // If the decl has a non-null name, make accessible in the current scope.
10624  if (!D->getName().empty())
10625  PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10626 
10627  // Similarly, dive into enums and fish their constants out, making them
10628  // accessible in this scope.
10629  if (auto *ED = dyn_cast<EnumDecl>(D)) {
10630  for (auto *EI : ED->enumerators())
10631  PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10632  }
10633  }
10634  }
10635 
10636  // Ensure that the function's exception specification is instantiated.
10637  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10638  ResolveExceptionSpec(D->getLocation(), FPT);
10639 
10640  // dllimport cannot be applied to non-inline function definitions.
10641  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10642  !FD->isTemplateInstantiation()) {
10643  assert(!FD->hasAttr<DLLExportAttr>());
10644  Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10645  FD->setInvalidDecl();
10646  return D;
10647  }
10648  // We want to attach documentation to original Decl (which might be
10649  // a function template).
10650  ActOnDocumentableDecl(D);
10651  if (getCurLexicalContext()->isObjCContainer() &&
10652  getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10653  getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10654  Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10655 
10656  return D;
10657 }
10658 
10659 /// \brief Given the set of return statements within a function body,
10660 /// compute the variables that are subject to the named return value
10661 /// optimization.
10662 ///
10663 /// Each of the variables that is subject to the named return value
10664 /// optimization will be marked as NRVO variables in the AST, and any
10665 /// return statement that has a marked NRVO variable as its NRVO candidate can
10666 /// use the named return value optimization.
10667 ///
10668 /// This function applies a very simplistic algorithm for NRVO: if every return
10669 /// statement in the scope of a variable has the same NRVO candidate, that
10670 /// candidate is an NRVO variable.
10672  ReturnStmt **Returns = Scope->Returns.data();
10673 
10674  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10675  if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10676  if (!NRVOCandidate->isNRVOVariable())
10677  Returns[I]->setNRVOCandidate(nullptr);
10678  }
10679  }
10680 }
10681 
10683  // We can't delay parsing the body of a constexpr function template (yet).
10685  return false;
10686 
10687  // We can't delay parsing the body of a function template with a deduced
10688  // return type (yet).
10690  // If the placeholder introduces a non-deduced trailing return type,
10691  // we can still delay parsing it.
10692  if (D.getNumTypeObjects()) {
10693  const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10694  if (Outer.Kind == DeclaratorChunk::Function &&
10695  Outer.Fun.hasTrailingReturnType()) {
10696  QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10697  return Ty.isNull() || !Ty->isUndeducedType();
10698  }
10699  }
10700  return false;
10701  }
10702 
10703  return true;
10704 }
10705 
10707  // We cannot skip the body of a function (or function template) which is
10708  // constexpr, since we may need to evaluate its body in order to parse the
10709  // rest of the file.
10710  // We cannot skip the body of a function with an undeduced return type,
10711  // because any callers of that function need to know the type.
10712  if (const FunctionDecl *FD = D->getAsFunction())
10713  if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10714  return false;
10715  return Consumer.shouldSkipFunctionBody(D);
10716 }
10717 
10719  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10720  FD->setHasSkippedBody();
10721  else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10722  MD->setHasSkippedBody();
10723  return ActOnFinishFunctionBody(Decl, nullptr);
10724 }
10725 
10727  return ActOnFinishFunctionBody(D, BodyArg, false);
10728 }
10729 
10731  bool IsInstantiation) {
10732  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10733 
10734  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10735  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10736 
10737  if (FD) {
10738  FD->setBody(Body);
10739 
10740  if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
10741  !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
10742  // If the function has a deduced result type but contains no 'return'
10743  // statements, the result type as written must be exactly 'auto', and
10744  // the deduced result type is 'void'.
10745  if (!FD->getReturnType()->getAs<AutoType>()) {
10746  Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
10747  << FD->getReturnType();
10748  FD->setInvalidDecl();
10749  } else {
10750  // Substitute 'void' for the 'auto' in the type.
10751  TypeLoc ResultType = getReturnTypeLoc(FD);
10753  FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
10754  }
10755  } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
10756  auto *LSI = getCurLambda();
10757  if (LSI->HasImplicitReturnType) {
10758  deduceClosureReturnType(*LSI);
10759 
10760  // C++11 [expr.prim.lambda]p4:
10761  // [...] if there are no return statements in the compound-statement
10762  // [the deduced type is] the type void
10763  QualType RetType =
10764  LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
10765 
10766  // Update the return type to the deduced type.
10767  const FunctionProtoType *Proto =
10768  FD->getType()->getAs<FunctionProtoType>();
10769  FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
10770  Proto->getExtProtoInfo()));
10771  }
10772  }
10773 
10774  // The only way to be included in UndefinedButUsed is if there is an
10775  // ODR use before the definition. Avoid the expensive map lookup if this
10776  // is the first declaration.
10777  if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
10778  if (!FD->isExternallyVisible())
10779  UndefinedButUsed.erase(FD);
10780  else if (FD->isInlined() &&
10781  !LangOpts.GNUInline &&
10782  (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
10783  UndefinedButUsed.erase(FD);
10784  }
10785 
10786  // If the function implicitly returns zero (like 'main') or is naked,
10787  // don't complain about missing return statements.
10788  if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
10790 
10791  // MSVC permits the use of pure specifier (=0) on function definition,
10792  // defined at class scope, warn about this non-standard construct.
10793  if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
10794  Diag(FD->getLocation(), diag::ext_pure_function_definition);
10795 
10796  if (!FD->isInvalidDecl()) {
10797  // Don't diagnose unused parameters of defaulted or deleted functions.
10798  if (!FD->isDeleted() && !FD->isDefaulted())
10799  DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
10800  DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
10801  FD->getReturnType(), FD);
10802 
10803  // If this is a structor, we need a vtable.
10804  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
10805  MarkVTableUsed(FD->getLocation(), Constructor->getParent());
10806  else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
10807  MarkVTableUsed(FD->getLocation(), Destructor->getParent());
10808 
10809  // Try to apply the named return value optimization. We have to check
10810  // if we can do this here because lambdas keep return statements around
10811  // to deduce an implicit return type.
10812  if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
10813  !FD->isDependentContext())
10814  computeNRVO(Body, getCurFunction());
10815  }
10816 
10817  // GNU warning -Wmissing-prototypes:
10818  // Warn if a global function is defined without a previous
10819  // prototype declaration. This warning is issued even if the
10820  // definition itself provides a prototype. The aim is to detect
10821  // global functions that fail to be declared in header files.
10822  const FunctionDecl *PossibleZeroParamPrototype = nullptr;
10823  if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
10824  Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
10825 
10826  if (PossibleZeroParamPrototype) {
10827  // We found a declaration that is not a prototype,
10828  // but that could be a zero-parameter prototype
10829  if (TypeSourceInfo *TI =
10830  PossibleZeroParamPrototype->getTypeSourceInfo()) {
10831  TypeLoc TL = TI->getTypeLoc();
10833  Diag(PossibleZeroParamPrototype->getLocation(),
10834  diag::note_declaration_not_a_prototype)
10835  << PossibleZeroParamPrototype
10836  << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
10837  }
10838  }
10839  }
10840 
10841  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10842  const CXXMethodDecl *KeyFunction;
10843  if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
10844  MD->isVirtual() &&
10845  (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
10846  MD == KeyFunction->getCanonicalDecl()) {
10847  // Update the key-function state if necessary for this ABI.
10848  if (FD->isInlined() &&
10851 
10852  // If the newly-chosen key function is already defined, then we
10853  // need to mark the vtable as used retroactively.
10854  KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
10855  const FunctionDecl *Definition;
10856  if (KeyFunction && KeyFunction->isDefined(Definition))
10857  MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
10858  } else {
10859  // We just defined they key function; mark the vtable as used.
10860  MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
10861  }
10862  }
10863  }
10864 
10865  assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
10866  "Function parsing confused");
10867  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
10868  assert(MD == getCurMethodDecl() && "Method parsing confused");
10869  MD->setBody(Body);
10870  if (!MD->isInvalidDecl()) {
10871  DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
10872  DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
10873  MD->getReturnType(), MD);
10874 
10875  if (Body)
10876  computeNRVO(Body, getCurFunction());
10877  }
10878  if (getCurFunction()->ObjCShouldCallSuper) {
10879  Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
10880  << MD->getSelector().getAsString();
10881  getCurFunction()->ObjCShouldCallSuper = false;
10882  }
10883  if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
10884  const ObjCMethodDecl *InitMethod = nullptr;
10885  bool isDesignated =
10886  MD->isDesignatedInitializerForTheInterface(&InitMethod);
10887  assert(isDesignated && InitMethod);
10888  (void)isDesignated;
10889 
10890  auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
10891  auto IFace = MD->getClassInterface();
10892  if (!IFace)
10893  return false;
10894  auto SuperD = IFace->getSuperClass();
10895  if (!SuperD)
10896  return false;
10897  return SuperD->getIdentifier() ==
10898  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
10899  };
10900  // Don't issue this warning for unavailable inits or direct subclasses
10901  // of NSObject.
10902  if (!MD->isUnavailable() && !superIsNSObject(MD)) {
10903  Diag(MD->getLocation(),
10904  diag::warn_objc_designated_init_missing_super_call);
10905  Diag(InitMethod->getLocation(),
10906  diag::note_objc_designated_init_marked_here);
10907  }
10908  getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
10909  }
10910  if (getCurFunction()->ObjCWarnForNoInitDelegation) {
10911  // Don't issue this warning for unavaialable inits.
10912  if (!MD->isUnavailable())
10913  Diag(MD->getLocation(),
10914  diag::warn_objc_secondary_init_missing_init_call);
10915  getCurFunction()->ObjCWarnForNoInitDelegation = false;
10916  }
10917  } else {
10918  return nullptr;
10919  }
10920 
10921  assert(!getCurFunction()->ObjCShouldCallSuper &&
10922  "This should only be set for ObjC methods, which should have been "
10923  "handled in the block above.");
10924 
10925  // Verify and clean out per-function state.
10926  if (Body && (!FD || !FD->isDefaulted())) {
10927  // C++ constructors that have function-try-blocks can't have return
10928  // statements in the handlers of that block. (C++ [except.handle]p14)
10929  // Verify this.
10930  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
10931  DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
10932 
10933  // Verify that gotos and switch cases don't jump into scopes illegally.
10934  if (getCurFunction()->NeedsScopeChecking() &&
10935  !PP.isCodeCompletionEnabled())
10936  DiagnoseInvalidJumps(Body);
10937 
10938  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
10939  if (!Destructor->getParent()->isDependentType())
10940  CheckDestructor(Destructor);
10941 
10942  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10943  Destructor->getParent());
10944  }
10945 
10946  // If any errors have occurred, clear out any temporaries that may have
10947  // been leftover. This ensures that these temporaries won't be picked up for
10948  // deletion in some later function.
10949  if (getDiagnostics().hasErrorOccurred() ||
10950  getDiagnostics().getSuppressAllDiagnostics()) {
10951  DiscardCleanupsInEvaluationContext();
10952  }
10953  if (!getDiagnostics().hasUncompilableErrorOccurred() &&
10954  !isa<FunctionTemplateDecl>(dcl)) {
10955  // Since the body is valid, issue any analysis-based warnings that are
10956  // enabled.
10957  ActivePolicy = &WP;
10958  }
10959 
10960  if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10961  (!CheckConstexprFunctionDecl(FD) ||
10962  !CheckConstexprFunctionBody(FD, Body)))
10963  FD->setInvalidDecl();
10964 
10965  if (FD && FD->hasAttr<NakedAttr>()) {
10966  for (const Stmt *S : Body->children()) {
10967  if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
10968  Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
10969  Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
10970  FD->setInvalidDecl();
10971  break;
10972  }
10973  }
10974  }
10975 
10976  assert(ExprCleanupObjects.size() ==
10977  ExprEvalContexts.back().NumCleanupObjects &&
10978  "Leftover temporaries in function");
10979  assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10980  assert(MaybeODRUseExprs.empty() &&
10981  "Leftover expressions for odr-use checking");
10982  }
10983 
10984  if (!IsInstantiation)
10985  PopDeclContext();
10986 
10987  PopFunctionScopeInfo(ActivePolicy, dcl);
10988  // If any errors have occurred, clear out any temporaries that may have
10989  // been leftover. This ensures that these temporaries won't be picked up for
10990  // deletion in some later function.
10991  if (getDiagnostics().hasErrorOccurred()) {
10992  DiscardCleanupsInEvaluationContext();
10993  }
10994 
10995  return dcl;
10996 }
10997 
10998 
10999 /// When we finish delayed parsing of an attribute, we must attach it to the
11000 /// relevant Decl.
11002  ParsedAttributes &Attrs) {
11003  // Always attach attributes to the underlying decl.
11004  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11005  D = TD->getTemplatedDecl();
11006  ProcessDeclAttributeList(S, D, Attrs.getList());
11007 
11008  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11009  if (Method->isStatic())
11010  checkThisInStaticMemberFunctionAttributes(Method);
11011 }
11012 
11013 
11014 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11015 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11017  IdentifierInfo &II, Scope *S) {
11018  // Before we produce a declaration for an implicitly defined
11019  // function, see whether there was a locally-scoped declaration of
11020  // this name as a function or variable. If so, use that
11021  // (non-visible) declaration, and complain about it.
11022  if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11023  Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11024  Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11025  return ExternCPrev;
11026  }
11027 
11028  // Extension in C99. Legal in C90, but warn about it.
11029  unsigned diag_id;
11030  if (II.getName().startswith("__builtin_"))
11031  diag_id = diag::warn_builtin_unknown;
11032  else if (getLangOpts().C99)
11033  diag_id = diag::ext_implicit_function_decl;
11034  else
11035  diag_id = diag::warn_implicit_function_decl;
11036  Diag(Loc, diag_id) << &II;
11037 
11038  // Because typo correction is expensive, only do it if the implicit
11039  // function declaration is going to be treated as an error.
11040  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11041  TypoCorrection Corrected;
11042  if (S &&
11043  (Corrected = CorrectTypo(
11044  DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11045  llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11046  diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11047  /*ErrorRecovery*/false);
11048  }
11049 
11050  // Set a Declarator for the implicit definition: int foo();
11051  const char *Dummy;
11052  AttributeFactory attrFactory;
11053  DeclSpec DS(attrFactory);
11054  unsigned DiagID;
11055  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11057  (void)Error; // Silence warning.
11058  assert(!Error && "Error setting up implicit decl!");
11059  SourceLocation NoLoc;
11061  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11062  /*IsAmbiguous=*/false,
11063  /*LParenLoc=*/NoLoc,
11064  /*Params=*/nullptr,
11065  /*NumParams=*/0,
11066  /*EllipsisLoc=*/NoLoc,
11067  /*RParenLoc=*/NoLoc,
11068  /*TypeQuals=*/0,
11069  /*RefQualifierIsLvalueRef=*/true,
11070  /*RefQualifierLoc=*/NoLoc,
11071  /*ConstQualifierLoc=*/NoLoc,
11072  /*VolatileQualifierLoc=*/NoLoc,
11073  /*RestrictQualifierLoc=*/NoLoc,
11074  /*MutableLoc=*/NoLoc,
11075  EST_None,
11076  /*ESpecLoc=*/NoLoc,
11077  /*Exceptions=*/nullptr,
11078  /*ExceptionRanges=*/nullptr,
11079  /*NumExceptions=*/0,
11080  /*NoexceptExpr=*/nullptr,
11081  /*ExceptionSpecTokens=*/nullptr,
11082  Loc, Loc, D),
11083  DS.getAttributes(),
11084  SourceLocation());
11085  D.SetIdentifier(&II, Loc);
11086 
11087  // Insert this function into translation-unit scope.
11088 
11089  DeclContext *PrevDC = CurContext;
11090  CurContext = Context.getTranslationUnitDecl();
11091 
11092  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11093  FD->setImplicit();
11094 
11095  CurContext = PrevDC;
11096 
11097  AddKnownFunctionAttributes(FD);
11098 
11099  return FD;
11100 }
11101 
11102 /// \brief Adds any function attributes that we know a priori based on
11103 /// the declaration of this function.
11104 ///
11105 /// These attributes can apply both to implicitly-declared builtins
11106 /// (like __builtin___printf_chk) or to library-declared functions
11107 /// like NSLog or printf.
11108 ///
11109 /// We need to check for duplicate attributes both here and where user-written
11110 /// attributes are applied to declarations.
11112  if (FD->isInvalidDecl())
11113  return;
11114 
11115  // If this is a built-in function, map its builtin attributes to
11116  // actual attributes.
11117  if (unsigned BuiltinID = FD->getBuiltinID()) {
11118  // Handle printf-formatting attributes.
11119  unsigned FormatIdx;
11120  bool HasVAListArg;
11121  if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11122  if (!FD->hasAttr<FormatAttr>()) {
11123  const char *fmt = "printf";
11124  unsigned int NumParams = FD->getNumParams();
11125  if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11126  FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11127  fmt = "NSString";
11128  FD->addAttr(FormatAttr::CreateImplicit(Context,
11129  &Context.Idents.get(fmt),
11130  FormatIdx+1,
11131  HasVAListArg ? 0 : FormatIdx+2,
11132  FD->getLocation()));
11133  }
11134  }
11135  if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11136  HasVAListArg)) {
11137  if (!FD->hasAttr<FormatAttr>())
11138  FD->addAttr(FormatAttr::CreateImplicit(Context,
11139  &Context.Idents.get("scanf"),
11140  FormatIdx+1,
11141  HasVAListArg ? 0 : FormatIdx+2,
11142  FD->getLocation()));
11143  }
11144 
11145  // Mark const if we don't care about errno and that is the only
11146  // thing preventing the function from being const. This allows
11147  // IRgen to use LLVM intrinsics for such functions.
11148  if (!getLangOpts().MathErrno &&
11150  if (!FD->hasAttr<ConstAttr>())
11151  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11152  }
11153 
11154  if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11155  !FD->hasAttr<ReturnsTwiceAttr>())
11156  FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11157  FD->getLocation()));
11158  if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11159  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11160  if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11161  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11162  }
11163 
11164  IdentifierInfo *Name = FD->getIdentifier();
11165  if (!Name)
11166  return;
11167  if ((!getLangOpts().CPlusPlus &&
11168  FD->getDeclContext()->isTranslationUnit()) ||
11169  (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11170  cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11172  // Okay: this could be a libc/libm/Objective-C function we know
11173  // about.
11174  } else
11175  return;
11176 
11177  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11178  // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11179  // target-specific builtins, perhaps?
11180  if (!FD->hasAttr<FormatAttr>())
11181  FD->addAttr(FormatAttr::CreateImplicit(Context,
11182  &Context.Idents.get("printf"), 2,
11183  Name->isStr("vasprintf") ? 0 : 3,
11184  FD->getLocation()));
11185  }
11186 
11187  if (Name->isStr("__CFStringMakeConstantString")) {
11188  // We already have a __builtin___CFStringMakeConstantString,
11189  // but builds that use -fno-constant-cfstrings don't go through that.
11190  if (!FD->hasAttr<FormatArgAttr>())
11191  FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11192  FD->getLocation()));
11193  }
11194 }
11195 
11197  TypeSourceInfo *TInfo) {
11198  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11199  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11200 
11201  if (!TInfo) {
11202  assert(D.isInvalidType() && "no declarator info for valid type");
11203  TInfo = Context.getTrivialTypeSourceInfo(T);
11204  }
11205 
11206  // Scope manipulation handled by caller.
11207  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11208  D.getLocStart(),
11209  D.getIdentifierLoc(),
11210  D.getIdentifier(),
11211  TInfo);
11212 
11213  // Bail out immediately if we have an invalid declaration.
11214  if (D.isInvalidType()) {
11215  NewTD->setInvalidDecl();
11216  return NewTD;
11217  }
11218 
11220  if (CurContext->isFunctionOrMethod())
11221  Diag(NewTD->getLocation(), diag::err_module_private_local)
11222  << 2 << NewTD->getDeclName()
11225  else
11226  NewTD->setModulePrivate();
11227  }
11228 
11229  // C++ [dcl.typedef]p8:
11230  // If the typedef declaration defines an unnamed class (or
11231  // enum), the first typedef-name declared by the declaration
11232  // to be that class type (or enum type) is used to denote the
11233  // class type (or enum type) for linkage purposes only.
11234  // We need to check whether the type was declared in the declaration.
11235  switch (D.getDeclSpec().getTypeSpecType()) {
11236  case TST_enum:
11237  case TST_struct:
11238  case TST_interface:
11239  case TST_union:
11240  case TST_class: {
11241  TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11242  setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11243  break;
11244  }
11245 
11246  default:
11247  break;
11248  }
11249 
11250  return NewTD;
11251 }
11252 
11253 
11254 /// \brief Check that this is a valid underlying type for an enum declaration.
11256  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11257  QualType T = TI->getType();
11258 
11259  if (T->isDependentType())
11260  return false;
11261 
11262  if (const BuiltinType *BT = T->getAs<BuiltinType>())
11263  if (BT->isInteger())
11264  return false;
11265 
11266  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11267  return true;
11268 }
11269 
11270 /// Check whether this is a valid redeclaration of a previous enumeration.
11271 /// \return true if the redeclaration was invalid.
11272 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
11273  QualType EnumUnderlyingTy,
11274  const EnumDecl *Prev) {
11275  bool IsFixed = !EnumUnderlyingTy.isNull();
11276 
11277  if (IsScoped != Prev->isScoped()) {
11278  Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11279  << Prev->isScoped();
11280  Diag(Prev->getLocation(), diag::note_previous_declaration);
11281  return true;
11282  }
11283 
11284  if (IsFixed && Prev->isFixed()) {
11285  if (!EnumUnderlyingTy->isDependentType() &&
11286  !Prev->getIntegerType()->isDependentType() &&
11287  !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11288  Prev->getIntegerType())) {
11289  // TODO: Highlight the underlying type of the redeclaration.
11290  Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11291  << EnumUnderlyingTy << Prev->getIntegerType();
11292  Diag(Prev->getLocation(), diag::note_previous_declaration)
11293  << Prev->getIntegerTypeRange();
11294  return true;
11295  }
11296  } else if (IsFixed != Prev->isFixed()) {
11297  Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11298  << Prev->isFixed();
11299  Diag(Prev->getLocation(), diag::note_previous_declaration);
11300  return true;
11301  }
11302 
11303  return false;
11304 }
11305 
11306 /// \brief Get diagnostic %select index for tag kind for
11307 /// redeclaration diagnostic message.
11308 /// WARNING: Indexes apply to particular diagnostics only!
11309 ///
11310 /// \returns diagnostic %select index.
11312  switch (Tag) {
11313  case TTK_Struct: return 0;
11314  case TTK_Interface: return 1;
11315  case TTK_Class: return 2;
11316  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11317  }
11318 }
11319 
11320 /// \brief Determine if tag kind is a class-key compatible with
11321 /// class for redeclaration (class, struct, or __interface).
11322 ///
11323 /// \returns true iff the tag kind is compatible.
11325 {
11326  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11327 }
11328 
11329 /// \brief Determine whether a tag with a given kind is acceptable
11330 /// as a redeclaration of the given tag declaration.
11331 ///
11332 /// \returns true if the new tag kind is acceptable, false otherwise.
11334  TagTypeKind NewTag, bool isDefinition,
11335  SourceLocation NewTagLoc,
11336  const IdentifierInfo *Name) {
11337  // C++ [dcl.type.elab]p3:
11338  // The class-key or enum keyword present in the
11339  // elaborated-type-specifier shall agree in kind with the
11340  // declaration to which the name in the elaborated-type-specifier
11341  // refers. This rule also applies to the form of
11342  // elaborated-type-specifier that declares a class-name or
11343  // friend class since it can be construed as referring to the
11344  // definition of the class. Thus, in any
11345  // elaborated-type-specifier, the enum keyword shall be used to
11346  // refer to an enumeration (7.2), the union class-key shall be
11347  // used to refer to a union (clause 9), and either the class or
11348  // struct class-key shall be used to refer to a class (clause 9)
11349  // declared using the class or struct class-key.
11350  TagTypeKind OldTag = Previous->getTagKind();
11351  if (!isDefinition || !isClassCompatTagKind(NewTag))
11352  if (OldTag == NewTag)
11353  return true;
11354 
11355  if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11356  // Warn about the struct/class tag mismatch.
11357  bool isTemplate = false;
11358  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11359  isTemplate = Record->getDescribedClassTemplate();
11360 
11361  if (!ActiveTemplateInstantiations.empty()) {
11362  // In a template instantiation, do not offer fix-its for tag mismatches
11363  // since they usually mess up the template instead of fixing the problem.
11364  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11365  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11366  << getRedeclDiagFromTagKind(OldTag);
11367  return true;
11368  }
11369 
11370  if (isDefinition) {
11371  // On definitions, check previous tags and issue a fix-it for each
11372  // one that doesn't match the current tag.
11373  if (Previous->getDefinition()) {
11374  // Don't suggest fix-its for redefinitions.
11375  return true;
11376  }
11377 
11378  bool previousMismatch = false;
11379  for (auto I : Previous->redecls()) {
11380  if (I->getTagKind() != NewTag) {
11381  if (!previousMismatch) {
11382  previousMismatch = true;
11383  Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11384  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11385  << getRedeclDiagFromTagKind(I->getTagKind());
11386  }
11387  Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11388  << getRedeclDiagFromTagKind(NewTag)
11389  << FixItHint::CreateReplacement(I->getInnerLocStart(),
11391  }
11392  }
11393  return true;
11394  }
11395 
11396  // Check for a previous definition. If current tag and definition
11397  // are same type, do nothing. If no definition, but disagree with
11398  // with previous tag type, give a warning, but no fix-it.
11399  const TagDecl *Redecl = Previous->getDefinition() ?
11400  Previous->getDefinition() : Previous;
11401  if (Redecl->getTagKind() == NewTag) {
11402  return true;
11403  }
11404 
11405  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11406  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11407  << getRedeclDiagFromTagKind(OldTag);
11408  Diag(Redecl->getLocation(), diag::note_previous_use);
11409 
11410  // If there is a previous definition, suggest a fix-it.
11411  if (Previous->getDefinition()) {
11412  Diag(NewTagLoc, diag::note_struct_class_suggestion)
11413  << getRedeclDiagFromTagKind(Redecl->getTagKind())
11416  }
11417 
11418  return true;
11419  }
11420  return false;
11421 }
11422 
11423 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11424 /// from an outer enclosing namespace or file scope inside a friend declaration.
11425 /// This should provide the commented out code in the following snippet:
11426 /// namespace N {
11427 /// struct X;
11428 /// namespace M {
11429 /// struct Y { friend struct /*N::*/ X; };
11430 /// }
11431 /// }
11433  SourceLocation NameLoc) {
11434  // While the decl is in a namespace, do repeated lookup of that name and see
11435  // if we get the same namespace back. If we do not, continue until
11436  // translation unit scope, at which point we have a fully qualified NNS.
11439  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11440  // This tag should be declared in a namespace, which can only be enclosed by
11441  // other namespaces. Bail if there's an anonymous namespace in the chain.
11442  NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11443  if (!Namespace || Namespace->isAnonymousNamespace())
11444  return FixItHint();
11445  IdentifierInfo *II = Namespace->getIdentifier();
11446  Namespaces.push_back(II);
11447  NamedDecl *Lookup = SemaRef.LookupSingleName(
11448  S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11449  if (Lookup == Namespace)
11450  break;
11451  }
11452 
11453  // Once we have all the namespaces, reverse them to go outermost first, and
11454  // build an NNS.
11455  SmallString<64> Insertion;
11456  llvm::raw_svector_ostream OS(Insertion);
11457  if (DC->isTranslationUnit())
11458  OS << "::";
11459  std::reverse(Namespaces.begin(), Namespaces.end());
11460  for (auto *II : Namespaces)
11461  OS << II->getName() << "::";
11462  OS.flush();
11463  return FixItHint::CreateInsertion(NameLoc, Insertion);
11464 }
11465 
11466 /// \brief Determine whether a tag originally declared in context \p OldDC can
11467 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11468 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11469 /// using-declaration).
11471  DeclContext *NewDC) {
11472  OldDC = OldDC->getRedeclContext();
11473  NewDC = NewDC->getRedeclContext();
11474 
11475  if (OldDC->Equals(NewDC))
11476  return true;
11477 
11478  // In MSVC mode, we allow a redeclaration if the contexts are related (either
11479  // encloses the other).
11480  if (S.getLangOpts().MSVCCompat &&
11481  (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11482  return true;
11483 
11484  return false;
11485 }
11486 
11487 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
11488 /// former case, Name will be non-null. In the later case, Name will be null.
11489 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11490 /// reference/declaration/definition of a tag.
11491 ///
11492 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11493 /// trailing-type-specifier) other than one in an alias-declaration.
11494 ///
11495 /// \param SkipBody If non-null, will be set to indicate if the caller should
11496 /// skip the definition of this tag and treat it as if it were a declaration.
11497 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11498  SourceLocation KWLoc, CXXScopeSpec &SS,
11499  IdentifierInfo *Name, SourceLocation NameLoc,
11501  SourceLocation ModulePrivateLoc,
11502  MultiTemplateParamsArg TemplateParameterLists,
11503  bool &OwnedDecl, bool &IsDependent,
11504  SourceLocation ScopedEnumKWLoc,
11505  bool ScopedEnumUsesClassTag,
11506  TypeResult UnderlyingType,
11507  bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11508  // If this is not a definition, it must have a name.
11509  IdentifierInfo *OrigName = Name;
11510  assert((Name != nullptr || TUK == TUK_Definition) &&
11511  "Nameless record must be a definition!");
11512  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11513 
11514  OwnedDecl = false;
11516  bool ScopedEnum = ScopedEnumKWLoc.isValid();
11517 
11518  // FIXME: Check explicit specializations more carefully.
11519  bool isExplicitSpecialization = false;
11520  bool Invalid = false;
11521 
11522  // We only need to do this matching if we have template parameters
11523  // or a scope specifier, which also conveniently avoids this work
11524  // for non-C++ cases.
11525  if (TemplateParameterLists.size() > 0 ||
11526  (SS.isNotEmpty() && TUK != TUK_Reference)) {
11527  if (TemplateParameterList *TemplateParams =
11528  MatchTemplateParametersToScopeSpecifier(
11529  KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11530  TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11531  if (Kind == TTK_Enum) {
11532  Diag(KWLoc, diag::err_enum_template);
11533  return nullptr;
11534  }
11535 
11536  if (TemplateParams->size() > 0) {
11537  // This is a declaration or definition of a class template (which may
11538  // be a member of another template).
11539 
11540  if (Invalid)
11541  return nullptr;
11542 
11543  OwnedDecl = false;
11544  DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11545  SS, Name, NameLoc, Attr,
11546  TemplateParams, AS,
11547  ModulePrivateLoc,
11548  /*FriendLoc*/SourceLocation(),
11549  TemplateParameterLists.size()-1,
11550  TemplateParameterLists.data(),
11551  SkipBody);
11552  return Result.get();
11553  } else {
11554  // The "template<>" header is extraneous.
11555  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11556  << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11557  isExplicitSpecialization = true;
11558  }
11559  }
11560  }
11561 
11562  // Figure out the underlying type if this a enum declaration. We need to do
11563  // this early, because it's needed to detect if this is an incompatible
11564  // redeclaration.
11565  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11566 
11567  if (Kind == TTK_Enum) {
11568  if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11569  // No underlying type explicitly specified, or we failed to parse the
11570  // type, default to int.
11571  EnumUnderlying = Context.IntTy.getTypePtr();
11572  else if (UnderlyingType.get()) {
11573  // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11574  // integral type; any cv-qualification is ignored.
11575  TypeSourceInfo *TI = nullptr;
11576  GetTypeFromParser(UnderlyingType.get(), &TI);
11577  EnumUnderlying = TI;
11578 
11579  if (CheckEnumUnderlyingType(TI))
11580  // Recover by falling back to int.
11581  EnumUnderlying = Context.IntTy.getTypePtr();
11582 
11583  if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11584  UPPC_FixedUnderlyingType))
11585  EnumUnderlying = Context.IntTy.getTypePtr();
11586 
11587  } else if (getLangOpts().MSVCCompat)
11588  // Microsoft enums are always of int type.
11589  EnumUnderlying = Context.IntTy.getTypePtr();
11590  }
11591 
11592  DeclContext *SearchDC = CurContext;
11593  DeclContext *DC = CurContext;
11594  bool isStdBadAlloc = false;
11595 
11596  RedeclarationKind Redecl = ForRedeclaration;
11597  if (TUK == TUK_Friend || TUK == TUK_Reference)
11598  Redecl = NotForRedeclaration;
11599 
11600  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11601  if (Name && SS.isNotEmpty()) {
11602  // We have a nested-name tag ('struct foo::bar').
11603 
11604  // Check for invalid 'foo::'.
11605  if (SS.isInvalid()) {
11606  Name = nullptr;
11607  goto CreateNewDecl;
11608  }
11609 
11610  // If this is a friend or a reference to a class in a dependent
11611  // context, don't try to make a decl for it.
11612  if (TUK == TUK_Friend || TUK == TUK_Reference) {
11613  DC = computeDeclContext(SS, false);
11614  if (!DC) {
11615  IsDependent = true;
11616  return nullptr;
11617  }
11618  } else {
11619  DC = computeDeclContext(SS, true);
11620  if (!DC) {
11621  Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11622  << SS.getRange();
11623  return nullptr;
11624  }
11625  }
11626 
11627  if (RequireCompleteDeclContext(SS, DC))
11628  return nullptr;
11629 
11630  SearchDC = DC;
11631  // Look-up name inside 'foo::'.
11632  LookupQualifiedName(Previous, DC);
11633 
11634  if (Previous.isAmbiguous())
11635  return nullptr;
11636 
11637  if (Previous.empty()) {
11638  // Name lookup did not find anything. However, if the
11639  // nested-name-specifier refers to the current instantiation,
11640  // and that current instantiation has any dependent base
11641  // classes, we might find something at instantiation time: treat
11642  // this as a dependent elaborated-type-specifier.
11643  // But this only makes any sense for reference-like lookups.
11644  if (Previous.wasNotFoundInCurrentInstantiation() &&
11645  (TUK == TUK_Reference || TUK == TUK_Friend)) {
11646  IsDependent = true;
11647  return nullptr;
11648  }
11649 
11650  // A tag 'foo::bar' must already exist.
11651  Diag(NameLoc, diag::err_not_tag_in_scope)
11652  << Kind << Name << DC << SS.getRange();
11653  Name = nullptr;
11654  Invalid = true;
11655  goto CreateNewDecl;
11656  }
11657  } else if (Name) {
11658  // C++14 [class.mem]p14:
11659  // If T is the name of a class, then each of the following shall have a
11660  // name different from T:
11661  // -- every member of class T that is itself a type
11662  if (TUK != TUK_Reference && TUK != TUK_Friend &&
11663  DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11664  return nullptr;
11665 
11666  // If this is a named struct, check to see if there was a previous forward
11667  // declaration or definition.
11668  // FIXME: We're looking into outer scopes here, even when we
11669  // shouldn't be. Doing so can result in ambiguities that we
11670  // shouldn't be diagnosing.
11671  LookupName(Previous, S);
11672 
11673  // When declaring or defining a tag, ignore ambiguities introduced
11674  // by types using'ed into this scope.
11675  if (Previous.isAmbiguous() &&
11676  (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11677  LookupResult::Filter F = Previous.makeFilter();
11678  while (F.hasNext()) {
11679  NamedDecl *ND = F.next();
11680  if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11681  F.erase();
11682  }
11683  F.done();
11684  }
11685 
11686  // C++11 [namespace.memdef]p3:
11687  // If the name in a friend declaration is neither qualified nor
11688  // a template-id and the declaration is a function or an
11689  // elaborated-type-specifier, the lookup to determine whether
11690  // the entity has been previously declared shall not consider
11691  // any scopes outside the innermost enclosing namespace.
11692  //
11693  // MSVC doesn't implement the above rule for types, so a friend tag
11694  // declaration may be a redeclaration of a type declared in an enclosing
11695  // scope. They do implement this rule for friend functions.
11696  //
11697  // Does it matter that this should be by scope instead of by
11698  // semantic context?
11699  if (!Previous.empty() && TUK == TUK_Friend) {
11700  DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11701  LookupResult::Filter F = Previous.makeFilter();
11702  bool FriendSawTagOutsideEnclosingNamespace = false;
11703  while (F.hasNext()) {
11704  NamedDecl *ND = F.next();
11706  if (DC->isFileContext() &&
11707  !EnclosingNS->Encloses(ND->getDeclContext())) {
11708  if (getLangOpts().MSVCCompat)
11709  FriendSawTagOutsideEnclosingNamespace = true;
11710  else
11711  F.erase();
11712  }
11713  }
11714  F.done();
11715 
11716  // Diagnose this MSVC extension in the easy case where lookup would have
11717  // unambiguously found something outside the enclosing namespace.
11718  if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11719  NamedDecl *ND = Previous.getFoundDecl();
11720  Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
11721  << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
11722  }
11723  }
11724 
11725  // Note: there used to be some attempt at recovery here.
11726  if (Previous.isAmbiguous())
11727  return nullptr;
11728 
11729  if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
11730  // FIXME: This makes sure that we ignore the contexts associated
11731  // with C structs, unions, and enums when looking for a matching
11732  // tag declaration or definition. See the similar lookup tweak
11733  // in Sema::LookupName; is there a better way to deal with this?
11734  while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
11735  SearchDC = SearchDC->getParent();
11736  }
11737  }
11738 
11739  if (Previous.isSingleResult() &&
11740  Previous.getFoundDecl()->isTemplateParameter()) {
11741  // Maybe we will complain about the shadowed template parameter.
11742  DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
11743  // Just pretend that we didn't see the previous declaration.
11744  Previous.clear();
11745  }
11746 
11747  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
11748  DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
11749  // This is a declaration of or a reference to "std::bad_alloc".
11750  isStdBadAlloc = true;
11751 
11752  if (Previous.empty() && StdBadAlloc) {
11753  // std::bad_alloc has been implicitly declared (but made invisible to
11754  // name lookup). Fill in this implicit declaration as the previous
11755  // declaration, so that the declarations get chained appropriately.
11756  Previous.addDecl(getStdBadAlloc());
11757  }
11758  }
11759 
11760  // If we didn't find a previous declaration, and this is a reference
11761  // (or friend reference), move to the correct scope. In C++, we
11762  // also need to do a redeclaration lookup there, just in case
11763  // there's a shadow friend decl.
11764  if (Name && Previous.empty() &&
11765  (TUK == TUK_Reference || TUK == TUK_Friend)) {
11766  if (Invalid) goto CreateNewDecl;
11767  assert(SS.isEmpty());
11768 
11769  if (TUK == TUK_Reference) {
11770  // C++ [basic.scope.pdecl]p5:
11771  // -- for an elaborated-type-specifier of the form
11772  //
11773  // class-key identifier
11774  //
11775  // if the elaborated-type-specifier is used in the
11776  // decl-specifier-seq or parameter-declaration-clause of a
11777  // function defined in namespace scope, the identifier is
11778  // declared as a class-name in the namespace that contains
11779  // the declaration; otherwise, except as a friend
11780  // declaration, the identifier is declared in the smallest
11781  // non-class, non-function-prototype scope that contains the
11782  // declaration.
11783  //
11784  // C99 6.7.2.3p8 has a similar (but not identical!) provision for
11785  // C structs and unions.
11786  //
11787  // It is an error in C++ to declare (rather than define) an enum
11788  // type, including via an elaborated type specifier. We'll
11789  // diagnose that later; for now, declare the enum in the same
11790  // scope as we would have picked for any other tag type.
11791  //
11792  // GNU C also supports this behavior as part of its incomplete
11793  // enum types extension, while GNU C++ does not.
11794  //
11795  // Find the context where we'll be declaring the tag.
11796  // FIXME: We would like to maintain the current DeclContext as the
11797  // lexical context,
11798  while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
11799  SearchDC = SearchDC->getParent();
11800 
11801  // Find the scope where we'll be declaring the tag.
11802  while (S->isClassScope() ||
11803  (getLangOpts().CPlusPlus &&
11804  S->isFunctionPrototypeScope()) ||
11805  ((S->getFlags() & Scope::DeclScope) == 0) ||
11806  (S->getEntity() && S->getEntity()->isTransparentContext()))
11807  S = S->getParent();
11808  } else {
11809  assert(TUK == TUK_Friend);
11810  // C++ [namespace.memdef]p3:
11811  // If a friend declaration in a non-local class first declares a
11812  // class or function, the friend class or function is a member of
11813  // the innermost enclosing namespace.
11814  SearchDC = SearchDC->getEnclosingNamespaceContext();
11815  }
11816 
11817  // In C++, we need to do a redeclaration lookup to properly
11818  // diagnose some problems.
11819  if (getLangOpts().CPlusPlus) {
11820  Previous.setRedeclarationKind(ForRedeclaration);
11821  LookupQualifiedName(Previous, SearchDC);
11822  }
11823  }
11824 
11825  // If we have a known previous declaration to use, then use it.
11826  if (Previous.empty() && SkipBody && SkipBody->Previous)
11827  Previous.addDecl(SkipBody->Previous);
11828 
11829  if (!Previous.empty()) {
11830  NamedDecl *PrevDecl = Previous.getFoundDecl();
11831  NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
11832 
11833  // It's okay to have a tag decl in the same scope as a typedef
11834  // which hides a tag decl in the same scope. Finding this
11835  // insanity with a redeclaration lookup can only actually happen
11836  // in C++.
11837  //
11838  // This is also okay for elaborated-type-specifiers, which is
11839  // technically forbidden by the current standard but which is
11840  // okay according to the likely resolution of an open issue;
11841  // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
11842  if (getLangOpts().CPlusPlus) {
11843  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11844  if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
11845  TagDecl *Tag = TT->getDecl();
11846  if (Tag->getDeclName() == Name &&
11848  ->Equals(TD->getDeclContext()->getRedeclContext())) {
11849  PrevDecl = Tag;
11850  Previous.clear();
11851  Previous.addDecl(Tag);
11852  Previous.resolveKind();
11853  }
11854  }
11855  }
11856  }
11857 
11858  // If this is a redeclaration of a using shadow declaration, it must
11859  // declare a tag in the same context. In MSVC mode, we allow a
11860  // redefinition if either context is within the other.
11861  if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
11862  auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
11863  if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
11864  isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
11865  !(OldTag && isAcceptableTagRedeclContext(
11866  *this, OldTag->getDeclContext(), SearchDC))) {
11867  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
11868  Diag(Shadow->getTargetDecl()->getLocation(),
11869  diag::note_using_decl_target);
11870  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
11871  << 0;
11872  // Recover by ignoring the old declaration.
11873  Previous.clear();
11874  goto CreateNewDecl;
11875  }
11876  }
11877 
11878  if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
11879  // If this is a use of a previous tag, or if the tag is already declared
11880  // in the same scope (so that the definition/declaration completes or
11881  // rementions the tag), reuse the decl.
11882  if (TUK == TUK_Reference || TUK == TUK_Friend ||
11883  isDeclInScope(DirectPrevDecl, SearchDC, S,
11884  SS.isNotEmpty() || isExplicitSpecialization)) {
11885  // Make sure that this wasn't declared as an enum and now used as a
11886  // struct or something similar.
11887  if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
11888  TUK == TUK_Definition, KWLoc,
11889  Name)) {
11890  bool SafeToContinue
11891  = (PrevTagDecl->getTagKind() != TTK_Enum &&
11892  Kind != TTK_Enum);
11893  if (SafeToContinue)
11894  Diag(KWLoc, diag::err_use_with_wrong_tag)
11895  << Name
11897  PrevTagDecl->getKindName());
11898  else
11899  Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
11900  Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
11901 
11902  if (SafeToContinue)
11903  Kind = PrevTagDecl->getTagKind();
11904  else {
11905  // Recover by making this an anonymous redefinition.
11906  Name = nullptr;
11907  Previous.clear();
11908  Invalid = true;
11909  }
11910  }
11911 
11912  if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
11913  const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
11914 
11915  // If this is an elaborated-type-specifier for a scoped enumeration,
11916  // the 'class' keyword is not necessary and not permitted.
11917  if (TUK == TUK_Reference || TUK == TUK_Friend) {
11918  if (ScopedEnum)
11919  Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
11920  << PrevEnum->isScoped()
11921  << FixItHint::CreateRemoval(ScopedEnumKWLoc);
11922  return PrevTagDecl;
11923  }
11924 
11925  QualType EnumUnderlyingTy;
11926  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11927  EnumUnderlyingTy = TI->getType().getUnqualifiedType();
11928  else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
11929  EnumUnderlyingTy = QualType(T, 0);
11930 
11931  // All conflicts with previous declarations are recovered by
11932  // returning the previous declaration, unless this is a definition,
11933  // in which case we want the caller to bail out.
11934  if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
11935  ScopedEnum, EnumUnderlyingTy, PrevEnum))
11936  return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
11937  }
11938 
11939  // C++11 [class.mem]p1:
11940  // A member shall not be declared twice in the member-specification,
11941  // except that a nested class or member class template can be declared
11942  // and then later defined.
11943  if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
11944  S->isDeclScope(PrevDecl)) {
11945  Diag(NameLoc, diag::ext_member_redeclared);
11946  Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
11947  }
11948 
11949  if (!Invalid) {
11950  // If this is a use, just return the declaration we found, unless
11951  // we have attributes.
11952 
11953  // FIXME: In the future, return a variant or some other clue
11954  // for the consumer of this Decl to know it doesn't own it.
11955  // For our current ASTs this shouldn't be a problem, but will
11956  // need to be changed with DeclGroups.
11957  if (!Attr &&
11958  ((TUK == TUK_Reference &&
11959  (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
11960  || TUK == TUK_Friend))
11961  return PrevTagDecl;
11962 
11963  // Diagnose attempts to redefine a tag.
11964  if (TUK == TUK_Definition) {
11965  if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
11966  // If we're defining a specialization and the previous definition
11967  // is from an implicit instantiation, don't emit an error
11968  // here; we'll catch this in the general case below.
11969  bool IsExplicitSpecializationAfterInstantiation = false;
11970  if (isExplicitSpecialization) {
11971  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
11972  IsExplicitSpecializationAfterInstantiation =
11973  RD->getTemplateSpecializationKind() !=
11975  else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
11976  IsExplicitSpecializationAfterInstantiation =
11977  ED->getTemplateSpecializationKind() !=
11979  }
11980 
11981  NamedDecl *Hidden = nullptr;
11982  if (SkipBody && getLangOpts().CPlusPlus &&
11983  !hasVisibleDefinition(Def, &Hidden)) {
11984  // There is a definition of this tag, but it is not visible. We
11985  // explicitly make use of C++'s one definition rule here, and
11986  // assume that this definition is identical to the hidden one
11987  // we already have. Make the existing definition visible and
11988  // use it in place of this one.
11989  SkipBody->ShouldSkip = true;
11990  makeMergedDefinitionVisible(Hidden, KWLoc);
11991  return Def;
11992  } else if (!IsExplicitSpecializationAfterInstantiation) {
11993  // A redeclaration in function prototype scope in C isn't
11994  // visible elsewhere, so merely issue a warning.
11995  if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
11996  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
11997  else
11998  Diag(NameLoc, diag::err_redefinition) << Name;
11999  Diag(Def->getLocation(), diag::note_previous_definition);
12000  // If this is a redefinition, recover by making this
12001  // struct be anonymous, which will make any later
12002  // references get the previous definition.
12003  Name = nullptr;
12004  Previous.clear();
12005  Invalid = true;
12006  }
12007  } else {
12008  // If the type is currently being defined, complain
12009  // about a nested redefinition.
12010  auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12011  if (TD->isBeingDefined()) {
12012  Diag(NameLoc, diag::err_nested_redefinition) << Name;
12013  Diag(PrevTagDecl->getLocation(),
12014  diag::note_previous_definition);
12015  Name = nullptr;
12016  Previous.clear();
12017  Invalid = true;
12018  }
12019  }
12020 
12021  // Okay, this is definition of a previously declared or referenced
12022  // tag. We're going to create a new Decl for it.
12023  }
12024 
12025  // Okay, we're going to make a redeclaration. If this is some kind
12026  // of reference, make sure we build the redeclaration in the same DC
12027  // as the original, and ignore the current access specifier.
12028  if (TUK == TUK_Friend || TUK == TUK_Reference) {
12029  SearchDC = PrevTagDecl->getDeclContext();
12030  AS = AS_none;
12031  }
12032  }
12033  // If we get here we have (another) forward declaration or we
12034  // have a definition. Just create a new decl.
12035 
12036  } else {
12037  // If we get here, this is a definition of a new tag type in a nested
12038  // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12039  // new decl/type. We set PrevDecl to NULL so that the entities
12040  // have distinct types.
12041  Previous.clear();
12042  }
12043  // If we get here, we're going to create a new Decl. If PrevDecl
12044  // is non-NULL, it's a definition of the tag declared by
12045  // PrevDecl. If it's NULL, we have a new definition.
12046 
12047 
12048  // Otherwise, PrevDecl is not a tag, but was found with tag
12049  // lookup. This is only actually possible in C++, where a few
12050  // things like templates still live in the tag namespace.
12051  } else {
12052  // Use a better diagnostic if an elaborated-type-specifier
12053  // found the wrong kind of type on the first
12054  // (non-redeclaration) lookup.
12055  if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12056  !Previous.isForRedeclaration()) {
12057  unsigned Kind = 0;
12058  if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12059  else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12060  else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12061  Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12062  Diag(PrevDecl->getLocation(), diag::note_declared_at);
12063  Invalid = true;
12064 
12065  // Otherwise, only diagnose if the declaration is in scope.
12066  } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12067  SS.isNotEmpty() || isExplicitSpecialization)) {
12068  // do nothing
12069 
12070  // Diagnose implicit declarations introduced by elaborated types.
12071  } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12072  unsigned Kind = 0;
12073  if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12074  else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12075  else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12076  Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12077  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12078  Invalid = true;
12079 
12080  // Otherwise it's a declaration. Call out a particularly common
12081  // case here.
12082  } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12083  unsigned Kind = 0;
12084  if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12085  Diag(NameLoc, diag::err_tag_definition_of_typedef)
12086  << Name << Kind << TND->getUnderlyingType();
12087  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12088  Invalid = true;
12089 
12090  // Otherwise, diagnose.
12091  } else {
12092  // The tag name clashes with something else in the target scope,
12093  // issue an error and recover by making this tag be anonymous.
12094  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12095  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12096  Name = nullptr;
12097  Invalid = true;
12098  }
12099 
12100  // The existing declaration isn't relevant to us; we're in a
12101  // new scope, so clear out the previous declaration.
12102  Previous.clear();
12103  }
12104  }
12105 
12106 CreateNewDecl:
12107 
12108  TagDecl *PrevDecl = nullptr;
12109  if (Previous.isSingleResult())
12110  PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12111 
12112  // If there is an identifier, use the location of the identifier as the
12113  // location of the decl, otherwise use the location of the struct/union
12114  // keyword.
12115  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12116 
12117  // Otherwise, create a new declaration. If there is a previous
12118  // declaration of the same entity, the two will be linked via
12119  // PrevDecl.
12120  TagDecl *New;
12121 
12122  bool IsForwardReference = false;
12123  if (Kind == TTK_Enum) {
12124  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12125  // enum X { A, B, C } D; D should chain to X.
12126  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12127  cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12128  ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12129  // If this is an undefined enum, warn.
12130  if (TUK != TUK_Definition && !Invalid) {
12131  TagDecl *Def;
12132  if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12133  cast<EnumDecl>(New)->isFixed()) {
12134  // C++0x: 7.2p2: opaque-enum-declaration.
12135  // Conflicts are diagnosed above. Do nothing.
12136  }
12137  else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12138  Diag(Loc, diag::ext_forward_ref_enum_def)
12139  << New;
12140  Diag(Def->getLocation(), diag::note_previous_definition);
12141  } else {
12142  unsigned DiagID = diag::ext_forward_ref_enum;
12143  if (getLangOpts().MSVCCompat)
12144  DiagID = diag::ext_ms_forward_ref_enum;
12145  else if (getLangOpts().CPlusPlus)
12146  DiagID = diag::err_forward_ref_enum;
12147  Diag(Loc, DiagID);
12148 
12149  // If this is a forward-declared reference to an enumeration, make a
12150  // note of it; we won't actually be introducing the declaration into
12151  // the declaration context.
12152  if (TUK == TUK_Reference)
12153  IsForwardReference = true;
12154  }
12155  }
12156 
12157  if (EnumUnderlying) {
12158  EnumDecl *ED = cast<EnumDecl>(New);
12159  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12160  ED->setIntegerTypeSourceInfo(TI);
12161  else
12162  ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12163  ED->setPromotionType(ED->getIntegerType());
12164  }
12165 
12166  } else {
12167  // struct/union/class
12168 
12169  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12170  // struct X { int A; } D; D should chain to X.
12171  if (getLangOpts().CPlusPlus) {
12172  // FIXME: Look for a way to use RecordDecl for simple structs.
12173  New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12174  cast_or_null<CXXRecordDecl>(PrevDecl));
12175 
12176  if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12177  StdBadAlloc = cast<CXXRecordDecl>(New);
12178  } else
12179  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12180  cast_or_null<RecordDecl>(PrevDecl));
12181  }
12182 
12183  // C++11 [dcl.type]p3:
12184  // A type-specifier-seq shall not define a class or enumeration [...].
12185  if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12186  Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12187  << Context.getTagDeclType(New);
12188  Invalid = true;
12189  }
12190 
12191  // Maybe add qualifier info.
12192  if (SS.isNotEmpty()) {
12193  if (SS.isSet()) {
12194  // If this is either a declaration or a definition, check the
12195  // nested-name-specifier against the current context. We don't do this
12196  // for explicit specializations, because they have similar checking
12197  // (with more specific diagnostics) in the call to
12198  // CheckMemberSpecialization, below.
12199  if (!isExplicitSpecialization &&
12200  (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12201  diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12202  Invalid = true;
12203 
12205  if (TemplateParameterLists.size() > 0) {
12207  TemplateParameterLists.size(),
12208  TemplateParameterLists.data());
12209  }
12210  }
12211  else
12212  Invalid = true;
12213  }
12214 
12215  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12216  // Add alignment attributes if necessary; these attributes are checked when
12217  // the ASTContext lays out the structure.
12218  //
12219  // It is important for implementing the correct semantics that this
12220  // happen here (in act on tag decl). The #pragma pack stack is
12221  // maintained as a result of parser callbacks which can occur at
12222  // many points during the parsing of a struct declaration (because
12223  // the #pragma tokens are effectively skipped over during the
12224  // parsing of the struct).
12225  if (TUK == TUK_Definition) {
12226  AddAlignmentAttributesForRecord(RD);
12227  AddMsStructLayoutForRecord(RD);
12228  }
12229  }
12230 
12231  if (ModulePrivateLoc.isValid()) {
12232  if (isExplicitSpecialization)
12233  Diag(New->getLocation(), diag::err_module_private_specialization)
12234  << 2
12235  << FixItHint::CreateRemoval(ModulePrivateLoc);
12236  // __module_private__ does not apply to local classes. However, we only
12237  // diagnose this as an error when the declaration specifiers are
12238  // freestanding. Here, we just ignore the __module_private__.
12239  else if (!SearchDC->isFunctionOrMethod())
12240  New->setModulePrivate();
12241  }
12242 
12243  // If this is a specialization of a member class (of a class template),
12244  // check the specialization.
12245  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12246  Invalid = true;
12247 
12248  // If we're declaring or defining a tag in function prototype scope in C,
12249  // note that this type can only be used within the function and add it to
12250  // the list of decls to inject into the function definition scope.
12251  if ((Name || Kind == TTK_Enum) &&
12252  getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12253  if (getLangOpts().CPlusPlus) {
12254  // C++ [dcl.fct]p6:
12255  // Types shall not be defined in return or parameter types.
12256  if (TUK == TUK_Definition && !IsTypeSpecifier) {
12257  Diag(Loc, diag::err_type_defined_in_param_type)
12258  << Name;
12259  Invalid = true;
12260  }
12261  } else {
12262  Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12263  }
12264  DeclsInPrototypeScope.push_back(New);
12265  }
12266 
12267  if (Invalid)
12268  New->setInvalidDecl();
12269 
12270  if (Attr)
12271  ProcessDeclAttributeList(S, New, Attr);
12272 
12273  // Set the lexical context. If the tag has a C++ scope specifier, the
12274  // lexical context will be different from the semantic context.
12275  New->setLexicalDeclContext(CurContext);
12276 
12277  // Mark this as a friend decl if applicable.
12278  // In Microsoft mode, a friend declaration also acts as a forward
12279  // declaration so we always pass true to setObjectOfFriendDecl to make
12280  // the tag name visible.
12281  if (TUK == TUK_Friend)
12282  New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12283 
12284  // Set the access specifier.
12285  if (!Invalid && SearchDC->isRecord())
12286  SetMemberAccessSpecifier(New, PrevDecl, AS);
12287 
12288  if (TUK == TUK_Definition)
12289  New->startDefinition();
12290 
12291  // If this has an identifier, add it to the scope stack.
12292  if (TUK == TUK_Friend) {
12293  // We might be replacing an existing declaration in the lookup tables;
12294  // if so, borrow its access specifier.
12295  if (PrevDecl)
12296  New->setAccess(PrevDecl->getAccess());
12297 
12299  DC->makeDeclVisibleInContext(New);
12300  if (Name) // can be null along some error paths
12301  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12302  PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12303  } else if (Name) {
12304  S = getNonFieldDeclScope(S);
12305  PushOnScopeChains(New, S, !IsForwardReference);
12306  if (IsForwardReference)
12307  SearchDC->makeDeclVisibleInContext(New);
12308 
12309  } else {
12310  CurContext->addDecl(New);
12311  }
12312 
12313  // If this is the C FILE type, notify the AST context.
12314  if (IdentifierInfo *II = New->getIdentifier())
12315  if (!New->isInvalidDecl() &&
12317  II->isStr("FILE"))
12318  Context.setFILEDecl(New);
12319 
12320  if (PrevDecl)
12321  mergeDeclAttributes(New, PrevDecl);
12322 
12323  // If there's a #pragma GCC visibility in scope, set the visibility of this
12324  // record.
12325  AddPushedVisibilityAttribute(New);
12326 
12327  OwnedDecl = true;
12328  // In C++, don't return an invalid declaration. We can't recover well from
12329  // the cases where we make the type anonymous.
12330  return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12331 }
12332 
12334  AdjustDeclIfTemplate(TagD);
12335  TagDecl *Tag = cast<TagDecl>(TagD);
12336 
12337  // Enter the tag context.
12338  PushDeclContext(S, Tag);
12339 
12340  ActOnDocumentableDecl(TagD);
12341 
12342  // If there's a #pragma GCC visibility in scope, set the visibility of this
12343  // record.
12344  AddPushedVisibilityAttribute(Tag);
12345 }
12346 
12348  assert(isa<ObjCContainerDecl>(IDecl) &&
12349  "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12350  DeclContext *OCD = cast<DeclContext>(IDecl);
12351  assert(getContainingDC(OCD) == CurContext &&
12352  "The next DeclContext should be lexically contained in the current one.");
12353  CurContext = OCD;
12354  return IDecl;
12355 }
12356 
12358  SourceLocation FinalLoc,
12359  bool IsFinalSpelledSealed,
12360  SourceLocation LBraceLoc) {
12361  AdjustDeclIfTemplate(TagD);
12362  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12363 
12364  FieldCollector->StartClass();
12365 
12366  if (!Record->getIdentifier())
12367  return;
12368 
12369  if (FinalLoc.isValid())
12370  Record->addAttr(new (Context)
12371  FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12372 
12373  // C++ [class]p2:
12374  // [...] The class-name is also inserted into the scope of the
12375  // class itself; this is known as the injected-class-name. For
12376  // purposes of access checking, the injected-class-name is treated
12377  // as if it were a public member name.
12378  CXXRecordDecl *InjectedClassName
12379  = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12380  Record->getLocStart(), Record->getLocation(),
12381  Record->getIdentifier(),
12382  /*PrevDecl=*/nullptr,
12383  /*DelayTypeCreation=*/true);
12384  Context.getTypeDeclType(InjectedClassName, Record);
12385  InjectedClassName->setImplicit();
12386  InjectedClassName->setAccess(AS_public);
12387  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12388  InjectedClassName->setDescribedClassTemplate(Template);
12389  PushOnScopeChains(InjectedClassName, S);
12390  assert(InjectedClassName->isInjectedClassName() &&
12391  "Broken injected-class-name");
12392 }
12393 
12395  SourceLocation RBraceLoc) {
12396  AdjustDeclIfTemplate(TagD);
12397  TagDecl *Tag = cast<TagDecl>(TagD);
12398  Tag->setRBraceLoc(RBraceLoc);
12399 
12400  // Make sure we "complete" the definition even it is invalid.
12401  if (Tag->isBeingDefined()) {
12402  assert(Tag->isInvalidDecl() && "We should already have completed it");
12403  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12404  RD->completeDefinition();
12405  }
12406 
12407  if (isa<CXXRecordDecl>(Tag))
12408  FieldCollector->FinishClass();
12409 
12410  // Exit this scope of this tag's definition.
12411  PopDeclContext();
12412 
12413  if (getCurLexicalContext()->isObjCContainer() &&
12414  Tag->getDeclContext()->isFileContext())
12416 
12417  // Notify the consumer that we've defined a tag.
12418  if (!Tag->isInvalidDecl())
12419  Consumer.HandleTagDeclDefinition(Tag);
12420 }
12421 
12423  // Exit this scope of this interface definition.
12424  PopDeclContext();
12425 }
12426 
12428  assert(DC == CurContext && "Mismatch of container contexts");
12429  OriginalLexicalContext = DC;
12430  ActOnObjCContainerFinishDefinition();
12431 }
12432 
12434  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12435  OriginalLexicalContext = nullptr;
12436 }
12437 
12439  AdjustDeclIfTemplate(TagD);
12440  TagDecl *Tag = cast<TagDecl>(TagD);
12441  Tag->setInvalidDecl();
12442 
12443  // Make sure we "complete" the definition even it is invalid.
12444  if (Tag->isBeingDefined()) {
12445  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12446  RD->completeDefinition();
12447  }
12448 
12449  // We're undoing ActOnTagStartDefinition here, not
12450  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12451  // the FieldCollector.
12452 
12453  PopDeclContext();
12454 }
12455 
12456 // Note that FieldName may be null for anonymous bitfields.
12458  IdentifierInfo *FieldName,
12459  QualType FieldTy, bool IsMsStruct,
12460  Expr *BitWidth, bool *ZeroWidth) {
12461  // Default to true; that shouldn't confuse checks for emptiness
12462  if (ZeroWidth)
12463  *ZeroWidth = true;
12464 
12465  // C99 6.7.2.1p4 - verify the field type.
12466  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12467  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12468  // Handle incomplete types with specific error.
12469  if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12470  return ExprError();
12471  if (FieldName)
12472  return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12473  << FieldName << FieldTy << BitWidth->getSourceRange();
12474  return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12475  << FieldTy << BitWidth->getSourceRange();
12476  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12477  UPPC_BitFieldWidth))
12478  return ExprError();
12479 
12480  // If the bit-width is type- or value-dependent, don't try to check
12481  // it now.
12482  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12483  return BitWidth;
12484 
12485  llvm::APSInt Value;
12486  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12487  if (ICE.isInvalid())
12488  return ICE;
12489  BitWidth = ICE.get();
12490 
12491  if (Value != 0 && ZeroWidth)
12492  *ZeroWidth = false;
12493 
12494  // Zero-width bitfield is ok for anonymous field.
12495  if (Value == 0 && FieldName)
12496  return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12497 
12498  if (Value.isSigned() && Value.isNegative()) {
12499  if (FieldName)
12500  return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12501  << FieldName << Value.toString(10);
12502  return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12503  << Value.toString(10);
12504  }
12505 
12506  if (!FieldTy->isDependentType()) {
12507  uint64_t TypeSize = Context.getTypeSize(FieldTy);
12508  if (Value.getZExtValue() > TypeSize) {
12509  if (!getLangOpts().CPlusPlus || IsMsStruct ||
12511  if (FieldName)
12512  return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
12513  << FieldName << (unsigned)Value.getZExtValue()
12514  << (unsigned)TypeSize;
12515 
12516  return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
12517  << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12518  }
12519 
12520  if (FieldName)
12521  Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
12522  << FieldName << (unsigned)Value.getZExtValue()
12523  << (unsigned)TypeSize;
12524  else
12525  Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
12526  << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
12527  }
12528  }
12529 
12530  return BitWidth;
12531 }
12532 
12533 /// ActOnField - Each field of a C struct/union is passed into this in order
12534 /// to create a FieldDecl object for it.
12536  Declarator &D, Expr *BitfieldWidth) {
12537  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12538  DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12539  /*InitStyle=*/ICIS_NoInit, AS_public);
12540  return Res;
12541 }
12542 
12543 /// HandleField - Analyze a field of a C struct or a C++ data member.
12544 ///
12546  SourceLocation DeclStart,
12547  Declarator &D, Expr *BitWidth,
12548  InClassInitStyle InitStyle,
12549  AccessSpecifier AS) {
12550  IdentifierInfo *II = D.getIdentifier();
12551  SourceLocation Loc = DeclStart;
12552  if (II) Loc = D.getIdentifierLoc();
12553 
12554  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12555  QualType T = TInfo->getType();
12556  if (getLangOpts().CPlusPlus) {
12557  CheckExtraCXXDefaultArguments(D);
12558 
12559  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12560  UPPC_DataMemberType)) {
12561  D.setInvalidType();
12562  T = Context.IntTy;
12563  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12564  }
12565  }
12566 
12567  // TR 18037 does not allow fields to be declared with address spaces.
12568  if (T.getQualifiers().hasAddressSpace()) {
12569  Diag(Loc, diag::err_field_with_address_space);
12570  D.setInvalidType();
12571  }
12572 
12573  // OpenCL 1.2 spec, s6.9 r:
12574  // The event type cannot be used to declare a structure or union field.
12575  if (LangOpts.OpenCL && T->isEventT()) {
12576  Diag(Loc, diag::err_event_t_struct_field);
12577  D.setInvalidType();
12578  }
12579 
12580  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12581 
12584  diag::err_invalid_thread)
12585  << DeclSpec::getSpecifierName(TSCS);
12586 
12587  // Check to see if this name was declared as a member previously
12588  NamedDecl *PrevDecl = nullptr;
12589  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12590  LookupName(Previous, S);
12591  switch (Previous.getResultKind()) {
12592  case LookupResult::Found:
12594  PrevDecl = Previous.getAsSingle<NamedDecl>();
12595  break;
12596 
12598  PrevDecl = Previous.getRepresentativeDecl();
12599  break;
12600 
12604  break;
12605  }
12606  Previous.suppressDiagnostics();
12607 
12608  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12609  // Maybe we will complain about the shadowed template parameter.
12610  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12611  // Just pretend that we didn't see the previous declaration.
12612  PrevDecl = nullptr;
12613  }
12614 
12615  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12616  PrevDecl = nullptr;
12617 
12618  bool Mutable
12620  SourceLocation TSSL = D.getLocStart();
12621  FieldDecl *NewFD
12622  = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12623  TSSL, AS, PrevDecl, &D);
12624 
12625  if (NewFD->isInvalidDecl())
12626  Record->setInvalidDecl();
12627 
12629  NewFD->setModulePrivate();
12630 
12631  if (NewFD->isInvalidDecl() && PrevDecl) {
12632  // Don't introduce NewFD into scope; there's already something
12633  // with the same name in the same scope.
12634  } else if (II) {
12635  PushOnScopeChains(NewFD, S);
12636  } else
12637  Record->addDecl(NewFD);
12638 
12639  return NewFD;
12640 }
12641 
12642 /// \brief Build a new FieldDecl and check its well-formedness.
12643 ///
12644 /// This routine builds a new FieldDecl given the fields name, type,
12645 /// record, etc. \p PrevDecl should refer to any previous declaration
12646 /// with the same name and in the same scope as the field to be
12647 /// created.
12648 ///
12649 /// \returns a new FieldDecl.
12650 ///
12651 /// \todo The Declarator argument is a hack. It will be removed once
12653  TypeSourceInfo *TInfo,
12654  RecordDecl *Record, SourceLocation Loc,
12655  bool Mutable, Expr *BitWidth,
12656  InClassInitStyle InitStyle,
12657  SourceLocation TSSL,
12658  AccessSpecifier AS, NamedDecl *PrevDecl,
12659  Declarator *D) {
12660  IdentifierInfo *II = Name.getAsIdentifierInfo();
12661  bool InvalidDecl = false;
12662  if (D) InvalidDecl = D->isInvalidType();
12663 
12664  // If we receive a broken type, recover by assuming 'int' and
12665  // marking this declaration as invalid.
12666  if (T.isNull()) {
12667  InvalidDecl = true;
12668  T = Context.IntTy;
12669  }
12670 
12671  QualType EltTy = Context.getBaseElementType(T);
12672  if (!EltTy->isDependentType()) {
12673  if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12674  // Fields of incomplete type force their record to be invalid.
12675  Record->setInvalidDecl();
12676  InvalidDecl = true;
12677  } else {
12678  NamedDecl *Def;
12679  EltTy->isIncompleteType(&Def);
12680  if (Def && Def->isInvalidDecl()) {
12681  Record->setInvalidDecl();
12682  InvalidDecl = true;
12683  }
12684  }
12685  }
12686 
12687  // OpenCL v1.2 s6.9.c: bitfields are not supported.
12688  if (BitWidth && getLangOpts().OpenCL) {
12689  Diag(Loc, diag::err_opencl_bitfields);
12690  InvalidDecl = true;
12691  }
12692 
12693  // C99 6.7.2.1p8: A member of a structure or union may have any type other
12694  // than a variably modified type.
12695  if (!InvalidDecl && T->isVariablyModifiedType()) {
12696  bool SizeIsNegative;
12697  llvm::APSInt Oversized;
12698 
12699  TypeSourceInfo *FixedTInfo =
12701  SizeIsNegative,
12702  Oversized);
12703  if (FixedTInfo) {
12704  Diag(Loc, diag::warn_illegal_constant_array_size);
12705  TInfo = FixedTInfo;
12706  T = FixedTInfo->getType();
12707  } else {
12708  if (SizeIsNegative)
12709  Diag(Loc, diag::err_typecheck_negative_array_size);
12710  else if (Oversized.getBoolValue())
12711  Diag(Loc, diag::err_array_too_large)
12712  << Oversized.toString(10);
12713  else
12714  Diag(Loc, diag::err_typecheck_field_variable_size);
12715  InvalidDecl = true;
12716  }
12717  }
12718 
12719  // Fields can not have abstract class types
12720  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
12721  diag::err_abstract_type_in_decl,
12722  AbstractFieldType))
12723  InvalidDecl = true;
12724 
12725  bool ZeroWidth = false;
12726  if (InvalidDecl)
12727  BitWidth = nullptr;
12728  // If this is declared as a bit-field, check the bit-field.
12729  if (BitWidth) {
12730  BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
12731  &ZeroWidth).get();
12732  if (!BitWidth) {
12733  InvalidDecl = true;
12734  BitWidth = nullptr;
12735  ZeroWidth = false;
12736  }
12737  }
12738 
12739  // Check that 'mutable' is consistent with the type of the declaration.
12740  if (!InvalidDecl && Mutable) {
12741  unsigned DiagID = 0;
12742  if (T->isReferenceType())
12743  DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
12744  : diag::err_mutable_reference;
12745  else if (T.isConstQualified())
12746  DiagID = diag::err_mutable_const;
12747 
12748  if (DiagID) {
12749  SourceLocation ErrLoc = Loc;
12750  if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
12751  ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
12752  Diag(ErrLoc, DiagID);
12753  if (DiagID != diag::ext_mutable_reference) {
12754  Mutable = false;
12755  InvalidDecl = true;
12756  }
12757  }
12758  }
12759 
12760  // C++11 [class.union]p8 (DR1460):
12761  // At most one variant member of a union may have a
12762  // brace-or-equal-initializer.
12763  if (InitStyle != ICIS_NoInit)
12764  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
12765 
12766  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
12767  BitWidth, Mutable, InitStyle);
12768  if (InvalidDecl)
12769  NewFD->setInvalidDecl();
12770 
12771  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
12772  Diag(Loc, diag::err_duplicate_member) << II;
12773  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12774  NewFD->setInvalidDecl();
12775  }
12776 
12777  if (!InvalidDecl && getLangOpts().CPlusPlus) {
12778  if (Record->isUnion()) {
12779  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12780  CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
12781  if (RDecl->getDefinition()) {
12782  // C++ [class.union]p1: An object of a class with a non-trivial
12783  // constructor, a non-trivial copy constructor, a non-trivial
12784  // destructor, or a non-trivial copy assignment operator
12785  // cannot be a member of a union, nor can an array of such
12786  // objects.
12787  if (CheckNontrivialField(NewFD))
12788  NewFD->setInvalidDecl();
12789  }
12790  }
12791 
12792  // C++ [class.union]p1: If a union contains a member of reference type,
12793  // the program is ill-formed, except when compiling with MSVC extensions
12794  // enabled.
12795  if (EltTy->isReferenceType()) {
12796  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
12797  diag::ext_union_member_of_reference_type :
12798  diag::err_union_member_of_reference_type)
12799  << NewFD->getDeclName() << EltTy;
12800  if (!getLangOpts().MicrosoftExt)
12801  NewFD->setInvalidDecl();
12802  }
12803  }
12804  }
12805 
12806  // FIXME: We need to pass in the attributes given an AST
12807  // representation, not a parser representation.
12808  if (D) {
12809  // FIXME: The current scope is almost... but not entirely... correct here.
12810  ProcessDeclAttributes(getCurScope(), NewFD, *D);
12811 
12812  if (NewFD->hasAttrs())
12813  CheckAlignasUnderalignment(NewFD);
12814  }
12815 
12816  // In auto-retain/release, infer strong retension for fields of
12817  // retainable type.
12818  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
12819  NewFD->setInvalidDecl();
12820 
12821  if (T.isObjCGCWeak())
12822  Diag(Loc, diag::warn_attribute_weak_on_field);
12823 
12824  NewFD->setAccess(AS);
12825  return NewFD;
12826 }
12827 
12829  assert(FD);
12830  assert(getLangOpts().CPlusPlus && "valid check only for C++");
12831 
12832  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
12833  return false;
12834 
12835  QualType EltTy = Context.getBaseElementType(FD->getType());
12836  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
12837  CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
12838  if (RDecl->getDefinition()) {
12839  // We check for copy constructors before constructors
12840  // because otherwise we'll never get complaints about
12841  // copy constructors.
12842 
12843  CXXSpecialMember member = CXXInvalid;
12844  // We're required to check for any non-trivial constructors. Since the
12845  // implicit default constructor is suppressed if there are any
12846  // user-declared constructors, we just need to check that there is a
12847  // trivial default constructor and a trivial copy constructor. (We don't
12848  // worry about move constructors here, since this is a C++98 check.)
12849  if (RDecl->hasNonTrivialCopyConstructor())
12850  member = CXXCopyConstructor;
12851  else if (!RDecl->hasTrivialDefaultConstructor())
12852  member = CXXDefaultConstructor;
12853  else if (RDecl->hasNonTrivialCopyAssignment())
12854  member = CXXCopyAssignment;
12855  else if (RDecl->hasNonTrivialDestructor())
12856  member = CXXDestructor;
12857 
12858  if (member != CXXInvalid) {
12859  if (!getLangOpts().CPlusPlus11 &&
12860  getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
12861  // Objective-C++ ARC: it is an error to have a non-trivial field of
12862  // a union. However, system headers in Objective-C programs
12863  // occasionally have Objective-C lifetime objects within unions,
12864  // and rather than cause the program to fail, we make those
12865  // members unavailable.
12866  SourceLocation Loc = FD->getLocation();
12867  if (getSourceManager().isInSystemHeader(Loc)) {
12868  if (!FD->hasAttr<UnavailableAttr>())
12869  FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12870  "this system field has retaining ownership",
12871  Loc));
12872  return false;
12873  }
12874  }
12875 
12876  Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
12877  diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
12878  diag::err_illegal_union_or_anon_struct_member)
12879  << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
12880  DiagnoseNontrivial(RDecl, member);
12881  return !getLangOpts().CPlusPlus11;
12882  }
12883  }
12884  }
12885 
12886  return false;
12887 }
12888 
12889 /// TranslateIvarVisibility - Translate visibility from a token ID to an
12890 /// AST enum value.
12893  switch (ivarVisibility) {
12894  default: llvm_unreachable("Unknown visitibility kind");
12895  case tok::objc_private: return ObjCIvarDecl::Private;
12896  case tok::objc_public: return ObjCIvarDecl::Public;
12897  case tok::objc_protected: return ObjCIvarDecl::Protected;
12898  case tok::objc_package: return ObjCIvarDecl::Package;
12899  }
12900 }
12901 
12902 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
12903 /// in order to create an IvarDecl object for it.
12905  SourceLocation DeclStart,
12906  Declarator &D, Expr *BitfieldWidth,
12908 
12909  IdentifierInfo *II = D.getIdentifier();
12910  Expr *BitWidth = (Expr*)BitfieldWidth;
12911  SourceLocation Loc = DeclStart;
12912  if (II) Loc = D.getIdentifierLoc();
12913 
12914  // FIXME: Unnamed fields can be handled in various different ways, for
12915  // example, unnamed unions inject all members into the struct namespace!
12916 
12917  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12918  QualType T = TInfo->getType();
12919 
12920  if (BitWidth) {
12921  // 6.7.2.1p3, 6.7.2.1p4
12922  BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
12923  if (!BitWidth)
12924  D.setInvalidType();
12925  } else {
12926  // Not a bitfield.
12927 
12928  // validate II.
12929 
12930  }
12931  if (T->isReferenceType()) {
12932  Diag(Loc, diag::err_ivar_reference_type);
12933  D.setInvalidType();
12934  }
12935  // C99 6.7.2.1p8: A member of a structure or union may have any type other
12936  // than a variably modified type.
12937  else if (T->isVariablyModifiedType()) {
12938  Diag(Loc, diag::err_typecheck_ivar_variable_size);
12939  D.setInvalidType();
12940  }
12941 
12942  // Get the visibility (access control) for this ivar.
12944  Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
12946  // Must set ivar's DeclContext to its enclosing interface.
12947  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
12948  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
12949  return nullptr;
12950  ObjCContainerDecl *EnclosingContext;
12951  if (ObjCImplementationDecl *IMPDecl =
12952  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12953  if (LangOpts.ObjCRuntime.isFragile()) {
12954  // Case of ivar declared in an implementation. Context is that of its class.
12955  EnclosingContext = IMPDecl->getClassInterface();
12956  assert(EnclosingContext && "Implementation has no class interface!");
12957  }
12958  else
12959  EnclosingContext = EnclosingDecl;
12960  } else {
12961  if (ObjCCategoryDecl *CDecl =
12962  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12963  if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
12964  Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
12965  return nullptr;
12966  }
12967  }
12968  EnclosingContext = EnclosingDecl;
12969  }
12970 
12971  // Construct the decl.
12972  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
12973  DeclStart, Loc, II, T,
12974  TInfo, ac, (Expr *)BitfieldWidth);
12975 
12976  if (II) {
12977  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
12978  ForRedeclaration);
12979  if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
12980  && !isa<TagDecl>(PrevDecl)) {
12981  Diag(Loc, diag::err_duplicate_member) << II;
12982  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12983  NewID->setInvalidDecl();
12984  }
12985  }
12986 
12987  // Process attributes attached to the ivar.
12988  ProcessDeclAttributes(S, NewID, D);
12989 
12990  if (D.isInvalidType())
12991  NewID->setInvalidDecl();
12992 
12993  // In ARC, infer 'retaining' for ivars of retainable type.
12994  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
12995  NewID->setInvalidDecl();
12996 
12998  NewID->setModulePrivate();
12999 
13000  if (II) {
13001  // FIXME: When interfaces are DeclContexts, we'll need to add
13002  // these to the interface.
13003  S->AddDecl(NewID);
13004  IdResolver.AddDecl(NewID);
13005  }
13006 
13007  if (LangOpts.ObjCRuntime.isNonFragile() &&
13008  !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13009  Diag(Loc, diag::warn_ivars_in_interface);
13010 
13011  return NewID;
13012 }
13013 
13014 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13015 /// class and class extensions. For every class \@interface and class
13016 /// extension \@interface, if the last ivar is a bitfield of any type,
13017 /// then add an implicit `char :0` ivar to the end of that interface.
13019  SmallVectorImpl<Decl *> &AllIvarDecls) {
13020  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13021  return;
13022 
13023  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13024  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13025 
13026  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13027  return;
13028  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13029  if (!ID) {
13030  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13031  if (!CD->IsClassExtension())
13032  return;
13033  }
13034  // No need to add this to end of @implementation.
13035  else
13036  return;
13037  }
13038  // All conditions are met. Add a new bitfield to the tail end of ivars.
13039  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13040  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13041 
13042  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13043  DeclLoc, DeclLoc, nullptr,
13044  Context.CharTy,
13046  DeclLoc),
13048  true);
13049  AllIvarDecls.push_back(Ivar);
13050 }
13051 
13052 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13053  ArrayRef<Decl *> Fields, SourceLocation LBrac,
13054  SourceLocation RBrac, AttributeList *Attr) {
13055  assert(EnclosingDecl && "missing record or interface decl");
13056 
13057  // If this is an Objective-C @implementation or category and we have
13058  // new fields here we should reset the layout of the interface since
13059  // it will now change.
13060  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13061  ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13062  switch (DC->getKind()) {
13063  default: break;
13064  case Decl::ObjCCategory:
13065  Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13066  break;
13067  case Decl::ObjCImplementation:
13068  Context.
13069  ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13070  break;
13071  }
13072  }
13073 
13074  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13075 
13076  // Start counting up the number of named members; make sure to include
13077  // members of anonymous structs and unions in the total.
13078  unsigned NumNamedMembers = 0;
13079  if (Record) {
13080  for (const auto *I : Record->decls()) {
13081  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13082  if (IFD->getDeclName())
13083  ++NumNamedMembers;
13084  }
13085  }
13086 
13087  // Verify that all the fields are okay.
13088  SmallVector<FieldDecl*, 32> RecFields;
13089 
13090  bool ARCErrReported = false;
13091  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13092  i != end; ++i) {
13093  FieldDecl *FD = cast<FieldDecl>(*i);
13094 
13095  // Get the type for the field.
13096  const Type *FDTy = FD->getType().getTypePtr();
13097 
13098  if (!FD->isAnonymousStructOrUnion()) {
13099  // Remember all fields written by the user.
13100  RecFields.push_back(FD);
13101  }
13102 
13103  // If the field is already invalid for some reason, don't emit more
13104  // diagnostics about it.
13105  if (FD->isInvalidDecl()) {
13106  EnclosingDecl->setInvalidDecl();
13107  continue;
13108  }
13109 
13110  // C99 6.7.2.1p2:
13111  // A structure or union shall not contain a member with
13112  // incomplete or function type (hence, a structure shall not
13113  // contain an instance of itself, but may contain a pointer to
13114  // an instance of itself), except that the last member of a
13115  // structure with more than one named member may have incomplete
13116  // array type; such a structure (and any union containing,
13117  // possibly recursively, a member that is such a structure)
13118  // shall not be a member of a structure or an element of an
13119  // array.
13120  if (FDTy->isFunctionType()) {
13121  // Field declared as a function.
13122  Diag(FD->getLocation(), diag::err_field_declared_as_function)
13123  << FD->getDeclName();
13124  FD->setInvalidDecl();
13125  EnclosingDecl->setInvalidDecl();
13126  continue;
13127  } else if (FDTy->isIncompleteArrayType() && Record &&
13128  ((i + 1 == Fields.end() && !Record->isUnion()) ||
13129  ((getLangOpts().MicrosoftExt ||
13130  getLangOpts().CPlusPlus) &&
13131  (i + 1 == Fields.end() || Record->isUnion())))) {
13132  // Flexible array member.
13133  // Microsoft and g++ is more permissive regarding flexible array.
13134  // It will accept flexible array in union and also
13135  // as the sole element of a struct/class.
13136  unsigned DiagID = 0;
13137  if (Record->isUnion())
13138  DiagID = getLangOpts().MicrosoftExt
13139  ? diag::ext_flexible_array_union_ms
13140  : getLangOpts().CPlusPlus
13141  ? diag::ext_flexible_array_union_gnu
13142  : diag::err_flexible_array_union;
13143  else if (Fields.size() == 1)
13144  DiagID = getLangOpts().MicrosoftExt
13145  ? diag::ext_flexible_array_empty_aggregate_ms
13146  : getLangOpts().CPlusPlus
13147  ? diag::ext_flexible_array_empty_aggregate_gnu
13148  : NumNamedMembers < 1
13149  ? diag::err_flexible_array_empty_aggregate
13150  : 0;
13151 
13152  if (DiagID)
13153  Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13154  << Record->getTagKind();
13155  // While the layout of types that contain virtual bases is not specified
13156  // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13157  // virtual bases after the derived members. This would make a flexible
13158  // array member declared at the end of an object not adjacent to the end
13159  // of the type.
13160  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13161  if (RD->getNumVBases() != 0)
13162  Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13163  << FD->getDeclName() << Record->getTagKind();
13164  if (!getLangOpts().C99)
13165  Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13166  << FD->getDeclName() << Record->getTagKind();
13167 
13168  // If the element type has a non-trivial destructor, we would not
13169  // implicitly destroy the elements, so disallow it for now.
13170  //
13171  // FIXME: GCC allows this. We should probably either implicitly delete
13172  // the destructor of the containing class, or just allow this.
13173  QualType BaseElem = Context.getBaseElementType(FD->getType());
13174  if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13175  Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13176  << FD->getDeclName() << FD->getType();
13177  FD->setInvalidDecl();
13178  EnclosingDecl->setInvalidDecl();
13179  continue;
13180  }
13181  // Okay, we have a legal flexible array member at the end of the struct.
13182  Record->setHasFlexibleArrayMember(true);
13183  } else if (!FDTy->isDependentType() &&
13184  RequireCompleteType(FD->getLocation(), FD->getType(),
13185  diag::err_field_incomplete)) {
13186  // Incomplete type
13187  FD->setInvalidDecl();
13188  EnclosingDecl->setInvalidDecl();
13189  continue;
13190  } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13191  if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13192  // A type which contains a flexible array member is considered to be a
13193  // flexible array member.
13194  Record->setHasFlexibleArrayMember(true);
13195  if (!Record->isUnion()) {
13196  // If this is a struct/class and this is not the last element, reject
13197  // it. Note that GCC supports variable sized arrays in the middle of
13198  // structures.
13199  if (i + 1 != Fields.end())
13200  Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13201  << FD->getDeclName() << FD->getType();
13202  else {
13203  // We support flexible arrays at the end of structs in
13204  // other structs as an extension.
13205  Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13206  << FD->getDeclName();
13207  }
13208  }
13209  }
13210  if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13211  RequireNonAbstractType(FD->getLocation(), FD->getType(),
13212  diag::err_abstract_type_in_decl,
13213  AbstractIvarType)) {
13214  // Ivars can not have abstract class types
13215  FD->setInvalidDecl();
13216  }
13217  if (Record && FDTTy->getDecl()->hasObjectMember())
13218  Record->setHasObjectMember(true);
13219  if (Record && FDTTy->getDecl()->hasVolatileMember())
13220  Record->setHasVolatileMember(true);
13221  } else if (FDTy->isObjCObjectType()) {
13222  /// A field cannot be an Objective-c object
13223  Diag(FD->getLocation(), diag::err_statically_allocated_object)
13224  << FixItHint::CreateInsertion(FD->getLocation(), "*");
13226  FD->setType(T);
13227  } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13228  (!getLangOpts().CPlusPlus || Record->isUnion())) {
13229  // It's an error in ARC if a field has lifetime.
13230  // We don't want to report this in a system header, though,
13231  // so we just make the field unavailable.
13232  // FIXME: that's really not sufficient; we need to make the type
13233  // itself invalid to, say, initialize or copy.
13234  QualType T = FD->getType();
13236  if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13237  SourceLocation loc = FD->getLocation();
13238  if (getSourceManager().isInSystemHeader(loc)) {
13239  if (!FD->hasAttr<UnavailableAttr>()) {
13240  FD->addAttr(UnavailableAttr::CreateImplicit(Context,
13241  "this system field has retaining ownership",
13242  loc));
13243  }
13244  } else {
13245  Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13246  << T->isBlockPointerType() << Record->getTagKind();
13247  }
13248  ARCErrReported = true;
13249  }
13250  } else if (getLangOpts().ObjC1 &&
13251  getLangOpts().getGC() != LangOptions::NonGC &&
13252  Record && !Record->hasObjectMember()) {
13253  if (FD->getType()->isObjCObjectPointerType() ||
13254  FD->getType().isObjCGCStrong())
13255  Record->setHasObjectMember(true);
13256  else if (Context.getAsArrayType(FD->getType())) {
13257  QualType BaseType = Context.getBaseElementType(FD->getType());
13258  if (BaseType->isRecordType() &&
13259  BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13260  Record->setHasObjectMember(true);
13261  else if (BaseType->isObjCObjectPointerType() ||
13262  BaseType.isObjCGCStrong())
13263  Record->setHasObjectMember(true);
13264  }
13265  }
13266  if (Record && FD->getType().isVolatileQualified())
13267  Record->setHasVolatileMember(true);
13268  // Keep track of the number of named members.
13269  if (FD->getIdentifier())
13270  ++NumNamedMembers;
13271  }
13272 
13273  // Okay, we successfully defined 'Record'.
13274  if (Record) {
13275  bool Completed = false;
13276  if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13277  if (!CXXRecord->isInvalidDecl()) {
13278  // Set access bits correctly on the directly-declared conversions.
13280  I = CXXRecord->conversion_begin(),
13281  E = CXXRecord->conversion_end(); I != E; ++I)
13282  I.setAccess((*I)->getAccess());
13283 
13284  if (!CXXRecord->isDependentType()) {
13285  if (CXXRecord->hasUserDeclaredDestructor()) {
13286  // Adjust user-defined destructor exception spec.
13287  if (getLangOpts().CPlusPlus11)
13288  AdjustDestructorExceptionSpec(CXXRecord,
13289  CXXRecord->getDestructor());
13290  }
13291 
13292  // Add any implicitly-declared members to this class.
13293  AddImplicitlyDeclaredMembersToClass(CXXRecord);
13294 
13295  // If we have virtual base classes, we may end up finding multiple
13296  // final overriders for a given virtual function. Check for this
13297  // problem now.
13298  if (CXXRecord->getNumVBases()) {
13299  CXXFinalOverriderMap FinalOverriders;
13300  CXXRecord->getFinalOverriders(FinalOverriders);
13301 
13302  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13303  MEnd = FinalOverriders.end();
13304  M != MEnd; ++M) {
13305  for (OverridingMethods::iterator SO = M->second.begin(),
13306  SOEnd = M->second.end();
13307  SO != SOEnd; ++SO) {
13308  assert(SO->second.size() > 0 &&
13309  "Virtual function without overridding functions?");
13310  if (SO->second.size() == 1)
13311  continue;
13312 
13313  // C++ [class.virtual]p2:
13314  // In a derived class, if a virtual member function of a base
13315  // class subobject has more than one final overrider the
13316  // program is ill-formed.
13317  Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13318  << (const NamedDecl *)M->first << Record;
13319  Diag(M->first->getLocation(),
13320  diag::note_overridden_virtual_function);
13322  OM = SO->second.begin(),
13323  OMEnd = SO->second.end();
13324  OM != OMEnd; ++OM)
13325  Diag(OM->Method->getLocation(), diag::note_final_overrider)
13326  << (const NamedDecl *)M->first << OM->Method->getParent();
13327 
13328  Record->setInvalidDecl();
13329  }
13330  }
13331  CXXRecord->completeDefinition(&FinalOverriders);
13332  Completed = true;
13333  }
13334  }
13335  }
13336  }
13337 
13338  if (!Completed)
13339  Record->completeDefinition();
13340 
13341  if (Record->hasAttrs()) {
13342  CheckAlignasUnderalignment(Record);
13343 
13344  if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13345  checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13346  IA->getRange(), IA->getBestCase(),
13347  IA->getSemanticSpelling());
13348  }
13349 
13350  // Check if the structure/union declaration is a type that can have zero
13351  // size in C. For C this is a language extension, for C++ it may cause
13352  // compatibility problems.
13353  bool CheckForZeroSize;
13354  if (!getLangOpts().CPlusPlus) {
13355  CheckForZeroSize = true;
13356  } else {
13357  // For C++ filter out types that cannot be referenced in C code.
13358  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13359  CheckForZeroSize =
13360  CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13361  !CXXRecord->isDependentType() &&
13362  CXXRecord->isCLike();
13363  }
13364  if (CheckForZeroSize) {
13365  bool ZeroSize = true;
13366  bool IsEmpty = true;
13367  unsigned NonBitFields = 0;
13368  for (RecordDecl::field_iterator I = Record->field_begin(),
13369  E = Record->field_end();
13370  (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13371  IsEmpty = false;
13372  if (I->isUnnamedBitfield()) {
13373  if (I->getBitWidthValue(Context) > 0)
13374  ZeroSize = false;
13375  } else {
13376  ++NonBitFields;
13377  QualType FieldType = I->getType();
13378  if (FieldType->isIncompleteType() ||
13379  !Context.getTypeSizeInChars(FieldType).isZero())
13380  ZeroSize = false;
13381  }
13382  }
13383 
13384  // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13385  // allowed in C++, but warn if its declaration is inside
13386  // extern "C" block.
13387  if (ZeroSize) {
13388  Diag(RecLoc, getLangOpts().CPlusPlus ?
13389  diag::warn_zero_size_struct_union_in_extern_c :
13390  diag::warn_zero_size_struct_union_compat)
13391  << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13392  }
13393 
13394  // Structs without named members are extension in C (C99 6.7.2.1p7),
13395  // but are accepted by GCC.
13396  if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13397  Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13398  diag::ext_no_named_members_in_struct_union)
13399  << Record->isUnion();
13400  }
13401  }
13402  } else {
13403  ObjCIvarDecl **ClsFields =
13404  reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13405  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13406  ID->setEndOfDefinitionLoc(RBrac);
13407  // Add ivar's to class's DeclContext.
13408  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13409  ClsFields[i]->setLexicalDeclContext(ID);
13410  ID->addDecl(ClsFields[i]);
13411  }
13412  // Must enforce the rule that ivars in the base classes may not be
13413  // duplicates.
13414  if (ID->getSuperClass())
13415  DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13416  } else if (ObjCImplementationDecl *IMPDecl =
13417  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13418  assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13419  for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13420  // Ivar declared in @implementation never belongs to the implementation.
13421  // Only it is in implementation's lexical context.
13422  ClsFields[I]->setLexicalDeclContext(IMPDecl);
13423  CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13424  IMPDecl->setIvarLBraceLoc(LBrac);
13425  IMPDecl->setIvarRBraceLoc(RBrac);
13426  } else if (ObjCCategoryDecl *CDecl =
13427  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13428  // case of ivars in class extension; all other cases have been
13429  // reported as errors elsewhere.
13430  // FIXME. Class extension does not have a LocEnd field.
13431  // CDecl->setLocEnd(RBrac);
13432  // Add ivar's to class extension's DeclContext.
13433  // Diagnose redeclaration of private ivars.
13434  ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13435  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13436  if (IDecl) {
13437  if (const ObjCIvarDecl *ClsIvar =
13438  IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13439  Diag(ClsFields[i]->getLocation(),
13440  diag::err_duplicate_ivar_declaration);
13441  Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13442  continue;
13443  }
13444  for (const auto *Ext : IDecl->known_extensions()) {
13445  if (const ObjCIvarDecl *ClsExtIvar
13446  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13447  Diag(ClsFields[i]->getLocation(),
13448  diag::err_duplicate_ivar_declaration);
13449  Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13450  continue;
13451  }
13452  }
13453  }
13454  ClsFields[i]->setLexicalDeclContext(CDecl);
13455  CDecl->addDecl(ClsFields[i]);
13456  }
13457  CDecl->setIvarLBraceLoc(LBrac);
13458  CDecl->setIvarRBraceLoc(RBrac);
13459  }
13460  }
13461 
13462  if (Attr)
13463  ProcessDeclAttributeList(S, Record, Attr);
13464 }
13465 
13466 /// \brief Determine whether the given integral value is representable within
13467 /// the given type T.
13469  llvm::APSInt &Value,
13470  QualType T) {
13471  assert(T->isIntegralType(Context) && "Integral type required!");
13472  unsigned BitWidth = Context.getIntWidth(T);
13473 
13474  if (Value.isUnsigned() || Value.isNonNegative()) {
13476  --BitWidth;
13477  return Value.getActiveBits() <= BitWidth;
13478  }
13479  return Value.getMinSignedBits() <= BitWidth;
13480 }
13481 
13482 // \brief Given an integral type, return the next larger integral type
13483 // (or a NULL type of no such type exists).
13485  // FIXME: Int128/UInt128 support, which also needs to be introduced into
13486  // enum checking below.
13487  assert(T->isIntegralType(Context) && "Integral type required!");
13488  const unsigned NumTypes = 4;
13489  QualType SignedIntegralTypes[NumTypes] = {
13490  Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13491  };
13492  QualType UnsignedIntegralTypes[NumTypes] = {
13493  Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13494  Context.UnsignedLongLongTy
13495  };
13496 
13497  unsigned BitWidth = Context.getTypeSize(T);
13498  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13499  : UnsignedIntegralTypes;
13500  for (unsigned I = 0; I != NumTypes; ++I)
13501  if (Context.getTypeSize(Types[I]) > BitWidth)
13502  return Types[I];
13503 
13504  return QualType();
13505 }
13506 
13508  EnumConstantDecl *LastEnumConst,
13509  SourceLocation IdLoc,
13510  IdentifierInfo *Id,
13511  Expr *Val) {
13512  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13513  llvm::APSInt EnumVal(IntWidth);
13514  QualType EltTy;
13515 
13516  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13517  Val = nullptr;
13518 
13519  if (Val)
13520  Val = DefaultLvalueConversion(Val).get();
13521 
13522  if (Val) {
13523  if (Enum->isDependentType() || Val->isTypeDependent())
13524  EltTy = Context.DependentTy;
13525  else {
13526  SourceLocation ExpLoc;
13527  if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13528  !getLangOpts().MSVCCompat) {
13529  // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13530  // constant-expression in the enumerator-definition shall be a converted
13531  // constant expression of the underlying type.
13532  EltTy = Enum->getIntegerType();
13533  ExprResult Converted =
13534  CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13535  CCEK_Enumerator);
13536  if (Converted.isInvalid())
13537  Val = nullptr;
13538  else
13539  Val = Converted.get();
13540  } else if (!Val->isValueDependent() &&
13541  !(Val = VerifyIntegerConstantExpression(Val,
13542  &EnumVal).get())) {
13543  // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13544  } else {
13545  if (Enum->isFixed()) {
13546  EltTy = Enum->getIntegerType();
13547 
13548  // In Obj-C and Microsoft mode, require the enumeration value to be
13549  // representable in the underlying type of the enumeration. In C++11,
13550  // we perform a non-narrowing conversion as part of converted constant
13551  // expression checking.
13552  if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13553  if (getLangOpts().MSVCCompat) {
13554  Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13555  Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13556  } else
13557  Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13558  } else
13559  Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13560  } else if (getLangOpts().CPlusPlus) {
13561  // C++11 [dcl.enum]p5:
13562  // If the underlying type is not fixed, the type of each enumerator
13563  // is the type of its initializing value:
13564  // - If an initializer is specified for an enumerator, the
13565  // initializing value has the same type as the expression.
13566  EltTy = Val->getType();
13567  } else {
13568  // C99 6.7.2.2p2:
13569  // The expression that defines the value of an enumeration constant
13570  // shall be an integer constant expression that has a value
13571  // representable as an int.
13572 
13573  // Complain if the value is not representable in an int.
13575  Diag(IdLoc, diag::ext_enum_value_not_int)
13576  << EnumVal.toString(10) << Val->getSourceRange()
13577  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13578  else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13579  // Force the type of the expression to 'int'.
13580  Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13581  }
13582  EltTy = Val->getType();
13583  }
13584  }
13585  }
13586  }
13587 
13588  if (!Val) {
13589  if (Enum->isDependentType())
13590  EltTy = Context.DependentTy;
13591  else if (!LastEnumConst) {
13592  // C++0x [dcl.enum]p5:
13593  // If the underlying type is not fixed, the type of each enumerator
13594  // is the type of its initializing value:
13595  // - If no initializer is specified for the first enumerator, the
13596  // initializing value has an unspecified integral type.
13597  //
13598  // GCC uses 'int' for its unspecified integral type, as does
13599  // C99 6.7.2.2p3.
13600  if (Enum->isFixed()) {
13601  EltTy = Enum->getIntegerType();
13602  }
13603  else {
13604  EltTy = Context.IntTy;
13605  }
13606  } else {
13607  // Assign the last value + 1.
13608  EnumVal = LastEnumConst->getInitVal();
13609  ++EnumVal;
13610  EltTy = LastEnumConst->getType();
13611 
13612  // Check for overflow on increment.
13613  if (EnumVal < LastEnumConst->getInitVal()) {
13614  // C++0x [dcl.enum]p5:
13615  // If the underlying type is not fixed, the type of each enumerator
13616  // is the type of its initializing value:
13617  //
13618  // - Otherwise the type of the initializing value is the same as
13619  // the type of the initializing value of the preceding enumerator
13620  // unless the incremented value is not representable in that type,
13621  // in which case the type is an unspecified integral type
13622  // sufficient to contain the incremented value. If no such type
13623  // exists, the program is ill-formed.
13625  if (T.isNull() || Enum->isFixed()) {
13626  // There is no integral type larger enough to represent this
13627  // value. Complain, then allow the value to wrap around.
13628  EnumVal = LastEnumConst->getInitVal();
13629  EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13630  ++EnumVal;
13631  if (Enum->isFixed())
13632  // When the underlying type is fixed, this is ill-formed.
13633  Diag(IdLoc, diag::err_enumerator_wrapped)
13634  << EnumVal.toString(10)
13635  << EltTy;
13636  else
13637  Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13638  << EnumVal.toString(10);
13639  } else {
13640  EltTy = T;
13641  }
13642 
13643  // Retrieve the last enumerator's value, extent that type to the
13644  // type that is supposed to be large enough to represent the incremented
13645  // value, then increment.
13646  EnumVal = LastEnumConst->getInitVal();
13647  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13648  EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13649  ++EnumVal;
13650 
13651  // If we're not in C++, diagnose the overflow of enumerator values,
13652  // which in C99 means that the enumerator value is not representable in
13653  // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13654  // permits enumerator values that are representable in some larger
13655  // integral type.
13656  if (!getLangOpts().CPlusPlus && !T.isNull())
13657  Diag(IdLoc, diag::warn_enum_value_overflow);
13658  } else if (!getLangOpts().CPlusPlus &&
13659  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13660  // Enforce C99 6.7.2.2p2 even when we compute the next value.
13661  Diag(IdLoc, diag::ext_enum_value_not_int)
13662  << EnumVal.toString(10) << 1;
13663  }
13664  }
13665  }
13666 
13667  if (!EltTy->isDependentType()) {
13668  // Make the enumerator value match the signedness and size of the
13669  // enumerator's type.
13670  EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13671  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13672  }
13673 
13674  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13675  Val, EnumVal);
13676 }
13677 
13679  SourceLocation IILoc) {
13680  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
13682  return SkipBodyInfo();
13683 
13684  // We have an anonymous enum definition. Look up the first enumerator to
13685  // determine if we should merge the definition with an existing one and
13686  // skip the body.
13687  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
13689  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
13690  NamedDecl *Hidden;
13691  if (PrevECD &&
13692  !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()),
13693  &Hidden)) {
13694  SkipBodyInfo Skip;
13695  Skip.Previous = Hidden;
13696  return Skip;
13697  }
13698 
13699  return SkipBodyInfo();
13700 }
13701 
13702 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13703  SourceLocation IdLoc, IdentifierInfo *Id,
13705  SourceLocation EqualLoc, Expr *Val) {
13706  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
13707  EnumConstantDecl *LastEnumConst =
13708  cast_or_null<EnumConstantDecl>(lastEnumConst);
13709 
13710  // The scope passed in may not be a decl scope. Zip up the scope tree until
13711  // we find one that is.
13712  S = getNonFieldDeclScope(S);
13713 
13714  // Verify that there isn't already something declared with this name in this
13715  // scope.
13716  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
13718  if (PrevDecl && PrevDecl->isTemplateParameter()) {
13719  // Maybe we will complain about the shadowed template parameter.
13720  DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
13721  // Just pretend that we didn't see the previous declaration.
13722  PrevDecl = nullptr;
13723  }
13724 
13725  if (PrevDecl) {
13726  // When in C++, we may get a TagDecl with the same name; in this case the
13727  // enum constant will 'hide' the tag.
13728  assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
13729  "Received TagDecl when not in C++!");
13730  if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
13731  if (isa<EnumConstantDecl>(PrevDecl))
13732  Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
13733  else
13734  Diag(IdLoc, diag::err_redefinition) << Id;
13735  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13736  return nullptr;
13737  }
13738  }
13739 
13740  // C++ [class.mem]p15:
13741  // If T is the name of a class, then each of the following shall have a name
13742  // different from T:
13743  // - every enumerator of every member of class T that is an unscoped
13744  // enumerated type
13745  if (!TheEnumDecl->isScoped())
13746  DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
13747  DeclarationNameInfo(Id, IdLoc));
13748 
13749  EnumConstantDecl *New =
13750  CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
13751 
13752  if (New) {
13753  // Process attributes.
13754  if (Attr) ProcessDeclAttributeList(S, New, Attr);
13755 
13756  // Register this decl in the current scope stack.
13757  New->setAccess(TheEnumDecl->getAccess());
13758  PushOnScopeChains(New, S);
13759  }
13760 
13761  ActOnDocumentableDecl(New);
13762 
13763  return New;
13764 }
13765 
13766 // Returns true when the enum initial expression does not trigger the
13767 // duplicate enum warning. A few common cases are exempted as follows:
13768 // Element2 = Element1
13769 // Element2 = Element1 + 1
13770 // Element2 = Element1 - 1
13771 // Where Element2 and Element1 are from the same enum.
13773  Expr *InitExpr = ECD->getInitExpr();
13774  if (!InitExpr)
13775  return true;
13776  InitExpr = InitExpr->IgnoreImpCasts();
13777 
13778  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
13779  if (!BO->isAdditiveOp())
13780  return true;
13781  IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
13782  if (!IL)
13783  return true;
13784  if (IL->getValue() != 1)
13785  return true;
13786 
13787  InitExpr = BO->getLHS();
13788  }
13789 
13790  // This checks if the elements are from the same enum.
13791  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
13792  if (!DRE)
13793  return true;
13794 
13795  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
13796  if (!EnumConstant)
13797  return true;
13798 
13799  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
13800  Enum)
13801  return true;
13802 
13803  return false;
13804 }
13805 
13806 struct DupKey {
13807  int64_t val;
13809  DupKey(int64_t val, bool isTombstoneOrEmptyKey)
13810  : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
13811 };
13812 
13813 static DupKey GetDupKey(const llvm::APSInt& Val) {
13814  return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
13815  false);
13816 }
13817 
13819  static DupKey getEmptyKey() { return DupKey(0, true); }
13820  static DupKey getTombstoneKey() { return DupKey(1, true); }
13821  static unsigned getHashValue(const DupKey Key) {
13822  return (unsigned)(Key.val * 37);
13823  }
13824  static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
13825  return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
13826  LHS.val == RHS.val;
13827  }
13828 };
13829 
13830 // Emits a warning when an element is implicitly set a value that
13831 // a previous element has already been set to.
13833  EnumDecl *Enum,
13834  QualType EnumType) {
13835  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
13836  return;
13837  // Avoid anonymous enums
13838  if (!Enum->getIdentifier())
13839  return;
13840 
13841  // Only check for small enums.
13842  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
13843  return;
13844 
13845  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
13846  typedef SmallVector<ECDVector *, 3> DuplicatesVector;
13847 
13848  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
13849  typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
13850  ValueToVectorMap;
13851 
13852  DuplicatesVector DupVector;
13853  ValueToVectorMap EnumMap;
13854 
13855  // Populate the EnumMap with all values represented by enum constants without
13856  // an initialier.
13857  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13858  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
13859 
13860  // Null EnumConstantDecl means a previous diagnostic has been emitted for
13861  // this constant. Skip this enum since it may be ill-formed.
13862  if (!ECD) {
13863  return;
13864  }
13865 
13866  if (ECD->getInitExpr())
13867  continue;
13868 
13869  DupKey Key = GetDupKey(ECD->getInitVal());
13870  DeclOrVector &Entry = EnumMap[Key];
13871 
13872  // First time encountering this value.
13873  if (Entry.isNull())
13874  Entry = ECD;
13875  }
13876 
13877  // Create vectors for any values that has duplicates.
13878  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13879  EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
13880  if (!ValidDuplicateEnum(ECD, Enum))
13881  continue;
13882 
13883  DupKey Key = GetDupKey(ECD->getInitVal());
13884 
13885  DeclOrVector& Entry = EnumMap[Key];
13886  if (Entry.isNull())
13887  continue;
13888 
13889  if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
13890  // Ensure constants are different.
13891  if (D == ECD)
13892  continue;
13893 
13894  // Create new vector and push values onto it.
13895  ECDVector *Vec = new ECDVector();
13896  Vec->push_back(D);
13897  Vec->push_back(ECD);
13898 
13899  // Update entry to point to the duplicates vector.
13900  Entry = Vec;
13901 
13902  // Store the vector somewhere we can consult later for quick emission of
13903  // diagnostics.
13904  DupVector.push_back(Vec);
13905  continue;
13906  }
13907 
13908  ECDVector *Vec = Entry.get<ECDVector*>();
13909  // Make sure constants are not added more than once.
13910  if (*Vec->begin() == ECD)
13911  continue;
13912 
13913  Vec->push_back(ECD);
13914  }
13915 
13916  // Emit diagnostics.
13917  for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
13918  DupVectorEnd = DupVector.end();
13919  DupVectorIter != DupVectorEnd; ++DupVectorIter) {
13920  ECDVector *Vec = *DupVectorIter;
13921  assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
13922 
13923  // Emit warning for one enum constant.
13924  ECDVector::iterator I = Vec->begin();
13925  S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
13926  << (*I)->getName() << (*I)->getInitVal().toString(10)
13927  << (*I)->getSourceRange();
13928  ++I;
13929 
13930  // Emit one note for each of the remaining enum constants with
13931  // the same value.
13932  for (ECDVector::iterator E = Vec->end(); I != E; ++I)
13933  S.Diag((*I)->getLocation(), diag::note_duplicate_element)
13934  << (*I)->getName() << (*I)->getInitVal().toString(10)
13935  << (*I)->getSourceRange();
13936  delete Vec;
13937  }
13938 }
13939 
13940 bool
13941 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
13942  bool AllowMask) const {
13943  FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>();
13944  assert(FEAttr && "looking for value in non-flag enum");
13945 
13946  llvm::APInt FlagMask = ~FEAttr->getFlagBits();
13947  unsigned Width = FlagMask.getBitWidth();
13948 
13949  // We will try a zero-extended value for the regular check first.
13950  llvm::APInt ExtVal = Val.zextOrSelf(Width);
13951 
13952  // A value is in a flag enum if either its bits are a subset of the enum's
13953  // flag bits (the first condition) or we are allowing masks and the same is
13954  // true of its complement (the second condition). When masks are allowed, we
13955  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
13956  //
13957  // While it's true that any value could be used as a mask, the assumption is
13958  // that a mask will have all of the insignificant bits set. Anything else is
13959  // likely a logic error.
13960  if (!(FlagMask & ExtVal))
13961  return true;
13962 
13963  if (AllowMask) {
13964  // Try a one-extended value instead. This can happen if the enum is wider
13965  // than the constant used, in C with extensions to allow for wider enums.
13966  // The mask will still have the correct behaviour, so we give the user the
13967  // benefit of the doubt.
13968  //
13969  // FIXME: This heuristic can cause weird results if the enum was extended
13970  // to a larger type and is signed, because then bit-masks of smaller types
13971  // that get extended will fall out of range (e.g. ~0x1u). We currently don't
13972  // detect that case and will get a false positive for it. In most cases,
13973  // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may
13974  // be fine just to accept this as a warning.
13975  ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth());
13976  if (!(FlagMask & ~ExtVal))
13977  return true;
13978  }
13979 
13980  return false;
13981 }
13982 
13984  SourceLocation RBraceLoc, Decl *EnumDeclX,
13985  ArrayRef<Decl *> Elements,
13986  Scope *S, AttributeList *Attr) {
13987  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
13989 
13990  if (Attr)
13991  ProcessDeclAttributeList(S, Enum, Attr);
13992 
13993  if (Enum->isDependentType()) {
13994  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
13995  EnumConstantDecl *ECD =
13996  cast_or_null<EnumConstantDecl>(Elements[i]);
13997  if (!ECD) continue;
13998 
13999  ECD->setType(EnumType);
14000  }
14001 
14003  return;
14004  }
14005 
14006  // TODO: If the result value doesn't fit in an int, it must be a long or long
14007  // long value. ISO C does not support this, but GCC does as an extension,
14008  // emit a warning.
14009  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14010  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14011  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14012 
14013  // Verify that all the values are okay, compute the size of the values, and
14014  // reverse the list.
14015  unsigned NumNegativeBits = 0;
14016  unsigned NumPositiveBits = 0;
14017 
14018  // Keep track of whether all elements have type int.
14019  bool AllElementsInt = true;
14020 
14021  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14022  EnumConstantDecl *ECD =
14023  cast_or_null<EnumConstantDecl>(Elements[i]);
14024  if (!ECD) continue; // Already issued a diagnostic.
14025 
14026  const llvm::APSInt &InitVal = ECD->getInitVal();
14027 
14028  // Keep track of the size of positive and negative values.
14029  if (InitVal.isUnsigned() || InitVal.isNonNegative())
14030  NumPositiveBits = std::max(NumPositiveBits,
14031  (unsigned)InitVal.getActiveBits());
14032  else
14033  NumNegativeBits = std::max(NumNegativeBits,
14034  (unsigned)InitVal.getMinSignedBits());
14035 
14036  // Keep track of whether every enum element has type int (very commmon).
14037  if (AllElementsInt)
14038  AllElementsInt = ECD->getType() == Context.IntTy;
14039  }
14040 
14041  // Figure out the type that should be used for this enum.
14042  QualType BestType;
14043  unsigned BestWidth;
14044 
14045  // C++0x N3000 [conv.prom]p3:
14046  // An rvalue of an unscoped enumeration type whose underlying
14047  // type is not fixed can be converted to an rvalue of the first
14048  // of the following types that can represent all the values of
14049  // the enumeration: int, unsigned int, long int, unsigned long
14050  // int, long long int, or unsigned long long int.
14051  // C99 6.4.4.3p2:
14052  // An identifier declared as an enumeration constant has type int.
14053  // The C99 rule is modified by a gcc extension
14054  QualType BestPromotionType;
14055 
14056  bool Packed = Enum->hasAttr<PackedAttr>();
14057  // -fshort-enums is the equivalent to specifying the packed attribute on all
14058  // enum definitions.
14059  if (LangOpts.ShortEnums)
14060  Packed = true;
14061 
14062  if (Enum->isFixed()) {
14063  BestType = Enum->getIntegerType();
14064  if (BestType->isPromotableIntegerType())
14065  BestPromotionType = Context.getPromotedIntegerType(BestType);
14066  else
14067  BestPromotionType = BestType;
14068 
14069  BestWidth = Context.getIntWidth(BestType);
14070  }
14071  else if (NumNegativeBits) {
14072  // If there is a negative value, figure out the smallest integer type (of
14073  // int/long/longlong) that fits.
14074  // If it's packed, check also if it fits a char or a short.
14075  if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14076  BestType = Context.SignedCharTy;
14077  BestWidth = CharWidth;
14078  } else if (Packed && NumNegativeBits <= ShortWidth &&
14079  NumPositiveBits < ShortWidth) {
14080  BestType = Context.ShortTy;
14081  BestWidth = ShortWidth;
14082  } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14083  BestType = Context.IntTy;
14084  BestWidth = IntWidth;
14085  } else {
14086  BestWidth = Context.getTargetInfo().getLongWidth();
14087 
14088  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14089  BestType = Context.LongTy;
14090  } else {
14091  BestWidth = Context.getTargetInfo().getLongLongWidth();
14092 
14093  if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14094  Diag(Enum->getLocation(), diag::ext_enum_too_large);
14095  BestType = Context.LongLongTy;
14096  }
14097  }
14098  BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14099  } else {
14100  // If there is no negative value, figure out the smallest type that fits
14101  // all of the enumerator values.
14102  // If it's packed, check also if it fits a char or a short.
14103  if (Packed && NumPositiveBits <= CharWidth) {
14104  BestType = Context.UnsignedCharTy;
14105  BestPromotionType = Context.IntTy;
14106  BestWidth = CharWidth;
14107  } else if (Packed && NumPositiveBits <= ShortWidth) {
14108  BestType = Context.UnsignedShortTy;
14109  BestPromotionType = Context.IntTy;
14110  BestWidth = ShortWidth;
14111  } else if (NumPositiveBits <= IntWidth) {
14112  BestType = Context.UnsignedIntTy;
14113  BestWidth = IntWidth;
14114  BestPromotionType
14115  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14117  } else if (NumPositiveBits <=
14118  (BestWidth = Context.getTargetInfo().getLongWidth())) {
14119  BestType = Context.UnsignedLongTy;
14120  BestPromotionType
14121  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14123  } else {
14124  BestWidth = Context.getTargetInfo().getLongLongWidth();
14125  assert(NumPositiveBits <= BestWidth &&
14126  "How could an initializer get larger than ULL?");
14127  BestType = Context.UnsignedLongLongTy;
14128  BestPromotionType
14129  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14131  }
14132  }
14133 
14134  FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>();
14135  if (FEAttr)
14136  FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0);
14137 
14138  // Loop over all of the enumerator constants, changing their types to match
14139  // the type of the enum if needed. If we have a flag type, we also prepare the
14140  // FlagBits cache.
14141  for (auto *D : Elements) {
14142  auto *ECD = cast_or_null<EnumConstantDecl>(D);
14143  if (!ECD) continue; // Already issued a diagnostic.
14144 
14145  // Standard C says the enumerators have int type, but we allow, as an
14146  // extension, the enumerators to be larger than int size. If each
14147  // enumerator value fits in an int, type it as an int, otherwise type it the
14148  // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14149  // that X has type 'int', not 'unsigned'.
14150 
14151  // Determine whether the value fits into an int.
14152  llvm::APSInt InitVal = ECD->getInitVal();
14153 
14154  // If it fits into an integer type, force it. Otherwise force it to match
14155  // the enum decl type.
14156  QualType NewTy;
14157  unsigned NewWidth;
14158  bool NewSign;
14159  if (!getLangOpts().CPlusPlus &&
14160  !Enum->isFixed() &&
14162  NewTy = Context.IntTy;
14163  NewWidth = IntWidth;
14164  NewSign = true;
14165  } else if (ECD->getType() == BestType) {
14166  // Already the right type!
14167  if (getLangOpts().CPlusPlus)
14168  // C++ [dcl.enum]p4: Following the closing brace of an
14169  // enum-specifier, each enumerator has the type of its
14170  // enumeration.
14171  ECD->setType(EnumType);
14172  goto flagbits;
14173  } else {
14174  NewTy = BestType;
14175  NewWidth = BestWidth;
14176  NewSign = BestType->isSignedIntegerOrEnumerationType();
14177  }
14178 
14179  // Adjust the APSInt value.
14180  InitVal = InitVal.extOrTrunc(NewWidth);
14181  InitVal.setIsSigned(NewSign);
14182  ECD->setInitVal(InitVal);
14183 
14184  // Adjust the Expr initializer and type.
14185  if (ECD->getInitExpr() &&
14186  !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14187  ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14189  ECD->getInitExpr(),
14190  /*base paths*/ nullptr,
14191  VK_RValue));
14192  if (getLangOpts().CPlusPlus)
14193  // C++ [dcl.enum]p4: Following the closing brace of an
14194  // enum-specifier, each enumerator has the type of its
14195  // enumeration.
14196  ECD->setType(EnumType);
14197  else
14198  ECD->setType(NewTy);
14199 
14200 flagbits:
14201  // Check to see if we have a constant with exactly one bit set. Note that x
14202  // & (x - 1) will be nonzero if and only if x has more than one bit set.
14203  if (FEAttr) {
14204  llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth);
14205  if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) {
14206  FEAttr->getFlagBits() |= ExtVal;
14207  }
14208  }
14209  }
14210 
14211  if (FEAttr) {
14212  for (Decl *D : Elements) {
14213  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14214  if (!ECD) continue; // Already issued a diagnostic.
14215 
14216  llvm::APSInt InitVal = ECD->getInitVal();
14217  if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true))
14218  Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14219  << ECD << Enum;
14220  }
14221  }
14222 
14223 
14224 
14225  Enum->completeDefinition(BestType, BestPromotionType,
14226  NumPositiveBits, NumNegativeBits);
14227 
14228  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14229 
14230  // Now that the enum type is defined, ensure it's not been underaligned.
14231  if (Enum->hasAttrs())
14233 }
14234 
14236  SourceLocation StartLoc,
14237  SourceLocation EndLoc) {
14238  StringLiteral *AsmString = cast<StringLiteral>(expr);
14239 
14241  AsmString, StartLoc,
14242  EndLoc);
14243  CurContext->addDecl(New);
14244  return New;
14245 }
14246 
14248  SourceLocation ImportLoc,
14249  DeclContext *DC) {
14250  if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14251  switch (LSD->getLanguage()) {
14253  if (!M->IsExternC) {
14254  S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
14255  << M->getFullModuleName();
14256  S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
14257  return;
14258  }
14259  break;
14261  break;
14262  }
14263  DC = LSD->getParent();
14264  }
14265 
14266  while (isa<LinkageSpecDecl>(DC))
14267  DC = DC->getParent();
14268  if (!isa<TranslationUnitDecl>(DC)) {
14269  S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
14270  << M->getFullModuleName() << DC;
14271  S.Diag(cast<Decl>(DC)->getLocStart(),
14272  diag::note_module_import_not_at_top_level)
14273  << DC;
14274  }
14275 }
14276 
14278  SourceLocation ImportLoc,
14279  ModuleIdPath Path) {
14280  Module *Mod =
14281  getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14282  /*IsIncludeDirective=*/false);
14283  if (!Mod)
14284  return true;
14285 
14286  VisibleModules.setVisible(Mod, ImportLoc);
14287 
14288  checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14289 
14290  // FIXME: we should support importing a submodule within a different submodule
14291  // of the same top-level module. Until we do, make it an error rather than
14292  // silently ignoring the import.
14294  Diag(ImportLoc, diag::err_module_self_import)
14297  Diag(ImportLoc, diag::err_module_import_in_implementation)
14299 
14300  SmallVector<SourceLocation, 2> IdentifierLocs;
14301  Module *ModCheck = Mod;
14302  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14303  // If we've run out of module parents, just drop the remaining identifiers.
14304  // We need the length to be consistent.
14305  if (!ModCheck)
14306  break;
14307  ModCheck = ModCheck->Parent;
14308 
14309  IdentifierLocs.push_back(Path[I].second);
14310  }
14311 
14314  AtLoc.isValid()? AtLoc : ImportLoc,
14315  Mod, IdentifierLocs);
14317  return Import;
14318 }
14319 
14321  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14322 
14323  // Determine whether we're in the #include buffer for a module. The #includes
14324  // in that buffer do not qualify as module imports; they're just an
14325  // implementation detail of us building the module.
14326  //
14327  // FIXME: Should we even get ActOnModuleInclude calls for those?
14328  bool IsInModuleIncludes =
14329  TUKind == TU_Module &&
14330  getSourceManager().isWrittenInMainFile(DirectiveLoc);
14331 
14332  // If this module import was due to an inclusion directive, create an
14333  // implicit import declaration to capture it in the AST.
14334  if (!IsInModuleIncludes) {
14337  DirectiveLoc, Mod,
14338  DirectiveLoc);
14339  TU->addDecl(ImportD);
14341  }
14342 
14344  VisibleModules.setVisible(Mod, DirectiveLoc);
14345 }
14346 
14348  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14349 
14350  if (getLangOpts().ModulesLocalVisibility)
14351  VisibleModulesStack.push_back(std::move(VisibleModules));
14352  VisibleModules.setVisible(Mod, DirectiveLoc);
14353 }
14354 
14355 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14356  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14357 
14358  if (getLangOpts().ModulesLocalVisibility) {
14359  VisibleModules = std::move(VisibleModulesStack.back());
14360  VisibleModulesStack.pop_back();
14361  VisibleModules.setVisible(Mod, DirectiveLoc);
14362  }
14363 }
14364 
14366  Module *Mod) {
14367  // Bail if we're not allowed to implicitly import a module here.
14368  if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14369  return;
14370 
14371  // Create the implicit import declaration.
14374  Loc, Mod, Loc);
14375  TU->addDecl(ImportD);
14377 
14378  // Make the module visible.
14380  VisibleModules.setVisible(Mod, Loc);
14381 }
14382 
14384  IdentifierInfo* AliasName,
14385  SourceLocation PragmaLoc,
14386  SourceLocation NameLoc,
14387  SourceLocation AliasNameLoc) {
14388  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14390  AsmLabelAttr *Attr =
14391  AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14392 
14393  // If a declaration that:
14394  // 1) declares a function or a variable
14395  // 2) has external linkage
14396  // already exists, add a label attribute to it.
14397  if (PrevDecl &&
14398  (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)) &&
14399  PrevDecl->hasExternalFormalLinkage())
14400  PrevDecl->addAttr(Attr);
14401  // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14402  else
14403  (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14404 }
14405 
14407  SourceLocation PragmaLoc,
14408  SourceLocation NameLoc) {
14409  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14410 
14411  if (PrevDecl) {
14412  PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14413  } else {
14414  (void)WeakUndeclaredIdentifiers.insert(
14415  std::pair<IdentifierInfo*,WeakInfo>
14416  (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14417  }
14418 }
14419 
14421  IdentifierInfo* AliasName,
14422  SourceLocation PragmaLoc,
14423  SourceLocation NameLoc,
14424  SourceLocation AliasNameLoc) {
14425  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14427  WeakInfo W = WeakInfo(Name, NameLoc);
14428 
14429  if (PrevDecl) {
14430  if (!PrevDecl->hasAttr<AliasAttr>())
14431  if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14432  DeclApplyPragmaWeak(TUScope, ND, W);
14433  } else {
14434  (void)WeakUndeclaredIdentifiers.insert(
14435  std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14436  }
14437 }
14438 
14440  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14441 }
14442 
14444  const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14445  if (!D)
14446  return AR_Available;
14447 
14448  // If we are within an Objective-C method, we should consult
14449  // both the availability of the method as well as the
14450  // enclosing class. If the class is (say) deprecated,
14451  // the entire method is considered deprecated from the
14452  // purpose of checking if the current context is deprecated.
14453  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14455  if (R != AR_Available)
14456  return R;
14457  D = MD->getClassInterface();
14458  }
14459  // If we are within an Objective-c @implementation, it
14460  // gets the same availability context as the @interface.
14461  else if (const ObjCImplementationDecl *ID =
14462  dyn_cast<ObjCImplementationDecl>(D)) {
14463  D = ID->getClassInterface();
14464  }
14465  // Recover from user error.
14466  return D ? D->getAvailability() : AR_Available;
14467 }
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossibleZeroParamPrototype)
Definition: SemaDecl.cpp:10387
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:265
unsigned getFlags() const
Definition: Scope.h:207
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:54
unsigned getAddressSpace() const
getAddressSpace - Return the address space of this type.
Definition: Type.h:5131
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:452
param_const_iterator param_begin() const
Definition: DeclObjC.h:359
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2411
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:1929
Defines the clang::ASTContext interface.
const AttributedType * getCallingConvAttributedType(QualType T) const
Definition: SemaDecl.cpp:2559
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1366
SourceLocation getEnd() const
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
CastKind getCastKind() const
Definition: Expr.h:2709
IdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:966
CanQualType LongLongTy
Definition: ASTContext.h:825
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:504
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:2442
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:4849
void setDeclsInPrototypeScope(ArrayRef< NamedDecl * > NewDecls)
Definition: Decl.cpp:2668
bool isVariadic() const
Definition: Type.h:3228
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:47
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchers.h:1110
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:629
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
Definition: DeclSpec.h:2039
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 isTransparentContext() const
Definition: DeclBase.cpp:883
iterator begin() const
Definition: DeclBase.h:1070
bool isTemplateParameter() const
Definition: DeclBase.h:1771
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringRef getName() const
Definition: Decl.h:168
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:12828
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1405
no exception specification
bool isTombstoneOrEmptyKey
Definition: SemaDecl.cpp:13808
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:5507
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:3295
EvaluatedExprVisitor - This class visits 'Expr *'s.
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:535
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2101
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:2202
ASTConsumer & Consumer
Definition: Sema.h:296
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility)
Definition: SemaDecl.cpp:12904
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1377
Simple class containing the result of Sema::CorrectTypo.
capture_const_range captures() const
Definition: DeclCXX.h:1070
const IdentifierInfo * getLiteralIdentifier() const
Definition: Decl.cpp:2925
void InstantiatedLocal(const Decl *D, Decl *Inst)
bool isEvaluatable(const ASTContext &Ctx) const
base_class_range bases()
Definition: DeclCXX.h:713
bool isInvalid() const
Definition: Ownership.h:159
const AttributeList * getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1429
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:534
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:14420
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, SmallVectorImpl< NamedDecl * > &Chaining, bool MSAnonStruct)
Definition: SemaDecl.cpp:3922
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2216
bool isReplaceableGlobalAllocationFunction() const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2492
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:560
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:2929
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2330
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1072
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1263
DestructionKind isDestructedType() const
Definition: Type.h:999
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:5127
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:312
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:252
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1144
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:943
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:602
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
IdentifierInfo * getIdentifier() const
Definition: Decl.h:163
DeclarationName getCXXConstructorName(CanQualType Ty)
Decl * getRepAsDecl() const
Definition: DeclSpec.h:485
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:428
const LangOptions & getLangOpts() const
Definition: Sema.h:1019
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:209
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
const Scope * getFnParent() const
Definition: Scope.h:220
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:13832
ArrayRef< RawComment * > getComments() const
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:3506
DeclClass * getAsSingle() const
Definition: Lookup.h:447
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:916
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:464
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1128
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3177
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:616
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:902
decl_range decls() const
Definition: DeclBase.h:1413
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration. If PrevDecl is NULL, set this as the first and only declaration...
Definition: Decl.h:3792
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program...
Definition: Decl.cpp:2434
const Expr * getInitExpr() const
Definition: Decl.h:2467
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function...
Definition: Decl.cpp:3199
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "...
Definition: Basic/Module.h:177
unsigned getIntWidth(QualType T) const
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:3410
const Scope * getParent() const
Definition: Scope.h:215
Defines the SourceManager interface.
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1348
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:10054
void ActOnDocumentableDecl(Decl *D)
Definition: SemaDecl.cpp:10050
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1429
static ClassScopeFunctionSpecializationDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD, bool HasExplicitTemplateArgs, TemplateArgumentListInfo TemplateArgs)
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1386
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:163
A conversion function name, e.g., operator int.
Definition: DeclSpec.h:882
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsExplicitSpecialization)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:8052
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
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:10671
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:588
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
bool isRecordType() const
Definition: Type.h:5289
static const TST TST_typeofExpr
Definition: DeclSpec.h:299
QualType getUnderlyingType() const
Definition: Decl.h:2616
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:184
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1088
void setRangeEnd(SourceLocation E)
Definition: Decl.h:1716
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:130
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:1987
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function...
Definition: SemaDecl.cpp:5067
static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:1708
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:123
bool isLiteralType(const ASTContext &Ctx) const
Definition: Type.cpp:2110
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1572
Defines the C++ template declaration subclasses.
void setModulePrivate(bool MP=true)
Specify whether this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:559
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...
bool isVoidPointerType() const
Definition: Type.cpp:384
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1269
Scope * TUScope
Definition: Sema.h:680
Represents a C++11 auto or C++1y decltype(auto) type.
Definition: Type.h:3874
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
Definition: SemaDecl.cpp:2551
void setPure(bool P=true)
Definition: Decl.cpp:2421
bool hasFlexibleArrayMember() const
Definition: Decl.h:3279
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:2576
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
Not a friend object.
Definition: DeclBase.h:949
SCS getStorageClassSpec() const
Definition: DeclSpec.h:442
void AddDecl(Decl *D)
Definition: Scope.h:272
bool hasDefinition() const
Definition: DeclCXX.h:680
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2186
PtrTy get() const
Definition: Ownership.h:163
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:6766
IdentifierInfo * getAsIdentifierInfo() const
bool isInStdNamespace() const
Definition: DeclBase.cpp:265
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:851
CanQualType LongTy
Definition: ASTContext.h:825
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2009
iterator begin() const
Definition: Lookup.h:275
unsigned getLength() const
Efficiently return the length of this identifier info.
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:2567
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:4025
MapType::iterator iterator
QualType getRecordType(const RecordDecl *Decl) const
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1086
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:1786
Declaration of a variable template.
const Expr * getInit() const
Definition: Decl.h:1068
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:400
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs. a reference).
Definition: Sema.h:2625
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1075
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:446
virtual void completeDefinition()
Definition: Decl.cpp:3638
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1390
bool isDecltypeAuto() const
Definition: Type.h:3890
decl_iterator begin()
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:552
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:83
bool isBooleanType() const
Definition: Type.h:5489
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1171
A container of type source information.
Definition: Decl.h:60
Wrapper for void* pointer.
Definition: Ownership.h:45
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:459
unsigned getFunctionPrototypeDepth() const
Definition: Scope.h:255
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:3524
bool isBlockPointerType() const
Definition: Type.h:5238
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T)
Definition: SemaDecl.cpp:3625
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:1924
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclBase.h:368
void PopDeclContext()
Definition: SemaDecl.cpp:1077
static DupKey getTombstoneKey()
Definition: SemaDecl.cpp:13820
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1159
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2147
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, bool Override)
Definition: SemaDecl.cpp:2208
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:6496
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:1526
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
***static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Definition: SemaDecl.cpp:11432
const TemplateArgumentLoc * getArgumentArray() const
Definition: TemplateBase.h:543
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group, bool TypeMayContainAuto=true)
Definition: SemaDecl.cpp:10002
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:80
This file provides some common utility functions for processing Lambda related AST Constructs...
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
Definition: SemaDecl.cpp:4602
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:51
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:539
void ActOnObjCReenterContainerContext(DeclContext *DC)
Definition: SemaDecl.cpp:12433
DeclContext::lookup_result Decls
The set of declarations found inside this base class subobject.
RAII object that enters a new expression evaluation context.
Definition: Sema.h:9016
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2056
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
Definition: SemaDecl.cpp:1726
bool hasNext() const
Definition: Lookup.h:573
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:1935
bool isFileVarDecl() const
isFileVarDecl - Returns true for file scoped variable declaration.
Definition: Decl.h:1040
static const TST TST_underlyingType
Definition: DeclSpec.h:302
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1572
DiagnosticsEngine & Diags
Definition: Sema.h:297
CXXMethodDecl * Method
Definition: SemaDecl.cpp:6522
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
const Expr * getCallee() const
Definition: Expr.h:2188
TLSKind getTLSKind() const
Definition: Decl.cpp:1803
The "union" keyword.
Definition: Type.h:4134
ExtProtoInfo - Extra information about a function prototype.
Definition: Type.h:3042
AccessSpecifier getAccess() const
Definition: DeclBase.h:416
bool isCanonical() const
Definition: Type.h:5060
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:39
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:1532
field_iterator field_begin() const
Definition: Decl.cpp:3629
bool isCLike() const
True if this class is C-like, without C++-specific features, e.g. it contains only public fields...
Definition: DeclCXX.cpp:975
The "__interface" keyword.
Definition: Type.h:4132
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1701
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1096
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:318
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:12427
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:922
static const TST TST_interface
Definition: DeclSpec.h:295
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
Definition: SemaDecl.cpp:6587
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:46
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:4203
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:284
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value...
Definition: Expr.h:3305
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:35
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:7184
bool isImageType() const
Definition: Type.h:5379
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:10097
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:10706
bool isSingleTagDecl() const
Asks if the result is a single tag decl.
Definition: Lookup.h:470
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:4462
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1334
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:1547
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isUnionType() const
Definition: Type.cpp:390
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:1159
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:194
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1727
bool isVoidType() const
Definition: Type.h:5426
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:3584
static const TemplateDecl * isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs)
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:2839
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Definition: SemaDecl.cpp:5029
void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto)
Definition: SemaDecl.cpp:9378
Information about a template-id annotation token.
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
Definition: SemaDecl.cpp:12545
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:275
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:37
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, TemplateParameterList **TPLists)
Definition: Decl.cpp:1657
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
Expr * IgnoreImpCasts() LLVM_READONLY
Definition: Expr.h:2803
unsigned getNumParams() const
Definition: Type.h:3133
std::string getFullModuleName() const
Retrieve the full name of this module, including the path from its top-level module.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body (definition). The function body might be in any of the (re-)d...
Definition: Decl.cpp:2368
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2120
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:2537
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:937
DeclarationName getName() const
getName - Returns the embedded declaration name.
bool isConst() const
Definition: DeclCXX.h:1758
iterator end() const
Definition: Lookup.h:276
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3124
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:6793
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:2916
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:57
bool isScalarType() const
Definition: Type.h:5461
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1428
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Definition: SemaDecl.cpp:5452
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:4363
method_iterator end_overridden_methods() const
Definition: DeclCXX.cpp:1582
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:3029
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:5049
OpaquePtr< QualType > ParsedType
Definition: Ownership.h:233
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
Definition: SemaDecl.cpp:3204
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:1509
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
bool hasAttr() const
Definition: DeclBase.h:487
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Definition: Decl.cpp:3950
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:924
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:3591
IdentifierInfo * getCorrectionAsIdentifierInfo() const
AttributeList * getList() const
void setManglingNumber(const NamedDecl *ND, unsigned Number)
Expr * getSizeExpr() const
Definition: Type.h:2568
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:2469
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization)
Definition: SemaDecl.cpp:5356
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1742
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1103
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
A C++ nested-name-specifier augmented with source location information.
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &attrs, SourceLocation EndLoc)
Definition: DeclSpec.h:1930
The results of name lookup within a DeclContext. This is either a single result (with no stable stora...
Definition: DeclBase.h:1034
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3138
bool decl_empty() const
Definition: Scope.h:270
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
Definition: SemaDecl.cpp:12333
Missing a type from <ucontext.h>
Definition: ASTContext.h:1648
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:11255
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:1213
const CXXScopeSpec & getCXXScopeSpec() const
Definition: DeclSpec.h:1691
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
Definition: DeclObjC.cpp:56
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:1604
bool isReferenceType() const
Definition: Type.h:5241
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:674
static const TST TST_class
Definition: DeclSpec.h:296
QualType getReturnType() const
Definition: Decl.h:1997
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:11333
bool isStructureOrClassType() const
Definition: Type.cpp:377
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:882
bool isCompleteDefinition() const
Definition: Decl.h:2838
int hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const llvm::Triple &T, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:6
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:54
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:899
void removeConst()
Definition: Type.h:230
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:326
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:450
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. A declaration will replace another declaration if, for example, it is a redeclaration of the same variable or function, but not if it is a declaration of a different kind (function vs. class) or an overloaded function.
Definition: Decl.cpp:1495
bool isPure() const
Definition: Decl.h:1789
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:1733
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:258
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3419
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:920
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:1785
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:675
bool isTranslationUnit() const
Definition: DeclBase.h:1243
bool isNoreturnSpecified() const
Definition: DeclSpec.h:562
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1776
TagKind getTagKind() const
Definition: Decl.h:2897
bool isPreviousDeclInSameBlockScope() const
Definition: Decl.h:1252
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1871
static const TST TST_error
Definition: DeclSpec.h:306
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
DeclarationName getCXXDestructorName(CanQualType Ty)
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Definition: SemaDecl.cpp:13678
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1107
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:449
SmallVector< Attr *, 2 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:42
This declaration is definitely a definition.
Definition: Decl.h:995
static const TST TST_enum
Definition: DeclSpec.h:292
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
Definition: SemaDecl.cpp:8318
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:503
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:11196
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1708
unsigned size() const
Definition: DeclTemplate.h:87
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, AttributeList *Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:13702
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
Definition: SemaDecl.cpp:539
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:11001
static unsigned getNumAddressingBits(ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:76
Expr * getSubExpr()
Definition: Expr.h:2713
void ClearStorageClassSpecs()
Definition: DeclSpec.h:456
bool isForRedeclaration() const
True if this lookup is just looking for an existing declaration.
Definition: Lookup.h:219
unsigned getRegParm() const
Definition: Type.h:2891
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.
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, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'. In the former case, Name will be non-null...
Definition: SemaDecl.cpp:11497
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:1114
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:1896
std::pair< NullabilityKind, bool > DiagNullabilityKind
Definition: Diagnostic.h:1113
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:39
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Definition: SemaDecl.cpp:5555
Describes a module or submodule.
Definition: Basic/Module.h:49
IdentifierTable & Idents
Definition: ASTContext.h:439
bool isThisDeclarationADefinition() const
Definition: Decl.h:2832
StorageClass getStorageClass() const
Returns the storage class as written in the source. For the computed linkage of symbol, see getLinkage.
Definition: Decl.h:871
RawCommentList & getRawCommentList()
Definition: ASTContext.h:621
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:95
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:913
Expr * getLHS() const
Definition: Expr.h:2964
bool isLinkageValid() const
True if the computed linkage is valid. Used for consistency checking. Should always return true...
Definition: Decl.cpp:1006
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:371
T * getAttr() const
Definition: DeclBase.h:484
bool isExplicitlyDefaulted() const
Definition: Decl.h:1810
unsigned getRegParmType() const
Definition: Type.h:2955
QualType mergeObjCGCQualifiers(QualType, QualType)
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:170
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU. Returns null if there is a pro...
Definition: Decl.cpp:1970
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition: DeclSpec.h:932
Describes an C or C++ initializer list.
Definition: Expr.h:3759
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:869
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
QualType getParenType(QualType NamedType) const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1474
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:358
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:488
Represents the results of name lookup.
Definition: Lookup.h:30
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:518
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:2368
MinSizeAttr * mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
const LangOptions & getLangOpts() const
Definition: ASTContext.h:533
static void filterNonConflictingPreviousTypedefDecls(Sema &S, TypedefNameDecl *Decl, LookupResult &Previous)
Definition: SemaDecl.cpp:1834
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:1947
bool isImplicit() const
Definition: DeclBase.h:503
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=ParsedType(), bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:241
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:960
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1013
Scope * getNonFieldDeclScope(Scope *S)
Definition: SemaDecl.cpp:1682
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Definition: SemaDecl.cpp:2101
bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:998
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getReturnType() const
Definition: Type.h:2952
Wrapper for source info for functions.
Definition: TypeLoc.h:1243
static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, Sema &S)
Definition: SemaDecl.cpp:10480
void ActOnInitializerError(Decl *Dcl)
Definition: SemaDecl.cpp:9341
SCS
storage-class-specifier
Definition: DeclSpec.h:237
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:3904
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
const CXXRecordDecl * getParent() const
Definition: DeclCXX.h:1817
AmbiguityKind getAmbiguityKind() const
Definition: Lookup.h:266
bool isDefaulted() const
Definition: Decl.h:1805
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:1881
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:5591
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:32
field_range fields() const
Definition: Decl.h:3349
Decl * ActOnObjCContainerStartDefinition(Decl *IDecl)
Definition: SemaDecl.cpp:12347
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:193
VarTemplateDecl * getInstantiatedFromMemberTemplate()
static bool isEqual(const DupKey &LHS, const DupKey &RHS)
Definition: SemaDecl.cpp:13824
bool isObjCLifetimeType() const
Definition: Type.cpp:3561
const ArrayType * getAsArrayType(QualType T) const
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:222
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:4628
static bool isRecordType(QualType T)
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1718
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2918
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2200
void setHasObjectMember(bool val)
Definition: Decl.h:3300
An implicit 'self' parameter.
Definition: DeclSpec.h:894
bool isValueDependent() const
Definition: Expr.h:146
static OpenCLParamType getOpenCLKernelParameterType(QualType PT)
Definition: SemaDecl.cpp:7012
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
QualType withoutLocalFastQualifiers() const
Definition: Type.h:792
void setHasImplicitReturnZero(bool IRZ)
Definition: Decl.h:1817
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Module * Parent
The parent of this module. This will be NULL for the top-level module.
Definition: Basic/Module.h:59
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:11470
child_range children()
Definition: Expr.h:3917
bool isOverloadedOperator() const
Definition: Decl.h:2050
LabelStmt * getStmt() const
Definition: Decl.h:378
FunctionTemplateDecl * getInstantiatedFromMemberTemplate()
Definition: DeclTemplate.h:929
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a #include or similar preprocessing directiv...
Definition: SemaDecl.cpp:14320
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:6024
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:14235
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:651
void setTrivial(bool IT)
Definition: Decl.h:1801
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:3005
static DupKey getEmptyKey()
Definition: SemaDecl.cpp:13819
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:1550
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:68
void ActOnFinishInlineMethodDef(CXXMethodDecl *D)
Definition: SemaDecl.cpp:10383
bool hasUnrecoverableErrorOccurred() const
Definition: Scope.h:315
bool isStructureType() const
Definition: Type.cpp:362
void setRedeclarationKind(Sema::RedeclarationKind RK)
Change this lookup's redeclaration kind.
Definition: Lookup.h:512
bool isIncompleteType(NamedDecl **Def=nullptr) const
Def If non-NULL, and the type refers to some kind of declaration that can be completed (such as a C s...
Definition: Type.cpp:1869
DeclContext * getLexicalDeclContext()
Definition: DeclBase.h:697
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:1874
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:658
void CheckCompleteVariableDeclaration(VarDecl *var)
Definition: SemaDecl.cpp:9665
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:6347
SourceLocation getLocation() const
Definition: Attr.h:93
bool isStaticLocal() const
Definition: Decl.h:904
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1785
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:726
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:446
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
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:158
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:8465
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:10726
Represents an ObjC class declaration.
Definition: DeclObjC.h:851
Represents a linkage specification.
Definition: DeclCXX.h:2467
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
const SourceRange & getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:496
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:497
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access. Does not test the acceptance criteria...
Definition: Lookup.h:366
static bool isDeclTUScopedExternallyVisible(const Decl *D)
Returns true if given declaration is TU-scoped and externally visible.
Definition: SemaDecl.cpp:5579
bool empty() const
Definition: Type.h:356
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
Definition: Sema.h:662
static bool isUsingDecl(NamedDecl *D)
Definition: SemaDecl.cpp:1308
CanQualType UnsignedCharTy
Definition: ASTContext.h:826
QualType getType() const
Definition: Decl.h:538
bool isInvalid() const
const LangOptions & LangOpts
Definition: Sema.h:293
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:1683
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced...
Definition: DeclSpec.h:928
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:733
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool AllowClassTemplates=false)
Definition: SemaDecl.cpp:555
void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, bool IncludeCXX11Attributes=true)
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:872
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:2631
TypeSpecTypeLoc pushTypeSpec(QualType T)
bool isDefined(const FunctionDecl *&Definition) const
Definition: Decl.cpp:2393
param_iterator param_begin()
Definition: Decl.h:1947
unsigned getMSLastManglingNumber() const
Definition: Scope.h:294
void setHasInheritedPrototype(bool P=true)
Definition: Decl.h:1832
TyLocType push(QualType T)
field_iterator field_end() const
Definition: Decl.h:3352
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:1823
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl)
Class that aids in the construction of nested-name-specifiers along with source-location information ...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:63
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:373
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:96
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:6740
static const Decl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2267
AnnotatingParser & P
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:1793
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:965
bool isStatic() const
Definition: DeclCXX.cpp:1402
bool isUnion() const
Definition: Decl.h:2906
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)
Definition: Decl.cpp:3530
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition: Decl.cpp:4058
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:10373
DeclSpec & getMutableDeclSpec()
Definition: DeclSpec.h:1683
void setLazyBody(uint64_t Offset)
Definition: Decl.h:1778
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
AvailabilityResult getAvailability(std::string *Message=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:442
const ArrayType * castAsArrayTypeUnsafe() const
Definition: Type.h:5595
ExtInfo getExtInfo() const
Definition: Type.h:2961
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:258
void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name)
Make the given externally-produced declaration visible at the top level scope.
Definition: SemaDecl.cpp:1262
llvm::APInt getValue() const
Definition: Expr.h:1262
bool isFunctionDeclarator(unsigned &idx) const
Definition: DeclSpec.h:2009
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:640
TST getTypeSpecType() const
Definition: DeclSpec.h:474
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:143
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:194
QualType getParamType(unsigned i) const
Definition: Type.h:3134
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, bool TypeMayContainAuto)
Definition: SemaDecl.cpp:8838
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:129
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:111
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2560
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:690
std::string CurrentModule
The name of the current module.
Definition: LangOptions.h:96
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
Definition: SemaDecl.cpp:2426
Qualifiers::ObjCLifetime getObjCLifetime() const
getObjCLifetime - Returns lifetime attribute of this type.
Definition: Type.h:976
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
Definition: SemaDecl.cpp:506
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:5261
Represents a ValueDecl that came out of a declarator. Contains type source information through TypeSo...
Definition: Decl.h:586
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:596
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1737
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:442
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1351
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld)
Definition: SemaDecl.cpp:2633
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1620
ASTContext * Context
std::vector< bool > & Stack
SourceLocation getInnerLocStart() const
Definition: Decl.h:2818
ArrayRef< NamedDecl * > getDeclsInPrototypeScope() const
Definition: Decl.h:1986
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ID
Defines the set of possible language-specific address spaces.
Definition: AddressSpaces.h:27
StorageClass getStorageClass() const
Returns the storage class as written in the source. For the computed linkage of symbol, see getLinkage.
Definition: Decl.h:2020
const CXXMethodDecl *const * method_iterator
Definition: DeclCXX.h:1809
QualType getPointeeType() const
Definition: Type.cpp:414
bool isFunctionPointerType() const
Definition: Type.h:5250
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:246
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
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:6686
static bool isDeclRep(TST T)
Definition: DeclSpec.h:409
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:533
void setVisible(Module *M, SourceLocation Loc, VisibleCallback Vis=[](Module *){}, ConflictCallback Cb=[](ArrayRef< Module * >, Module *, StringRef){})
Make a specific module visible.
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:213
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, bool isImplicitlyDeclared)
Definition: DeclCXX.cpp:1903
bool isSignedIntegerOrEnumerationType() const
Definition: Type.cpp:1699
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
unsigned getNumExprs() const
Definition: Expr.h:4386
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1861
DeclContext * getLexicalParent()
Definition: DeclBase.h:1190
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:626
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:2549
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:39
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:101
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:133
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2224
const Type * getTypeForDecl() const
Definition: Decl.h:2557
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1358
unsigned param_size() const
Definition: Decl.h:1941
unsigned getTypeQualifiers() const
Definition: DeclCXX.h:1833
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5495
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:204
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:2578
StringRef getName() const
Return the actual identifier string.
const Expr * getExpr(unsigned Init) const
Definition: Expr.h:4388
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:651
Represents a character-granular source range.
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4156
DLLImportAttr * mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
static unsigned getMaxSizeBits(ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:111
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:537
bool isDeclScope(Decl *D)
Definition: Scope.h:306
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
Definition: Sema.h:475
static Kind getNullabilityAttrKind(NullabilityKind kind)
Definition: Type.h:3652
StateNode * Previous
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Definition: SemaDecl.cpp:6316
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
bool isFunctionDefinition() const
Definition: DeclSpec.h:2182
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:1156
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:908
SourceLocation getNameLoc() const
Definition: Lookup.h:545
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:910
bool isVirtual() const
Definition: DeclCXX.h:1761
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:13772
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2358
void setInit(Expr *I)
Definition: Decl.cpp:2047
void setInvalidDecl(bool Invalid=true)
Definition: DeclBase.cpp:96
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:812
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup. Asserts that one was found.
Definition: Lookup.h:457
bool isObjCGCWeak() const
isObjCGCWeak true when Type is objc's weak.
Definition: Type.h:966
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:540
bool isVariableArrayType() const
Definition: Type.h:5280
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
Definition: SemaDecl.cpp:4310
Defines the clang::Preprocessor interface.
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
bool isInherited() const
Definition: Attr.h:97
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:829
Kind getKind() const
Definition: DeclBase.h:375
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:1968
bool getNoReturn() const
Definition: Type.h:2888
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3142
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O)
Definition: Type.h:3051
static void CheckPoppedLabel(LabelDecl *L, Sema &S)
Definition: SemaDecl.cpp:1575
llvm::MapVector< IdentifierInfo *, WeakInfo > WeakUndeclaredIdentifiers
Definition: Sema.h:656
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:536
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage. This will either be a local variabl...
Definition: DeclBase.h:908
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:155
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls. Unprototyped calls also use the ...
Definition: Specifiers.h:222
DeclContext * getDeclContext()
Definition: DeclBase.h:381
void CheckAlignasUnderalignment(Decl *D)
This declaration is a tentative definition.
Definition: Decl.h:994
bool isFloatingType() const
Definition: Type.cpp:1760
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1335
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:13484
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Definition: Type.cpp:2346
CanQualType ShortTy
Definition: ASTContext.h:825
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:736
Represents a C++ template name within the type system.
Definition: TemplateName.h:175
bool isWrittenInMainFile(SourceLocation Loc) const
Returns true if the spelling location for the given location is in the main file buffer.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
Definition: SemaDecl.cpp:5168
bool isMSAsmLabel() const
Definition: Decl.h:388
bool isFunctionNoProtoType() const
Definition: Type.h:1616
bool isObjCIdType() const
Definition: Type.h:5328
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
Definition: SemaDecl.cpp:12535
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:1368
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2040
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:654
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
bool isConstexprSpecified() const
Definition: DeclSpec.h:692
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void setConstexpr(bool IC)
Definition: Decl.h:1236
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:12652
Expr * getAsmLabel() const
Definition: DeclSpec.h:2151
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling)
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
Definition: SemaDecl.cpp:2293
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:6826
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3166
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
Definition: SemaDecl.cpp:4480
StorageClass
Storage classes.
Definition: Specifiers.h:173
Expr * getSubExpr() const
Definition: Expr.h:1699
const SourceRange & getRange() const
Definition: DeclSpec.h:73
bool isDependentType() const
Definition: Type.h:1727
void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Direct list-initialization (C++11)
Definition: Decl.h:720
bool isFunctionOrMethod() const
Definition: DeclBase.h:1223
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:197
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1174
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
QualType getCXXNameType() const
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1510
static const TST TST_int
Definition: DeclSpec.h:283
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:858
bool isExternallyVisible() const
Definition: Decl.h:279
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:2624
DeclContextLookupResult slice(size_t N) const
Definition: DeclBase.h:1081
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:46
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:551
struct CXXOpName CXXOperatorName
DeclarationName getDeclName() const
Definition: Decl.h:189
DeclContext * getContainingDC(DeclContext *DC)
Definition: SemaDecl.cpp:1034
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1202
TagDecl * getDefinition() const
Definition: Decl.cpp:3442
ValueDecl * getDecl()
Definition: Expr.h:994
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view. Entities in anonymous namespaces are external (in c++9...
Definition: Decl.h:270
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:1798
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2405
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:1116
The result type of a method or function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration. Return null if the results were absent...
SourceLocation getLocEnd() const LLVM_READONLY
Definition: TypeLoc.h:131
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1785
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:451
RecordDecl * getDefinition() const
Definition: Decl.h:3339
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:414
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:5508
bool checkInitIsICE() const
Determine whether the value of the initializer attached to this declaration is an integral constant e...
Definition: Decl.cpp:2159
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:155
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:1241
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:611
bool isVirtualSpecified() const
Definition: DeclSpec.h:556
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:6569
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
decl_range found_decls()
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, unsigned diagnostic)
Definition: SemaDecl.cpp:3880
void setDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:226
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:204
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:2937
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:1893
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo. If Normalized is true, scale the distance down by the CharDistanceWeight to return the edit distance in terms of single-character edits.
unsigned getSpellingListIndex() const
Definition: Attr.h:90
CanQualType SignedCharTy
Definition: ASTContext.h:825
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:486
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1835
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:148
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Basic/Module.h:372
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
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:95
AttrVec & getAttrs()
Definition: DeclBase.h:431
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:731
param_const_iterator param_end() const
Definition: DeclObjC.h:362
bool isAmbiguous() const
Definition: Lookup.h:241
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Definition: SemaDecl.cpp:6233
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:144
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:81
void addAttr(Attr *A)
Definition: DeclBase.h:437
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:10718
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:365
UnqualifiedTypeNameLookupResult
Definition: SemaDecl.cpp:132
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
Definition: SemaDecl.cpp:11016
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Definition: SemaDecl.cpp:5499
void initializeFullCopy(TypeLoc Other) const
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:165
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1035
void setTypeForDecl(const Type *TD)
Definition: Decl.h:2558
Wrapper for source info for arrays.
Definition: TypeLoc.h:1346
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.h:1367
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:3551
bool doesThisDeclarationHaveABody() const
Definition: Decl.h:1773
There is no lifetime qualification on this type.
Definition: Type.h:130
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:2923
DeclContext * getEntity() const
Definition: Scope.h:310
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:208
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type. This may omit quali...
Definition: Decl.cpp:2819
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl. It will iterate at least once ...
Definition: Redeclarable.h:228
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:1722
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1511
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:10337
The "struct" keyword.
Definition: Type.h:4130
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Kind
static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, AttributeList::Kind Kind)
Definition: SemaDecl.cpp:5528
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5476
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:96
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:136
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1456
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:3610
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:172
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
Definition: SemaDecl.cpp:13941
SourceLocation getOuterLocStart() const
Definition: Decl.cpp:1674
OverrideErrorKind
Definition: SemaDecl.cpp:6561
ExternCContextDecl * getExternCContextDecl() const
Definition: ASTContext.cpp:894
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
bool isAnonymousStructOrUnion() const
Definition: Decl.cpp:3334
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:541
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:8485
unsigned getNumParams() const
Definition: Decl.cpp:2651
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.h:2110
SourceLocation CurrentPragmaLocation
Definition: Sema.h:381
const Type * getTypePtr() const
Definition: Type.h:5016
bool containedInPrototypeScope() const
Definition: Scope.cpp:94
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3344
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:1577
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache"...
Definition: Builtins.h:137
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:623
static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, void *UserData)
Member lookup function that determines whether a given C++ method overrides a method in a base class...
Definition: SemaDecl.cpp:6528
int64_t val
Definition: SemaDecl.cpp:13807
An overloaded operator name, e.g., operator+.
Definition: DeclSpec.h:880
Expr * getRepAsExpr() const
Definition: DeclSpec.h:489
bool isShadowed() const
Determine whether the lookup result was shadowed by some other declaration that lookup ignored...
Definition: Lookup.h:399
DLLExportAttr * mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex)
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1695
void FinalizeDeclaration(Decl *D)
Definition: SemaDecl.cpp:9850
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isExplicit, bool isInline, bool isImplicitlyDeclared, bool isConstexpr)
Definition: DeclCXX.cpp:1750
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function...
Definition: SemaDecl.cpp:11111
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:14406
bool isValid() const
Return true if this is a valid SourceLocation object.
OverloadedOperatorKind getCXXOverloadedOperator() const
void setFreeStanding(bool isFreeStanding=true)
Definition: Decl.h:2861
reference front() const
Definition: DeclBase.h:1076
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1132
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2694
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have...
Definition: Linkage.h:55
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:153
attr_range attrs() const
Definition: DeclBase.h:447
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:284
bool isValid() const
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.
ASTContext & getASTContext() const
Definition: Sema.h:1026
bool isLocalVarDecl() const
Definition: Decl.h:951
Data used with FindOverriddenMethod.
Definition: SemaDecl.cpp:6520
static const TST TST_union
Definition: DeclSpec.h:293
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:92
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:494
ParsedType getRepAsType() const
Definition: DeclSpec.h:481
bool isConstWithoutErrno(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno...
Definition: Builtins.h:176
const char * GetName(unsigned ID) const
Return the identifier name for the specified builtin, e.g. "__builtin_abs".
Definition: Builtins.h:85
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1717
void setDefaulted(bool D=true)
Definition: Decl.h:1806
void setHasFlexibleArrayMember(bool V)
Definition: Decl.h:3280
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:10682
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine whether there is any declaration of D that was ever a definition (perhaps before module mer...
Definition: SemaType.cpp:6376
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:1568
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:716
void setEntity(DeclContext *E)
Definition: Scope.h:311
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T)
Retrieve a version of the type 'T' that is elaborated by Keyword and qualified by the nested-name-spe...
Definition: SemaType.cpp:6713
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:2909
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:199
SourceLocation getStrTokenLoc(unsigned TokNum) const
Definition: Expr.h:1583
A friend of a previously-declared entity.
Definition: DeclBase.h:950
Name lookup found an unresolvable value declaration and cannot yet complete. This only happens in C++...
Definition: Lookup.h:52
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1412
void ResetObjCLayout(const ObjCContainerDecl *CD)
Definition: ASTContext.h:2173
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:693
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:3140
CanQualType VoidTy
Definition: ASTContext.h:817
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
decl_range decls() const
Definition: Scope.h:267
Describes the kind of initialization being performed, along with location information for tokens rela...
bool hasVolatileMember() const
Definition: Decl.h:3302
arg_range arguments()
Definition: Expr.h:2241
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or NULL if no such declaration exists...
Definition: DeclTemplate.h:908
This declaration is only a declaration.
Definition: Decl.h:993
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, SourceLocation ESpecLoc, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult())
Definition: DeclSpec.cpp:162
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:557
static const TST TST_typeofType
Definition: DeclSpec.h:298
SourceLocation getBegin() const
bool isTypeDependent() const
Definition: Expr.h:166
const T * castAs() const
Definition: Type.h:5586
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:77
lookup_result lookup(DeclarationName Name) const
Definition: DeclBase.cpp:1339
const SourceRange & getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1707
No entity found met the criteria.
Definition: Lookup.h:34
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
bool isFileContext() const
Definition: DeclBase.h:1239
static bool AllowOverloadingOfFunction(LookupResult &Previous, ASTContext &Context)
Determine whether we allow overloading of the function PrevDecl with another declaration.
Definition: SemaDecl.cpp:1189
PtrTy get() const
Definition: Ownership.h:74
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1825
bool is(tok::TokenKind K) const
Definition: Token.h:95
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:2868
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
Definition: SemaDecl.cpp:13018
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2601
Expr ** getExprs()
Definition: Expr.h:4398
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2275
bool isStaticMember()
Definition: DeclSpec.cpp:345
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:4065
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2024
Assigning into this object requires a lifetime extension.
Definition: Type.h:147
bool hasObjectMember() const
Definition: Decl.h:3299
static bool isExternC(T *D)
Definition: SemaDecl.cpp:2580
Attr * clone(ASTContext &C) const
void dropAttrs()
Definition: DeclBase.cpp:643
NamedDecl * next()
Definition: Lookup.h:577
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5086
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:128
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList)
Definition: SemaDecl.cpp:13052
void setObjCSuperType(QualType ST)
Definition: ASTContext.h:1301
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:430
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:645
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:538
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:13468
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:261
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2178
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:68
void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, TemplateParameterList **TPLists)
Definition: Decl.cpp:3485
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:1694
Opcode getOpcode() const
Definition: Expr.h:1696
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message. WARNING: Indexes apply...
Definition: SemaDecl.cpp:11311
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:3704
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.cpp:193
bool isFunctionProtoType() const
Definition: Type.h:1617
QualType getPointeeType() const
Definition: Type.h:2139
void setVirtualAsWritten(bool V)
Definition: Decl.h:1785
A constructor named via a template-id.
Definition: DeclSpec.h:888
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2509
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool containsPlaceholderType() const
Definition: DeclSpec.h:514
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:1520
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration. ...
Definition: SemaDecl.cpp:5216
void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc)
Definition: DeclSpec.h:2118
AttributeFactory & getFactory() const
CanQualType UnsignedShortTy
Definition: ASTContext.h:826
param_range params()
Definition: Decl.h:1951
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1242
static void checkModuleImportContext(Sema &S, Module *M, SourceLocation ImportLoc, DeclContext *DC)
Definition: SemaDecl.cpp:14247
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
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:14365
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
attr::Kind getKind() const
Definition: Attr.h:86
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2576
QualType getType() const
Definition: Expr.h:125
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
CanQualType CharTy
Definition: ASTContext.h:819
TLS with a dynamic initializer.
Definition: Decl.h:727
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1146
ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, SourceLocation NameLoc)
For compatibility with MSVC, we delay parsing of some default template type arguments until instantia...
Definition: SemaDecl.cpp:474
void setBody(Stmt *B)
Definition: Decl.cpp:2415
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons...
Definition: Type.h:2173
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:72
TagTypeKind
The kind of a tag type.
Definition: Type.h:4128
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:443
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2276
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:1956
SourceRange getCXXOperatorNameRange() const
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:4997
void setImplicitlyInline()
Flag that this function is implicitly inline.
Definition: Decl.h:2033
void setHasVolatileMember(bool val)
Definition: Decl.h:3303
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:10213
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:4982
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
unsigned getMSCurManglingNumber() const
Definition: Scope.h:300
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type. ...
Definition: Type.cpp:1845
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:311
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
Definition: SemaDecl.cpp:1103
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:214
A template instantiation that is currently in progress.
Definition: Sema.h:6398
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
static const TST TST_decltype
Definition: DeclSpec.h:300
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
static const TST TST_auto
Definition: DeclSpec.h:303
bool lookupInBases(BaseMatchesCallback *BaseMatches, void *UserData, CXXBasePaths &Paths) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
bool isFriendSpecified() const
Definition: DeclSpec.h:686
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1184
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W)
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1639
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:739
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Definition: ASTContext.cpp:439
void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, SourceLocation RBraceLoc, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, AttributeList *Attr)
Definition: SemaDecl.cpp:13983
bool hasInit() const
Definition: Decl.h:1065
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:4403
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceLocation RBraceLoc)
Definition: SemaDecl.cpp:12394
bool isInvalidDecl() const
Definition: DeclBase.h:498
OpenCLParamType
Definition: SemaDecl.cpp:7003
bool getProducesResult() const
Definition: Type.h:2889
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1044
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
Definition: SemaDecl.cpp:14347
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:13524
unsigned getNextFunctionPrototypeIndex()
Definition: Scope.h:261
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:827
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1209
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
bool isCallingConv() const
Definition: Type.cpp:2878
const llvm::APSInt & getInitVal() const
Definition: Decl.h:2469
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1219
SectionAttr * mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex)
This is a scope that corresponds to the template parameters of a C++ template. Template parameter sco...
Definition: Scope.h:75
virtual void HandleImplicitImportDecl(ImportDecl *D)
Handle an ImportDecl that was implicitly created due to an inclusion directive. The default implement...
Definition: ASTConsumer.cpp:30
void setShadowed()
Note that we found and ignored a declaration while performing lookup.
Definition: Lookup.h:403
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1170
unsigned short getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
Definition: SemaDecl.cpp:12892
CallingConv getCC() const
Definition: Type.h:2897
const Type * strip(QualType type)
Definition: Type.h:4989
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:3557
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
Expr * getSizeExpr() const
Definition: TypeLoc.h:1369
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition. If this could be a tentative definition (in C)...
Definition: Decl.cpp:1896
bool isUsed(bool CheckUsedAttr=true) const
Whether this declaration was used, meaning that a definition is required.
Definition: DeclBase.cpp:305
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1070
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:6861
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
A mapping from each virtual member function to its set of final overriders.
StringRef getString() const
Definition: Expr.h:1521
virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective)=0
Attempt to load the given module.
bool isThisDeclarationADefinition() const
Definition: Decl.h:1766
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:633
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool hasAttrs() const
Definition: DeclBase.h:427
VisibilityAttr * mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex)
void mergeNRVOIntoParent()
Definition: Scope.cpp:118
QualType getModifiedType() const
Definition: Type.h:3638
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:666
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const
Determine whether the token kind starts a simple-type-specifier.
Definition: SemaDecl.cpp:95
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
bool isHalfType() const
Definition: Type.h:5432
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:563
bool hasName() const
Definition: DeclSpec.h:1911
bool isSamplerT() const
Definition: Type.h:5371
unsigned getNumArgs() const
Definition: Expr.h:2205
bool isSingleResult() const
Definition: Lookup.h:248
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D)
Definition: SemaDecl.cpp:1448
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1855
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc)
Definition: SemaDecl.cpp:12357
bool isMsStruct(const ASTContext &C) const
Definition: Decl.cpp:3646
void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls)
Definition: SemaDecl.cpp:1913
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1257
DiagList Warnings
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:3503
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:10271
static const TST TST_unspecified
Definition: DeclSpec.h:277
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:4000
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
std::string ImplementationOfModule
The name of the module that the translation unit is an implementation of. Prevents semantic imports...
Definition: LangOptions.h:101
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:54
enum clang::DeclaratorChunk::@184 Kind
const RecordType * getAsStructureType() const
Definition: Type.cpp:430
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:2534
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration...
Definition: DeclBase.h:919
All of the names in this module are visible.
Definition: Basic/Module.h:209
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1428
Expr * IgnoreParenImpCasts() LLVM_READONLY
Definition: Expr.cpp:2526
DupKey(int64_t val, bool isTombstoneOrEmptyKey)
Definition: SemaDecl.cpp:13809
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2006
param_iterator param_end()
Definition: Decl.h:1948
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration...
Definition: DeclBase.h:892
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1795
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated", "unavailable", and "availability").
Definition: Sema.h:2085
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
Definition: Expr.cpp:2727
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:5088
void RemoveDecl(Decl *D)
Definition: Scope.h:276
Name lookup found a single declaration that met the criteria. getFoundDecl() will return this declara...
Definition: Lookup.h:43
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:279
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:1589
bool isKeyword() const
bool isObjCObjectType() const
Definition: Type.h:5307
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
void DiagnoseUnusedParameters(ParmVarDecl *const *Begin, ParmVarDecl *const *End)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:10226
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:196
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:97
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum. These widths include the rightmost leading 1; that is:
Definition: Decl.h:3158
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:517
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
SourceManager & getSourceManager() const
Definition: Sema.h:1024
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:3465
CanQualType UnknownAnyTy
Definition: ASTContext.h:832
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
Definition: SemaDecl.cpp:12438
const T * getAs() const
Definition: Type.h:5555
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:1523
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
QualType getCanonicalType() const
Definition: Type.h:5055
ValueType CurrentValue
Definition: Sema.h:380
UsingDecl * getUsingDecl() const
Gets the using declaration to which this declaration is tied.
Definition: DeclCXX.cpp:2078
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.h:2114
CanQualType UnsignedLongTy
Definition: ASTContext.h:826
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, Expr *Cpy)
Definition: ScopeInfo.h:833
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:967
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1626
bool isRedeclaration() const
Definition: DeclSpec.h:2201
bool isDeduced() const
Definition: Type.h:3900
CanQualType DependentTy
Definition: ASTContext.h:832
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false)
Definition: SemaDecl.cpp:1267
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:13507
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Definition: SemaDecl.cpp:1272
QualType getIntegerType() const
Definition: Decl.h:3115
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:616
void setBuiltinID(unsigned ID)
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function. Checks the key-function cache for the method'...
bool isFunctionType() const
Definition: Type.h:5229
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr)
Definition: SemaDecl.cpp:10443
static const TST TST_typename
Definition: DeclSpec.h:297
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1201
DeclContext * getRedeclContext()
Definition: DeclBase.cpp:1466
CXXConstructorDecl * getConstructor() const
Definition: ExprCXX.h:1137
const DeclarationNameLoc & getInfo() const
static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:5255
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1505
bool isTrivial() const
Definition: Decl.h:1800
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:958
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:9972
void CheckShadow(Scope *S, VarDecl *D, const LookupResult &R)
Diagnose variable or built-in function shadowing. Implements -Wshadow.
Definition: SemaDecl.cpp:6146
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
Definition: SemaDecl.cpp:14383
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:1467
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1215
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:9594
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
Definition: SemaDecl.cpp:4046
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:386
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:78
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1228
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:4011
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
void setInherited(bool I)
Definition: Attr.h:128
void setBlockVarCopyInits(VarDecl *VD, Expr *Init)
Set the copy inialization expression of a block var decl.
bool isInlineSpecified() const
Definition: DeclSpec.h:549
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd)
Definition: SemaDecl.cpp:9635
The "class" keyword.
Definition: Type.h:4136
A template-id, e.g., f<int>.
Definition: DeclSpec.h:892
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, ModuleIdPath Path)
The parser has processed a module import declaration.
Definition: SemaDecl.cpp:14277
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:982
Represents a base class of a C++ class.
Definition: DeclCXX.h:157
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:493
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2305
void setNamedTypeInfo(TypeSourceInfo *TInfo)
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.h:1371
bool isUsable() const
Definition: Ownership.h:160
This is a scope that can contain a declaration. Some scopes just contain loop constructs but don't co...
Definition: Scope.h:57
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:130
SourceManager & getSourceManager()
Definition: ASTContext.h:494
void * SkippedDefinitionContext
Definition: Sema.h:1926
bool isTLSSupported() const
Whether the target supports thread-local storage.
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:1915
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:683
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:4710
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:3317
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS)
Definition: SemaDecl.cpp:3540
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3110
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:1633
Expr * getBase() const
Definition: Expr.h:2405
bool isFunctionPrototypeScope() const
Definition: Scope.h:368
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:8996
bool isObjCGCStrong() const
isObjCGCStrong true when Type is objc's strong.
Definition: Type.h:971
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2162
Reading or writing from this object requires a barrier call.
Definition: Type.h:144
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:11324
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1371
bool isPODType(ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:1922
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
bool hasAddressSpace() const
Definition: Type.h:312
Call-style initialization (C++98)
Definition: Decl.h:719
AttributePool & getPool() const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.h:2131
bool Failed() const
Determine whether the initialization sequence is invalid.
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:160
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)
Definition: SemaDecl.cpp:4929
Captures information about "declaration specifiers".
Definition: DeclSpec.h:233
bool isExplicitSpecified() const
Definition: DeclSpec.h:559
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:1921
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Definition: Decl.h:3141
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or NULL if there isn't one...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:3045
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:253
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:876
A user-defined literal name, e.g., operator "" _i.
Definition: DeclSpec.h:884
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations from the lookup results.
Definition: SemaDecl.cpp:1315
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
Definition: SemaDecl.cpp:3329
bool isObjCObjectPointerType() const
Definition: Type.h:5304
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2229
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
Definition: SemaDecl.cpp:4515
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth=nullptr)
Definition: SemaDecl.cpp:12457
Missing a type from <stdio.h>
Definition: ASTContext.h:1646
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
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:2019
void setConstexpr(bool IC)
Definition: Decl.h:1836
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:470
virtual bool isOutOfLine() const
Definition: Decl.cpp:43
static void filterNonConflictingPreviousDecls(Sema &S, NamedDecl *decl, LookupResult &previous)
Filter out any previous declarations that the given declaration should not consider because they are ...
Definition: SemaDecl.cpp:1803
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:3942
CallingConv getDefaultCallingConvention(bool isVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
bool duplicatesAllowed() const
By default, attributes cannot be duplicated when being merged; however, an attribute can override thi...
Definition: Attr.h:118
Capturing by reference.
Definition: Lambda.h:37
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1376
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition: Scope.h:323
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1019
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:441
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:307
The "enum" keyword.
Definition: Type.h:4138
bool isEventT() const
Definition: Type.h:5375
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
Definition: SemaDecl.cpp:1589
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.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:820
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1233
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:43
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
Definition: SemaDecl.cpp:3990
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:115
void addVLATypeCapture(SourceLocation Loc, QualType CaptureType)
Definition: ScopeInfo.h:504
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:335
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
LookupResultKind getResultKind() const
Definition: Lookup.h:261
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:70
bool isTypeSpecOwned() const
Definition: DeclSpec.h:478
bool isArrayType() const
Definition: Type.h:5271
decl_iterator end()
TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:913
Defines the clang::TargetInfo interface.
Expr * getRHS() const
Definition: Expr.h:2966
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, NamedDecl **CH, unsigned CHS)
Definition: Decl.cpp:3920
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1290
TLS with a known-constant initializer.
Definition: Decl.h:726
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3222
AvailabilityResult getCurContextAvailability() const
Definition: SemaDecl.cpp:14443
ExprResult ExprError()
Definition: Ownership.h:267
The translation unit is a complete translation unit.
Definition: LangOptions.h:165
void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl *const *Begin, ParmVarDecl *const *End, 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:10242
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:2980
bool getHasRegParm() const
Definition: Type.h:2890
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1362
static bool DeclHasAttr(const Decl *D, const Attr *A)
Definition: SemaDecl.cpp:2070
bool isIncompleteArrayType() const
Definition: Type.h:5277
CanQualType IntTy
Definition: ASTContext.h:825
bool isRecord() const
Definition: DeclBase.h:1247
static OpaquePtr make(QualTypeP)
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's not an overload (nor a hidden tag declaration).
Definition: SemaDecl.cpp:2587
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:158
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:78
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Definition: Expr.h:899
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
bool isSet() const
Definition: DeclSpec.h:214
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:3941
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:128
static const TST TST_atomic
Definition: DeclSpec.h:305
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...
QualType getElementType() const
Definition: Type.h:2434
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
Definition: SemaDecl.cpp:5059
DeclContext * getPrimaryContext()
Definition: DeclBase.cpp:920
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool Override, unsigned AttrSpellingListIndex)
Attribute merging methods. Return true if a new attribute was added.
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:12422
SourceManager & SourceMgr
Definition: Sema.h:298
bool isResolvedMSAsmLabel() const
Definition: Decl.h:389
static const TST TST_struct
Definition: DeclSpec.h:294
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:52
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, Expr *Cpy)
Definition: ScopeInfo.h:496
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, const EnumDecl *Prev)
Definition: SemaDecl.cpp:11272
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3170
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1084
static bool hasDependentAlignment(VarDecl *VD)
Determines if a variable's alignment is dependent.
Definition: SemaDecl.cpp:9838
void suppressDiagnostics()
Definition: Lookup.h:522
const DeclaratorChunk & getTypeObject(unsigned i) const
Definition: DeclSpec.h:1951
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
Definition: SemaDecl.cpp:14355
AttributeList * getNext() const
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:2540
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:82
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:99
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1022
static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned NumArgs, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:2957
static DupKey GetDupKey(const llvm::APSInt &Val)
Definition: SemaDecl.cpp:13813
static unsigned getHashValue(const DupKey Key)
Definition: SemaDecl.cpp:13821
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.h:1149
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:372
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:289
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:3127
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:230
ASTContext & Context
Definition: Sema.h:295
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:2590
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex)
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:973
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:1709
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1417
bool isInvalidType() const
Definition: DeclSpec.h:2163
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1395
void dropAttr()
Definition: DeclBase.h:459
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:689
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:2621
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:411
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
No keyword precedes the qualified type name.
Definition: Type.h:4158
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1331
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5075
bool hasImplicitReturnZero() const
Definition: Decl.h:1816
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:5305
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition: DeclSpec.h:946
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:3292
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
Definition: Type.h:633
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:2611
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1047
virtual void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc)=0
Make the given module visible.
Describes an entity that is being initialized.
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:3319
unsigned NumArgs
NumArgs - The number of template arguments.
Decl * getObjCDeclContext() const
Definition: SemaDecl.cpp:14439
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2191
NamedDecl * Previous
Definition: Sema.h:1849
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:597
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:3177
Missing a type from <setjmp.h>
Definition: ASTContext.h:1647
void setType(QualType newType)
Definition: Decl.h:539
Wrapper for source info for pointers.
Definition: TypeLoc.h:1122
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Definition: Type.cpp:3326
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:1863
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2089
No in-class initializer.
Definition: Specifiers.h:198
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
Definition: SemaDecl.cpp:4357
bool isBeingDefined() const
isBeingDefined - Return true if this decl is currently being defined.
Definition: Decl.h:2849
bool isIntegralType(ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1602
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
enum clang::UnqualifiedId::IdKind Kind
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
Definition: DeclTemplate.h:821
void clear()
Clears out any current state.
Definition: Lookup.h:494
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1718
Attr - This represents one attribute.
Definition: Attr.h:44
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:735
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:2779
bool hasLocalStorage() const
Definition: Decl.h:887
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:2814
const RecordDecl * getParent() const
Definition: Decl.h:2424
Expr * IgnoreParens() LLVM_READONLY
Definition: Expr.cpp:2408
const DeclSpec & getDeclSpec() const
Definition: DeclSpec.h:1676
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:4584
CanQualType UnsignedIntTy
Definition: ASTContext.h:826
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:7042
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5043
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Definition: SemaDecl.cpp:1289
bool isPointerType() const
Definition: Type.h:5232
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:654
bool isPOD() const
Whether this class is a POD-type (C++ [class]p4)
Definition: DeclCXX.h:1130
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
A RAII object to temporarily push a declaration context.
Definition: Sema.h:601
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:1536
The translation unit is a module.
Definition: LangOptions.h:170
const AttributeList * getAttributes() const
Definition: DeclSpec.h:2125
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:126
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
QualType getDeducedType() const
Get the type deduced for this auto type, or null if it's either not been deduced or was deduced to a ...
Definition: Type.h:3897