clang  9.0.0svn
SemaDecl.cpp
Go to the documentation of this file.
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 
50 using namespace clang;
51 using namespace sema;
52 
54  if (OwnedType) {
55  Decl *Group[2] = { OwnedType, Ptr };
56  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57  }
58 
59  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
67  bool AllowTemplates = false,
68  bool AllowNonTemplates = true)
69  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70  AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
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  if (!AllowInvalidDecl && ND->isInvalidDecl())
79  return false;
80 
81  if (getAsTypeTemplateDecl(ND))
82  return AllowTemplates;
83 
84  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85  if (!IsType)
86  return false;
87 
88  if (AllowNonTemplates)
89  return true;
90 
91  // An injected-class-name of a class template (specialization) is valid
92  // as a template or as a non-template.
93  if (AllowTemplates) {
94  auto *RD = dyn_cast<CXXRecordDecl>(ND);
95  if (!RD || !RD->isInjectedClassName())
96  return false;
97  RD = cast<CXXRecordDecl>(RD->getDeclContext());
98  return RD->getDescribedClassTemplate() ||
99  isa<ClassTemplateSpecializationDecl>(RD);
100  }
101 
102  return false;
103  }
104 
105  return !WantClassName && candidate.isKeyword();
106  }
107 
108  private:
109  bool AllowInvalidDecl;
110  bool WantClassName;
111  bool AllowTemplates;
112  bool AllowNonTemplates;
113 };
114 
115 } // end anonymous namespace
116 
117 /// Determine whether the token kind starts a simple-type-specifier.
119  switch (Kind) {
120  // FIXME: Take into account the current language when deciding whether a
121  // token kind is a valid type specifier
122  case tok::kw_short:
123  case tok::kw_long:
124  case tok::kw___int64:
125  case tok::kw___int128:
126  case tok::kw_signed:
127  case tok::kw_unsigned:
128  case tok::kw_void:
129  case tok::kw_char:
130  case tok::kw_int:
131  case tok::kw_half:
132  case tok::kw_float:
133  case tok::kw_double:
134  case tok::kw__Float16:
135  case tok::kw___float128:
136  case tok::kw_wchar_t:
137  case tok::kw_bool:
138  case tok::kw___underlying_type:
139  case tok::kw___auto_type:
140  return true;
141 
142  case tok::annot_typename:
143  case tok::kw_char16_t:
144  case tok::kw_char32_t:
145  case tok::kw_typeof:
146  case tok::annot_decltype:
147  case tok::kw_decltype:
148  return getLangOpts().CPlusPlus;
149 
150  case tok::kw_char8_t:
151  return getLangOpts().Char8;
152 
153  default:
154  break;
155  }
156 
157  return false;
158 }
159 
160 namespace {
162  NotFound,
163  FoundNonType,
164  FoundType
165 };
166 } // end anonymous namespace
167 
168 /// Tries to perform unqualified lookup of the type decls in bases for
169 /// dependent class.
170 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
171 /// type decl, \a FoundType if only type decls are found.
174  SourceLocation NameLoc,
175  const CXXRecordDecl *RD) {
176  if (!RD->hasDefinition())
177  return UnqualifiedTypeNameLookupResult::NotFound;
178  // Look for type decls in base classes.
179  UnqualifiedTypeNameLookupResult FoundTypeDecl =
180  UnqualifiedTypeNameLookupResult::NotFound;
181  for (const auto &Base : RD->bases()) {
182  const CXXRecordDecl *BaseRD = nullptr;
183  if (auto *BaseTT = Base.getType()->getAs<TagType>())
184  BaseRD = BaseTT->getAsCXXRecordDecl();
185  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
186  // Look for type decls in dependent base classes that have known primary
187  // templates.
188  if (!TST || !TST->isDependentType())
189  continue;
190  auto *TD = TST->getTemplateName().getAsTemplateDecl();
191  if (!TD)
192  continue;
193  if (auto *BasePrimaryTemplate =
194  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
195  if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
196  BaseRD = BasePrimaryTemplate;
197  else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199  CTD->findPartialSpecialization(Base.getType()))
200  if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
201  BaseRD = PS;
202  }
203  }
204  }
205  if (BaseRD) {
206  for (NamedDecl *ND : BaseRD->lookup(&II)) {
207  if (!isa<TypeDecl>(ND))
208  return UnqualifiedTypeNameLookupResult::FoundNonType;
209  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
210  }
211  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
212  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
213  case UnqualifiedTypeNameLookupResult::FoundNonType:
214  return UnqualifiedTypeNameLookupResult::FoundNonType;
215  case UnqualifiedTypeNameLookupResult::FoundType:
216  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217  break;
218  case UnqualifiedTypeNameLookupResult::NotFound:
219  break;
220  }
221  }
222  }
223  }
224 
225  return FoundTypeDecl;
226 }
227 
229  const IdentifierInfo &II,
230  SourceLocation NameLoc) {
231  // Lookup in the parent class template context, if any.
232  const CXXRecordDecl *RD = nullptr;
233  UnqualifiedTypeNameLookupResult FoundTypeDecl =
234  UnqualifiedTypeNameLookupResult::NotFound;
235  for (DeclContext *DC = S.CurContext;
236  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
237  DC = DC->getParent()) {
238  // Look for type decls in dependent base classes that have known primary
239  // templates.
240  RD = dyn_cast<CXXRecordDecl>(DC);
241  if (RD && RD->getDescribedClassTemplate())
242  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
243  }
244  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
245  return nullptr;
246 
247  // We found some types in dependent base classes. Recover as if the user
248  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
249  // lookup during template instantiation.
250  S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
251 
252  ASTContext &Context = S.Context;
253  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
254  cast<Type>(Context.getRecordType(RD)));
255  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
256 
257  CXXScopeSpec SS;
258  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
259 
260  TypeLocBuilder Builder;
261  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
262  DepTL.setNameLoc(NameLoc);
264  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
265  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
266 }
267 
268 /// If the identifier refers to a type name within this scope,
269 /// return the declaration of that type.
270 ///
271 /// This routine performs ordinary name lookup of the identifier II
272 /// within the given scope, with optional C++ scope specifier SS, to
273 /// determine whether the name refers to a type. If so, returns an
274 /// opaque pointer (actually a QualType) corresponding to that
275 /// type. Otherwise, returns NULL.
277  Scope *S, CXXScopeSpec *SS,
278  bool isClassName, bool HasTrailingDot,
279  ParsedType ObjectTypePtr,
280  bool IsCtorOrDtorName,
281  bool WantNontrivialTypeSourceInfo,
282  bool IsClassTemplateDeductionContext,
283  IdentifierInfo **CorrectedII) {
284  // FIXME: Consider allowing this outside C++1z mode as an extension.
285  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286  getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
287  !isClassName && !HasTrailingDot;
288 
289  // Determine where we will perform name lookup.
290  DeclContext *LookupCtx = nullptr;
291  if (ObjectTypePtr) {
292  QualType ObjectType = ObjectTypePtr.get();
293  if (ObjectType->isRecordType())
294  LookupCtx = computeDeclContext(ObjectType);
295  } else if (SS && SS->isNotEmpty()) {
296  LookupCtx = computeDeclContext(*SS, false);
297 
298  if (!LookupCtx) {
299  if (isDependentScopeSpecifier(*SS)) {
300  // C++ [temp.res]p3:
301  // A qualified-id that refers to a type and in which the
302  // nested-name-specifier depends on a template-parameter (14.6.2)
303  // shall be prefixed by the keyword typename to indicate that the
304  // qualified-id denotes a type, forming an
305  // elaborated-type-specifier (7.1.5.3).
306  //
307  // We therefore do not perform any name lookup if the result would
308  // refer to a member of an unknown specialization.
309  if (!isClassName && !IsCtorOrDtorName)
310  return nullptr;
311 
312  // We know from the grammar that this name refers to a type,
313  // so build a dependent node to describe the type.
314  if (WantNontrivialTypeSourceInfo)
315  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
316 
317  NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
318  QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
319  II, NameLoc);
320  return ParsedType::make(T);
321  }
322 
323  return nullptr;
324  }
325 
326  if (!LookupCtx->isDependentContext() &&
327  RequireCompleteDeclContext(*SS, LookupCtx))
328  return nullptr;
329  }
330 
331  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
332  // lookup for class-names.
333  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
334  LookupOrdinaryName;
335  LookupResult Result(*this, &II, NameLoc, Kind);
336  if (LookupCtx) {
337  // Perform "qualified" name lookup into the declaration context we
338  // computed, which is either the type of the base of a member access
339  // expression or the declaration context associated with a prior
340  // nested-name-specifier.
341  LookupQualifiedName(Result, LookupCtx);
342 
343  if (ObjectTypePtr && Result.empty()) {
344  // C++ [basic.lookup.classref]p3:
345  // If the unqualified-id is ~type-name, the type-name is looked up
346  // in the context of the entire postfix-expression. If the type T of
347  // the object expression is of a class type C, the type-name is also
348  // looked up in the scope of class C. At least one of the lookups shall
349  // find a name that refers to (possibly cv-qualified) T.
350  LookupName(Result, S);
351  }
352  } else {
353  // Perform unqualified name lookup.
354  LookupName(Result, S);
355 
356  // For unqualified lookup in a class template in MSVC mode, look into
357  // dependent base classes where the primary class template is known.
358  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
359  if (ParsedType TypeInBase =
360  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
361  return TypeInBase;
362  }
363  }
364 
365  NamedDecl *IIDecl = nullptr;
366  switch (Result.getResultKind()) {
369  if (CorrectedII) {
370  TypoCorrection Correction =
371  CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
372  llvm::make_unique<TypeNameValidatorCCC>(
373  true, isClassName, AllowDeducedTemplate),
374  CTK_ErrorRecovery);
375  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
376  TemplateTy Template;
377  bool MemberOfUnknownSpecialization;
379  TemplateName.setIdentifier(NewII, NameLoc);
380  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
381  CXXScopeSpec NewSS, *NewSSPtr = SS;
382  if (SS && NNS) {
383  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
384  NewSSPtr = &NewSS;
385  }
386  if (Correction && (NNS || NewII != &II) &&
387  // Ignore a correction to a template type as the to-be-corrected
388  // identifier is not a template (typo correction for template names
389  // is handled elsewhere).
390  !(getLangOpts().CPlusPlus && NewSSPtr &&
391  isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
392  Template, MemberOfUnknownSpecialization))) {
393  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
394  isClassName, HasTrailingDot, ObjectTypePtr,
395  IsCtorOrDtorName,
396  WantNontrivialTypeSourceInfo,
397  IsClassTemplateDeductionContext);
398  if (Ty) {
399  diagnoseTypo(Correction,
400  PDiag(diag::err_unknown_type_or_class_name_suggest)
401  << Result.getLookupName() << isClassName);
402  if (SS && NNS)
403  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
404  *CorrectedII = NewII;
405  return Ty;
406  }
407  }
408  }
409  // If typo correction failed or was not performed, fall through
410  LLVM_FALLTHROUGH;
413  Result.suppressDiagnostics();
414  return nullptr;
415 
417  // Recover from type-hiding ambiguities by hiding the type. We'll
418  // do the lookup again when looking for an object, and we can
419  // diagnose the error then. If we don't do this, then the error
420  // about hiding the type will be immediately followed by an error
421  // that only makes sense if the identifier was treated like a type.
423  Result.suppressDiagnostics();
424  return nullptr;
425  }
426 
427  // Look to see if we have a type anywhere in the list of results.
428  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
429  Res != ResEnd; ++Res) {
430  if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
431  (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
432  if (!IIDecl ||
433  (*Res)->getLocation().getRawEncoding() <
434  IIDecl->getLocation().getRawEncoding())
435  IIDecl = *Res;
436  }
437  }
438 
439  if (!IIDecl) {
440  // None of the entities we found is a type, so there is no way
441  // to even assume that the result is a type. In this case, don't
442  // complain about the ambiguity. The parser will either try to
443  // perform this lookup again (e.g., as an object name), which
444  // will produce the ambiguity, or will complain that it expected
445  // a type name.
446  Result.suppressDiagnostics();
447  return nullptr;
448  }
449 
450  // We found a type within the ambiguous lookup; diagnose the
451  // ambiguity and then return that type. This might be the right
452  // answer, or it might not be, but it suppresses any attempt to
453  // perform the name lookup again.
454  break;
455 
456  case LookupResult::Found:
457  IIDecl = Result.getFoundDecl();
458  break;
459  }
460 
461  assert(IIDecl && "Didn't find decl");
462 
463  QualType T;
464  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
465  // C++ [class.qual]p2: A lookup that would find the injected-class-name
466  // instead names the constructors of the class, except when naming a class.
467  // This is ill-formed when we're not actually forming a ctor or dtor name.
468  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
469  auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
470  if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
471  FoundRD->isInjectedClassName() &&
472  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
473  Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
474  << &II << /*Type*/1;
475 
476  DiagnoseUseOfDecl(IIDecl, NameLoc);
477 
478  T = Context.getTypeDeclType(TD);
479  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
480  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
481  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
482  if (!HasTrailingDot)
483  T = Context.getObjCInterfaceType(IDecl);
484  } else if (AllowDeducedTemplate) {
485  if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487  QualType(), false);
488  }
489 
490  if (T.isNull()) {
491  // If it's not plausibly a type, suppress diagnostics.
492  Result.suppressDiagnostics();
493  return nullptr;
494  }
495 
496  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
497  // constructor or destructor name (in such a case, the scope specifier
498  // will be attached to the enclosing Expr or Decl node).
499  if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
500  !isa<ObjCInterfaceDecl>(IIDecl)) {
501  if (WantNontrivialTypeSourceInfo) {
502  // Construct a type with type-source information.
503  TypeLocBuilder Builder;
504  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
505 
506  T = getElaboratedType(ETK_None, *SS, T);
507  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509  ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
510  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
511  } else {
512  T = getElaboratedType(ETK_None, *SS, T);
513  }
514  }
515 
516  return ParsedType::make(T);
517 }
518 
519 // Builds a fake NNS for the given decl context.
520 static NestedNameSpecifier *
522  for (;; DC = DC->getLookupParent()) {
523  DC = DC->getPrimaryContext();
524  auto *ND = dyn_cast<NamespaceDecl>(DC);
525  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
526  return NestedNameSpecifier::Create(Context, nullptr, ND);
527  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
528  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
529  RD->getTypeForDecl());
530  else if (isa<TranslationUnitDecl>(DC))
531  return NestedNameSpecifier::GlobalSpecifier(Context);
532  }
533  llvm_unreachable("something isn't in TU scope?");
534 }
535 
536 /// Find the parent class with dependent bases of the innermost enclosing method
537 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
538 /// up allowing unqualified dependent type names at class-level, which MSVC
539 /// correctly rejects.
540 static const CXXRecordDecl *
542  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
543  DC = DC->getPrimaryContext();
544  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
545  if (MD->getParent()->hasAnyDependentBases())
546  return MD->getParent();
547  }
548  return nullptr;
549 }
550 
552  SourceLocation NameLoc,
553  bool IsTemplateTypeArg) {
554  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
555 
556  NestedNameSpecifier *NNS = nullptr;
557  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
558  // If we weren't able to parse a default template argument, delay lookup
559  // until instantiation time by making a non-dependent DependentTypeName. We
560  // pretend we saw a NestedNameSpecifier referring to the current scope, and
561  // lookup is retried.
562  // FIXME: This hurts our diagnostic quality, since we get errors like "no
563  // type named 'Foo' in 'current_namespace'" when the user didn't write any
564  // name specifiers.
565  NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
566  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
567  } else if (const CXXRecordDecl *RD =
569  // Build a DependentNameType that will perform lookup into RD at
570  // instantiation time.
571  NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572  RD->getTypeForDecl());
573 
574  // Diagnose that this identifier was undeclared, and retry the lookup during
575  // template instantiation.
576  Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
577  << RD;
578  } else {
579  // This is not a situation that we should recover from.
580  return ParsedType();
581  }
582 
583  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
584 
585  // Build type location information. We synthesized the qualifier, so we have
586  // to build a fake NestedNameSpecifierLoc.
587  NestedNameSpecifierLocBuilder NNSLocBuilder;
588  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
589  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
590 
591  TypeLocBuilder Builder;
592  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
593  DepTL.setNameLoc(NameLoc);
595  DepTL.setQualifierLoc(QualifierLoc);
596  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
597 }
598 
599 /// isTagName() - This method is called *for error recovery purposes only*
600 /// to determine if the specified name is a valid tag name ("struct foo"). If
601 /// so, this returns the TST for the tag corresponding to it (TST_enum,
602 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
603 /// cases in C where the user forgot to specify the tag.
605  // Do a tag name lookup in this scope.
606  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
607  LookupName(R, S, false);
610  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
611  switch (TD->getTagKind()) {
612  case TTK_Struct: return DeclSpec::TST_struct;
614  case TTK_Union: return DeclSpec::TST_union;
615  case TTK_Class: return DeclSpec::TST_class;
616  case TTK_Enum: return DeclSpec::TST_enum;
617  }
618  }
619 
621 }
622 
623 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
624 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
625 /// then downgrade the missing typename error to a warning.
626 /// This is needed for MSVC compatibility; Example:
627 /// @code
628 /// template<class T> class A {
629 /// public:
630 /// typedef int TYPE;
631 /// };
632 /// template<class T> class B : public A<T> {
633 /// public:
634 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
635 /// };
636 /// @endcode
638  if (CurContext->isRecord()) {
640  return true;
641 
642  const Type *Ty = SS->getScopeRep()->getAsType();
643 
644  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
645  for (const auto &Base : RD->bases())
646  if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
647  return true;
648  return S->isFunctionPrototypeScope();
649  }
650  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
651 }
652 
654  SourceLocation IILoc,
655  Scope *S,
656  CXXScopeSpec *SS,
657  ParsedType &SuggestedType,
658  bool IsTemplateName) {
659  // Don't report typename errors for editor placeholders.
660  if (II->isEditorPlaceholder())
661  return;
662  // We don't have anything to suggest (yet).
663  SuggestedType = nullptr;
664 
665  // There may have been a typo in the name of the type. Look up typo
666  // results, in case we have something that we can suggest.
667  if (TypoCorrection Corrected =
668  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
669  llvm::make_unique<TypeNameValidatorCCC>(
670  false, false, IsTemplateName, !IsTemplateName),
671  CTK_ErrorRecovery)) {
672  // FIXME: Support error recovery for the template-name case.
673  bool CanRecover = !IsTemplateName;
674  if (Corrected.isKeyword()) {
675  // We corrected to a keyword.
676  diagnoseTypo(Corrected,
677  PDiag(IsTemplateName ? diag::err_no_template_suggest
678  : diag::err_unknown_typename_suggest)
679  << II);
680  II = Corrected.getCorrectionAsIdentifierInfo();
681  } else {
682  // We found a similarly-named type or interface; suggest that.
683  if (!SS || !SS->isSet()) {
684  diagnoseTypo(Corrected,
685  PDiag(IsTemplateName ? diag::err_no_template_suggest
686  : diag::err_unknown_typename_suggest)
687  << II, CanRecover);
688  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
689  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
690  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
691  II->getName().equals(CorrectedStr);
692  diagnoseTypo(Corrected,
693  PDiag(IsTemplateName
694  ? diag::err_no_member_template_suggest
695  : diag::err_unknown_nested_typename_suggest)
696  << II << DC << DroppedSpecifier << SS->getRange(),
697  CanRecover);
698  } else {
699  llvm_unreachable("could not have corrected a typo here");
700  }
701 
702  if (!CanRecover)
703  return;
704 
705  CXXScopeSpec tmpSS;
706  if (Corrected.getCorrectionSpecifier())
707  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
708  SourceRange(IILoc));
709  // FIXME: Support class template argument deduction here.
710  SuggestedType =
711  getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
712  tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
713  /*IsCtorOrDtorName=*/false,
714  /*NonTrivialTypeSourceInfo=*/true);
715  }
716  return;
717  }
718 
719  if (getLangOpts().CPlusPlus && !IsTemplateName) {
720  // See if II is a class template that the user forgot to pass arguments to.
721  UnqualifiedId Name;
722  Name.setIdentifier(II, IILoc);
723  CXXScopeSpec EmptySS;
724  TemplateTy TemplateResult;
725  bool MemberOfUnknownSpecialization;
726  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
727  Name, nullptr, true, TemplateResult,
728  MemberOfUnknownSpecialization) == TNK_Type_template) {
729  diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
730  return;
731  }
732  }
733 
734  // FIXME: Should we move the logic that tries to recover from a missing tag
735  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
736 
737  if (!SS || (!SS->isSet() && !SS->isInvalid()))
738  Diag(IILoc, IsTemplateName ? diag::err_no_template
739  : diag::err_unknown_typename)
740  << II;
741  else if (DeclContext *DC = computeDeclContext(*SS, false))
742  Diag(IILoc, IsTemplateName ? diag::err_no_member_template
743  : diag::err_typename_nested_not_found)
744  << II << DC << SS->getRange();
745  else if (isDependentScopeSpecifier(*SS)) {
746  unsigned DiagID = diag::err_typename_missing;
747  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
748  DiagID = diag::ext_typename_missing;
749 
750  Diag(SS->getRange().getBegin(), DiagID)
751  << SS->getScopeRep() << II->getName()
752  << SourceRange(SS->getRange().getBegin(), IILoc)
753  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
754  SuggestedType = ActOnTypenameType(S, SourceLocation(),
755  *SS, *II, IILoc).get();
756  } else {
757  assert(SS && SS->isInvalid() &&
758  "Invalid scope specifier has already been diagnosed");
759  }
760 }
761 
762 /// Determine whether the given result set contains either a type name
763 /// or
764 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
765  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
766  NextToken.is(tok::less);
767 
768  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
769  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
770  return true;
771 
772  if (CheckTemplate && isa<TemplateDecl>(*I))
773  return true;
774  }
775 
776  return false;
777 }
778 
779 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
780  Scope *S, CXXScopeSpec &SS,
781  IdentifierInfo *&Name,
782  SourceLocation NameLoc) {
783  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
784  SemaRef.LookupParsedName(R, S, &SS);
785  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
786  StringRef FixItTagName;
787  switch (Tag->getTagKind()) {
788  case TTK_Class:
789  FixItTagName = "class ";
790  break;
791 
792  case TTK_Enum:
793  FixItTagName = "enum ";
794  break;
795 
796  case TTK_Struct:
797  FixItTagName = "struct ";
798  break;
799 
800  case TTK_Interface:
801  FixItTagName = "__interface ";
802  break;
803 
804  case TTK_Union:
805  FixItTagName = "union ";
806  break;
807  }
808 
809  StringRef TagName = FixItTagName.drop_back();
810  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
811  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
812  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
813 
814  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
815  I != IEnd; ++I)
816  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
817  << Name << TagName;
818 
819  // Replace lookup results with just the tag decl.
820  Result.clear(Sema::LookupTagName);
821  SemaRef.LookupParsedName(Result, S, &SS);
822  return true;
823  }
824 
825  return false;
826 }
827 
828 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830  QualType T, SourceLocation NameLoc) {
831  ASTContext &Context = S.Context;
832 
833  TypeLocBuilder Builder;
834  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
835 
836  T = S.getElaboratedType(ETK_None, SS, T);
837  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
840  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
841 }
842 
845  SourceLocation NameLoc, const Token &NextToken,
846  bool IsAddressOfOperand,
847  std::unique_ptr<CorrectionCandidateCallback> CCC) {
848  DeclarationNameInfo NameInfo(Name, NameLoc);
849  ObjCMethodDecl *CurMethod = getCurMethodDecl();
850 
851  if (NextToken.is(tok::coloncolon)) {
852  NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
853  BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
854  } else if (getLangOpts().CPlusPlus && SS.isSet() &&
855  isCurrentClassName(*Name, S, &SS)) {
856  // Per [class.qual]p2, this names the constructors of SS, not the
857  // injected-class-name. We don't have a classification for that.
858  // There's not much point caching this result, since the parser
859  // will reject it later.
861  }
862 
863  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
864  LookupParsedName(Result, S, &SS, !CurMethod);
865 
866  // For unqualified lookup in a class template in MSVC mode, look into
867  // dependent base classes where the primary class template is known.
868  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
869  if (ParsedType TypeInBase =
870  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
871  return TypeInBase;
872  }
873 
874  // Perform lookup for Objective-C instance variables (including automatically
875  // synthesized instance variables), if we're in an Objective-C method.
876  // FIXME: This lookup really, really needs to be folded in to the normal
877  // unqualified lookup mechanism.
878  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
879  ExprResult E = LookupInObjCMethod(Result, S, Name, true);
880  if (E.get() || E.isInvalid())
881  return E;
882  }
883 
884  bool SecondTry = false;
885  bool IsFilteredTemplateName = false;
886 
887 Corrected:
888  switch (Result.getResultKind()) {
890  // If an unqualified-id is followed by a '(', then we have a function
891  // call.
892  if (!SS.isSet() && NextToken.is(tok::l_paren)) {
893  // In C++, this is an ADL-only call.
894  // FIXME: Reference?
895  if (getLangOpts().CPlusPlus)
896  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
897 
898  // C90 6.3.2.2:
899  // If the expression that precedes the parenthesized argument list in a
900  // function call consists solely of an identifier, and if no
901  // declaration is visible for this identifier, the identifier is
902  // implicitly declared exactly as if, in the innermost block containing
903  // the function call, the declaration
904  //
905  // extern int identifier ();
906  //
907  // appeared.
908  //
909  // We also allow this in C99 as an extension.
910  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
911  Result.addDecl(D);
912  Result.resolveKind();
913  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
914  }
915  }
916 
917  // In C, we first see whether there is a tag type by the same name, in
918  // which case it's likely that the user just forgot to write "enum",
919  // "struct", or "union".
920  if (!getLangOpts().CPlusPlus && !SecondTry &&
921  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
922  break;
923  }
924 
925  // Perform typo correction to determine if there is another name that is
926  // close to this name.
927  if (!SecondTry && CCC) {
928  SecondTry = true;
929  if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
930  Result.getLookupKind(), S,
931  &SS, std::move(CCC),
932  CTK_ErrorRecovery)) {
933  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
934  unsigned QualifiedDiag = diag::err_no_member_suggest;
935 
936  NamedDecl *FirstDecl = Corrected.getFoundDecl();
937  NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
938  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
939  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
940  UnqualifiedDiag = diag::err_no_template_suggest;
941  QualifiedDiag = diag::err_no_member_template_suggest;
942  } else if (UnderlyingFirstDecl &&
943  (isa<TypeDecl>(UnderlyingFirstDecl) ||
944  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
945  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
946  UnqualifiedDiag = diag::err_unknown_typename_suggest;
947  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
948  }
949 
950  if (SS.isEmpty()) {
951  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
952  } else {// FIXME: is this even reachable? Test it.
953  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
954  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
955  Name->getName().equals(CorrectedStr);
956  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
957  << Name << computeDeclContext(SS, false)
958  << DroppedSpecifier << SS.getRange());
959  }
960 
961  // Update the name, so that the caller has the new name.
962  Name = Corrected.getCorrectionAsIdentifierInfo();
963 
964  // Typo correction corrected to a keyword.
965  if (Corrected.isKeyword())
966  return Name;
967 
968  // Also update the LookupResult...
969  // FIXME: This should probably go away at some point
970  Result.clear();
971  Result.setLookupName(Corrected.getCorrection());
972  if (FirstDecl)
973  Result.addDecl(FirstDecl);
974 
975  // If we found an Objective-C instance variable, let
976  // LookupInObjCMethod build the appropriate expression to
977  // reference the ivar.
978  // FIXME: This is a gross hack.
979  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
980  Result.clear();
981  ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
982  return E;
983  }
984 
985  goto Corrected;
986  }
987  }
988 
989  // We failed to correct; just fall through and let the parser deal with it.
990  Result.suppressDiagnostics();
992 
994  // We performed name lookup into the current instantiation, and there were
995  // dependent bases, so we treat this result the same way as any other
996  // dependent nested-name-specifier.
997 
998  // C++ [temp.res]p2:
999  // A name used in a template declaration or definition and that is
1000  // dependent on a template-parameter is assumed not to name a type
1001  // unless the applicable name lookup finds a type name or the name is
1002  // qualified by the keyword typename.
1003  //
1004  // FIXME: If the next token is '<', we might want to ask the parser to
1005  // perform some heroics to see if we actually have a
1006  // template-argument-list, which would indicate a missing 'template'
1007  // keyword here.
1008  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1009  NameInfo, IsAddressOfOperand,
1010  /*TemplateArgs=*/nullptr);
1011  }
1012 
1013  case LookupResult::Found:
1016  break;
1017 
1019  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1020  hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1021  /*AllowDependent=*/false)) {
1022  // C++ [temp.local]p3:
1023  // A lookup that finds an injected-class-name (10.2) can result in an
1024  // ambiguity in certain cases (for example, if it is found in more than
1025  // one base class). If all of the injected-class-names that are found
1026  // refer to specializations of the same class template, and if the name
1027  // is followed by a template-argument-list, the reference refers to the
1028  // class template itself and not a specialization thereof, and is not
1029  // ambiguous.
1030  //
1031  // This filtering can make an ambiguous result into an unambiguous one,
1032  // so try again after filtering out template names.
1033  FilterAcceptableTemplateNames(Result);
1034  if (!Result.isAmbiguous()) {
1035  IsFilteredTemplateName = true;
1036  break;
1037  }
1038  }
1039 
1040  // Diagnose the ambiguity and return an error.
1041  return NameClassification::Error();
1042  }
1043 
1044  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045  (IsFilteredTemplateName ||
1046  hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047  /*AllowDependent=*/false))) {
1048  // C++ [temp.names]p3:
1049  // After name lookup (3.4) finds that a name is a template-name or that
1050  // an operator-function-id or a literal- operator-id refers to a set of
1051  // overloaded functions any member of which is a function template if
1052  // this is followed by a <, the < is always taken as the delimiter of a
1053  // template-argument-list and never as the less-than operator.
1054  if (!IsFilteredTemplateName)
1055  FilterAcceptableTemplateNames(Result);
1056 
1057  if (!Result.empty()) {
1058  bool IsFunctionTemplate;
1059  bool IsVarTemplate;
1060  TemplateName Template;
1061  if (Result.end() - Result.begin() > 1) {
1062  IsFunctionTemplate = true;
1063  Template = Context.getOverloadedTemplateName(Result.begin(),
1064  Result.end());
1065  } else {
1066  auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1067  *Result.begin(), /*AllowFunctionTemplates=*/true,
1068  /*AllowDependent=*/false));
1069  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070  IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072  if (SS.isSet() && !SS.isInvalid())
1073  Template =
1075  /*TemplateKeyword=*/false, TD);
1076  else
1077  Template = TemplateName(TD);
1078  }
1079 
1080  if (IsFunctionTemplate) {
1081  // Function templates always go through overload resolution, at which
1082  // point we'll perform the various checks (e.g., accessibility) we need
1083  // to based on which function we selected.
1084  Result.suppressDiagnostics();
1085 
1086  return NameClassification::FunctionTemplate(Template);
1087  }
1088 
1089  return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090  : NameClassification::TypeTemplate(Template);
1091  }
1092  }
1093 
1094  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096  DiagnoseUseOfDecl(Type, NameLoc);
1097  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098  QualType T = Context.getTypeDeclType(Type);
1099  if (SS.isNotEmpty())
1100  return buildNestedType(*this, SS, T, NameLoc);
1101  return ParsedType::make(T);
1102  }
1103 
1104  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105  if (!Class) {
1106  // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107  if (ObjCCompatibleAliasDecl *Alias =
1108  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109  Class = Alias->getClassInterface();
1110  }
1111 
1112  if (Class) {
1113  DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115  if (NextToken.is(tok::period)) {
1116  // Interface. <something> is parsed as a property reference expression.
1117  // Just return "unknown" as a fall-through for now.
1118  Result.suppressDiagnostics();
1119  return NameClassification::Unknown();
1120  }
1121 
1122  QualType T = Context.getObjCInterfaceType(Class);
1123  return ParsedType::make(T);
1124  }
1125 
1126  // We can have a type template here if we're classifying a template argument.
1127  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128  !isa<VarTemplateDecl>(FirstDecl))
1129  return NameClassification::TypeTemplate(
1130  TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132  // Check for a tag type hidden by a non-type decl in a few cases where it
1133  // seems likely a type is wanted instead of the non-type that was found.
1134  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135  if ((NextToken.is(tok::identifier) ||
1136  (NextIsOp &&
1137  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140  DiagnoseUseOfDecl(Type, NameLoc);
1141  QualType T = Context.getTypeDeclType(Type);
1142  if (SS.isNotEmpty())
1143  return buildNestedType(*this, SS, T, NameLoc);
1144  return ParsedType::make(T);
1145  }
1146 
1147  if (FirstDecl->isCXXClassMember())
1148  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149  nullptr, S);
1150 
1151  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152  return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1157  auto *TD = Name.getAsTemplateDecl();
1158  if (!TD)
1159  return TemplateNameKindForDiagnostics::DependentTemplate;
1160  if (isa<ClassTemplateDecl>(TD))
1161  return TemplateNameKindForDiagnostics::ClassTemplate;
1162  if (isa<FunctionTemplateDecl>(TD))
1163  return TemplateNameKindForDiagnostics::FunctionTemplate;
1164  if (isa<VarTemplateDecl>(TD))
1165  return TemplateNameKindForDiagnostics::VarTemplate;
1166  if (isa<TypeAliasTemplateDecl>(TD))
1167  return TemplateNameKindForDiagnostics::AliasTemplate;
1168  if (isa<TemplateTemplateParmDecl>(TD))
1169  return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170  return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context. This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1177 
1178  // Functions defined inline within classes aren't parsed until we've
1179  // finished parsing the top-level class, so the top-level class is
1180  // the context we'll need to return to.
1181  // A Lambda call operator whose parent is a class must not be treated
1182  // as an inline member function. A Lambda can be used legally
1183  // either as an in-class member initializer or a default argument. These
1184  // are parsed once the class has been marked complete and so the containing
1185  // context would be the nested class (when the lambda is defined in one);
1186  // If the class is not complete, then the lambda is being used in an
1187  // ill-formed fashion (such as to specify the width of a bit-field, or
1188  // in an array-bound) - in which case we still want to return the
1189  // lexically containing DC (which could be a nested class).
1190  if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191  DC = DC->getLexicalParent();
1192 
1193  // A function not defined within a class will always return to its
1194  // lexical context.
1195  if (!isa<CXXRecordDecl>(DC))
1196  return DC;
1197 
1198  // A C++ inline method/friend is parsed *after* the topmost class
1199  // it was declared in is fully parsed ("complete"); the topmost
1200  // class is the context we need to return to.
1201  while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202  DC = RD;
1203 
1204  // Return the declaration context of the topmost class the inline method is
1205  // declared in.
1206  return DC;
1207  }
1208 
1209  return DC->getLexicalParent();
1210 }
1211 
1213  assert(getContainingDC(DC) == CurContext &&
1214  "The next DeclContext should be lexically contained in the current one.");
1215  CurContext = DC;
1216  S->setEntity(DC);
1217 }
1218 
1220  assert(CurContext && "DeclContext imbalance!");
1221 
1222  CurContext = getContainingDC(CurContext);
1223  assert(CurContext && "Popped translation unit!");
1224 }
1225 
1227  Decl *D) {
1228  // Unlike PushDeclContext, the context to which we return is not necessarily
1229  // the containing DC of TD, because the new context will be some pre-existing
1230  // TagDecl definition instead of a fresh one.
1231  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232  CurContext = cast<TagDecl>(D)->getDefinition();
1233  assert(CurContext && "skipping definition of undefined tag");
1234  // Start lookups from the parent of the current context; we don't want to look
1235  // into the pre-existing complete definition.
1236  S->setEntity(CurContext->getLookupParent());
1237  return Result;
1238 }
1239 
1241  CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1248  // C++0x [basic.lookup.unqual]p13:
1249  // A name used in the definition of a static data member of class
1250  // X (after the qualified-id of the static member) is looked up as
1251  // if the name was used in a member function of X.
1252  // C++0x [basic.lookup.unqual]p14:
1253  // If a variable member of a namespace is defined outside of the
1254  // scope of its namespace then any name used in the definition of
1255  // the variable member (after the declarator-id) is looked up as
1256  // if the definition of the variable member occurred in its
1257  // namespace.
1258  // Both of these imply that we should push a scope whose context
1259  // is the semantic context of the declaration. We can't use
1260  // PushDeclContext here because that context is not necessarily
1261  // lexically contained in the current context. Fortunately,
1262  // the containing scope should have the appropriate information.
1263 
1264  assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267  Scope *Ancestor = S->getParent();
1268  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272  CurContext = DC;
1273  S->setEntity(DC);
1274 }
1275 
1277  assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279  // Switch back to the lexical context. The safety of this is
1280  // enforced by an assert in EnterDeclaratorContext.
1281  Scope *Ancestor = S->getParent();
1282  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283  CurContext = Ancestor->getEntity();
1284 
1285  // We don't need to do anything with the scope, which is going to
1286  // disappear.
1287 }
1288 
1290  // We assume that the caller has already called
1291  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292  FunctionDecl *FD = D->getAsFunction();
1293  if (!FD)
1294  return;
1295 
1296  // Same implementation as PushDeclContext, but enters the context
1297  // from the lexical parent, rather than the top-level class.
1298  assert(CurContext == FD->getLexicalParent() &&
1299  "The next DeclContext should be lexically contained in the current one.");
1300  CurContext = FD;
1301  S->setEntity(CurContext);
1302 
1303  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304  ParmVarDecl *Param = FD->getParamDecl(P);
1305  // If the parameter has an identifier, then add it to the scope
1306  if (Param->getIdentifier()) {
1307  S->AddDecl(Param);
1308  IdResolver.AddDecl(Param);
1309  }
1310  }
1311 }
1312 
1314  // Same implementation as PopDeclContext, but returns to the lexical parent,
1315  // rather than the top-level class.
1316  assert(CurContext && "DeclContext imbalance!");
1317  CurContext = CurContext->getLexicalParent();
1318  assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1331  ASTContext &Context,
1332  const FunctionDecl *New) {
1333  if (Context.getLangOpts().CPlusPlus)
1334  return true;
1335 
1336  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337  return true;
1338 
1339  return Previous.getResultKind() == LookupResult::Found &&
1340  (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341  New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346  // Move up the scope chain until we find the nearest enclosing
1347  // non-transparent context. The declaration will be introduced into this
1348  // scope.
1349  while (S->getEntity() && S->getEntity()->isTransparentContext())
1350  S = S->getParent();
1351 
1352  // Add scoped declarations into their context, so that they can be
1353  // found later. Declarations without a context won't be inserted
1354  // into any context.
1355  if (AddToContext)
1356  CurContext->addDecl(D);
1357 
1358  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359  // are function-local declarations.
1360  if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1364  return;
1365 
1366  // Template instantiations should also not be pushed into scope.
1367  if (isa<FunctionDecl>(D) &&
1368  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369  return;
1370 
1371  // If this replaces anything in the current scope,
1372  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373  IEnd = IdResolver.end();
1374  for (; I != IEnd; ++I) {
1375  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376  S->RemoveDecl(*I);
1377  IdResolver.RemoveDecl(*I);
1378 
1379  // Should only need to replace one decl.
1380  break;
1381  }
1382  }
1383 
1384  S->AddDecl(D);
1385 
1386  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387  // Implicitly-generated labels may end up getting generated in an order that
1388  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389  // the label at the appropriate place in the identifier chain.
1390  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392  if (IDC == CurContext) {
1393  if (!S->isDeclScope(*I))
1394  continue;
1395  } else if (IDC->Encloses(CurContext))
1396  break;
1397  }
1398 
1399  IdResolver.InsertDeclAfter(I, D);
1400  } else {
1401  IdResolver.AddDecl(D);
1402  }
1403 }
1404 
1406  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407  TUScope->AddDecl(D);
1408 }
1409 
1411  bool AllowInlineNamespace) {
1412  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1416  DeclContext *TargetDC = DC->getPrimaryContext();
1417  do {
1418  if (DeclContext *ScopeDC = S->getEntity())
1419  if (ScopeDC->getPrimaryContext() == TargetDC)
1420  return S;
1421  } while ((S = S->getParent()));
1422 
1423  return nullptr;
1424 }
1425 
1427  DeclContext*,
1428  ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1433  bool ConsiderLinkage,
1434  bool AllowInlineNamespace) {
1436  while (F.hasNext()) {
1437  NamedDecl *D = F.next();
1438 
1439  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440  continue;
1441 
1442  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443  continue;
1444 
1445  F.erase();
1446  }
1447 
1448  F.done();
1449 }
1450 
1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1454  // FIXME: The Modules TS is not clear about how friend declarations are
1455  // to be treated. It's not meaningful to have different owning modules for
1456  // linkage in redeclarations of the same entity, so for now allow the
1457  // redeclaration and change the owning modules to match.
1458  if (New->getFriendObjectKind() &&
1461  makeMergedDefinitionVisible(New);
1462  return false;
1463  }
1464 
1465  Module *NewM = New->getOwningModule();
1466  Module *OldM = Old->getOwningModule();
1467  if (NewM == OldM)
1468  return false;
1469 
1470  // FIXME: Check proclaimed-ownership-declarations here too.
1471  bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472  bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473  if (NewIsModuleInterface || OldIsModuleInterface) {
1474  // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475  // if a declaration of D [...] appears in the purview of a module, all
1476  // other such declarations shall appear in the purview of the same module
1477  Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478  << New
1479  << NewIsModuleInterface
1480  << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481  << OldIsModuleInterface
1482  << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483  Diag(Old->getLocation(), diag::note_previous_declaration);
1484  New->setInvalidDecl();
1485  return true;
1486  }
1487 
1488  return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492  return isa<UsingShadowDecl>(D) ||
1493  isa<UnresolvedUsingTypenameDecl>(D) ||
1494  isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1500  while (F.hasNext())
1501  if (isUsingDecl(F.next()))
1502  F.erase();
1503 
1504  F.done();
1505 }
1506 
1507 /// Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 /// S(const S&); // DO NOT IMPLEMENT
1511 /// void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1515  // FIXME: Should check for private access too but access is set after we get
1516  // the decl here.
1518  return false;
1519 
1520  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521  return CD->isCopyConstructor();
1522  return D->isCopyAssignmentOperator();
1523 }
1524 
1525 // We need this to handle
1526 //
1527 // typedef struct {
1528 // void *foo() { return 0; }
1529 // } A;
1530 //
1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532 // for example. If 'A', foo will have external linkage. If we have '*A',
1533 // foo will have no linkage. Since we can't know until we get to the end
1534 // of the typedef, this function finds out if D might have non-external linkage.
1535 // Callers should verify at the end of the TU if it D has external linkage or
1536 // not.
1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538  const DeclContext *DC = D->getDeclContext();
1539  while (!DC->isTranslationUnit()) {
1540  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541  if (!RD->hasNameForLinkage())
1542  return true;
1543  }
1544  DC = DC->getParent();
1545  }
1546 
1547  return !D->isExternallyVisible();
1548 }
1549 
1550 // FIXME: This needs to be refactored; some other isInMainFile users want
1551 // these semantics.
1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553  if (S.TUKind != TU_Complete)
1554  return false;
1555  return S.SourceMgr.isInMainFile(Loc);
1556 }
1557 
1559  assert(D);
1560 
1561  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562  return false;
1563 
1564  // Ignore all entities declared within templates, and out-of-line definitions
1565  // of members of class templates.
1566  if (D->getDeclContext()->isDependentContext() ||
1568  return false;
1569 
1570  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572  return false;
1573  // A non-out-of-line declaration of a member specialization was implicitly
1574  // instantiated; it's the out-of-line declaration that we're interested in.
1575  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576  FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577  return false;
1578 
1579  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581  return false;
1582  } else {
1583  // 'static inline' functions are defined in headers; don't warn.
1584  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585  return false;
1586  }
1587 
1588  if (FD->doesThisDeclarationHaveABody() &&
1589  Context.DeclMustBeEmitted(FD))
1590  return false;
1591  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592  // Constants and utility variables are defined in headers with internal
1593  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1594  // like "inline".)
1595  if (!isMainFileLoc(*this, VD->getLocation()))
1596  return false;
1597 
1598  if (Context.DeclMustBeEmitted(VD))
1599  return false;
1600 
1601  if (VD->isStaticDataMember() &&
1602  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603  return false;
1604  if (VD->isStaticDataMember() &&
1605  VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606  VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607  return false;
1608 
1609  if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610  return false;
1611  } else {
1612  return false;
1613  }
1614 
1615  // Only warn for unused decls internal to the translation unit.
1616  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617  // for inline functions defined in the main source file, for instance.
1618  return mightHaveNonExternalLinkage(D);
1619 }
1620 
1622  if (!D)
1623  return;
1624 
1625  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626  const FunctionDecl *First = FD->getFirstDecl();
1627  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628  return; // First should already be in the vector.
1629  }
1630 
1631  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632  const VarDecl *First = VD->getFirstDecl();
1633  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634  return; // First should already be in the vector.
1635  }
1636 
1637  if (ShouldWarnIfUnusedFileScopedDecl(D))
1638  UnusedFileScopedDecls.push_back(D);
1639 }
1640 
1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642  if (D->isInvalidDecl())
1643  return false;
1644 
1645  bool Referenced = false;
1646  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647  // For a decomposition declaration, warn if none of the bindings are
1648  // referenced, instead of if the variable itself is referenced (which
1649  // it is, by the bindings' expressions).
1650  for (auto *BD : DD->bindings()) {
1651  if (BD->isReferenced()) {
1652  Referenced = true;
1653  break;
1654  }
1655  }
1656  } else if (!D->getDeclName()) {
1657  return false;
1658  } else if (D->isReferenced() || D->isUsed()) {
1659  Referenced = true;
1660  }
1661 
1662  if (Referenced || D->hasAttr<UnusedAttr>() ||
1663  D->hasAttr<ObjCPreciseLifetimeAttr>())
1664  return false;
1665 
1666  if (isa<LabelDecl>(D))
1667  return true;
1668 
1669  // Except for labels, we only care about unused decls that are local to
1670  // functions.
1671  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673  // For dependent types, the diagnostic is deferred.
1674  WithinFunction =
1675  WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676  if (!WithinFunction)
1677  return false;
1678 
1679  if (isa<TypedefNameDecl>(D))
1680  return true;
1681 
1682  // White-list anything that isn't a local variable.
1683  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684  return false;
1685 
1686  // Types of valid local variables should be complete, so this should succeed.
1687  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688 
1689  // White-list anything with an __attribute__((unused)) type.
1690  const auto *Ty = VD->getType().getTypePtr();
1691 
1692  // Only look at the outermost level of typedef.
1693  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694  if (TT->getDecl()->hasAttr<UnusedAttr>())
1695  return false;
1696  }
1697 
1698  // If we failed to complete the type for some reason, or if the type is
1699  // dependent, don't diagnose the variable.
1700  if (Ty->isIncompleteType() || Ty->isDependentType())
1701  return false;
1702 
1703  // Look at the element type to ensure that the warning behaviour is
1704  // consistent for both scalars and arrays.
1705  Ty = Ty->getBaseElementTypeUnsafe();
1706 
1707  if (const TagType *TT = Ty->getAs<TagType>()) {
1708  const TagDecl *Tag = TT->getDecl();
1709  if (Tag->hasAttr<UnusedAttr>())
1710  return false;
1711 
1712  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714  return false;
1715 
1716  if (const Expr *Init = VD->getInit()) {
1717  if (const ExprWithCleanups *Cleanups =
1718  dyn_cast<ExprWithCleanups>(Init))
1719  Init = Cleanups->getSubExpr();
1720  const CXXConstructExpr *Construct =
1721  dyn_cast<CXXConstructExpr>(Init);
1722  if (Construct && !Construct->isElidable()) {
1723  CXXConstructorDecl *CD = Construct->getConstructor();
1724  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726  return false;
1727  }
1728  }
1729  }
1730  }
1731 
1732  // TODO: __attribute__((unused)) templates?
1733  }
1734 
1735  return true;
1736 }
1737 
1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739  FixItHint &Hint) {
1740  if (isa<LabelDecl>(D)) {
1742  D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1743  true);
1744  if (AfterColon.isInvalid())
1745  return;
1746  Hint = FixItHint::CreateRemoval(
1747  CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1748  }
1749 }
1750 
1752  if (D->getTypeForDecl()->isDependentType())
1753  return;
1754 
1755  for (auto *TmpD : D->decls()) {
1756  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1757  DiagnoseUnusedDecl(T);
1758  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1759  DiagnoseUnusedNestedTypedefs(R);
1760  }
1761 }
1762 
1763 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1764 /// unless they are marked attr(unused).
1766  if (!ShouldDiagnoseUnusedDecl(D))
1767  return;
1768 
1769  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1770  // typedefs can be referenced later on, so the diagnostics are emitted
1771  // at end-of-translation-unit.
1772  UnusedLocalTypedefNameCandidates.insert(TD);
1773  return;
1774  }
1775 
1776  FixItHint Hint;
1777  GenerateFixForUnusedDecl(D, Context, Hint);
1778 
1779  unsigned DiagID;
1780  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1781  DiagID = diag::warn_unused_exception_param;
1782  else if (isa<LabelDecl>(D))
1783  DiagID = diag::warn_unused_label;
1784  else
1785  DiagID = diag::warn_unused_variable;
1786 
1787  Diag(D->getLocation(), DiagID) << D << Hint;
1788 }
1789 
1790 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1791  // Verify that we have no forward references left. If so, there was a goto
1792  // or address of a label taken, but no definition of it. Label fwd
1793  // definitions are indicated with a null substmt which is also not a resolved
1794  // MS inline assembly label name.
1795  bool Diagnose = false;
1796  if (L->isMSAsmLabel())
1797  Diagnose = !L->isResolvedMSAsmLabel();
1798  else
1799  Diagnose = L->getStmt() == nullptr;
1800  if (Diagnose)
1801  S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1802 }
1803 
1805  S->mergeNRVOIntoParent();
1806 
1807  if (S->decl_empty()) return;
1808  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1809  "Scope shouldn't contain decls!");
1810 
1811  for (auto *TmpD : S->decls()) {
1812  assert(TmpD && "This decl didn't get pushed??");
1813 
1814  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1815  NamedDecl *D = cast<NamedDecl>(TmpD);
1816 
1817  // Diagnose unused variables in this scope.
1818  if (!S->hasUnrecoverableErrorOccurred()) {
1819  DiagnoseUnusedDecl(D);
1820  if (const auto *RD = dyn_cast<RecordDecl>(D))
1821  DiagnoseUnusedNestedTypedefs(RD);
1822  }
1823 
1824  if (!D->getDeclName()) continue;
1825 
1826  // If this was a forward reference to a label, verify it was defined.
1827  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1828  CheckPoppedLabel(LD, *this);
1829 
1830  // Remove this name from our lexical scope, and warn on it if we haven't
1831  // already.
1832  IdResolver.RemoveDecl(D);
1833  auto ShadowI = ShadowingDecls.find(D);
1834  if (ShadowI != ShadowingDecls.end()) {
1835  if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1836  Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1837  << D << FD << FD->getParent();
1838  Diag(FD->getLocation(), diag::note_previous_declaration);
1839  }
1840  ShadowingDecls.erase(ShadowI);
1841  }
1842  }
1843 }
1844 
1845 /// Look for an Objective-C class in the translation unit.
1846 ///
1847 /// \param Id The name of the Objective-C class we're looking for. If
1848 /// typo-correction fixes this name, the Id will be updated
1849 /// to the fixed name.
1850 ///
1851 /// \param IdLoc The location of the name in the translation unit.
1852 ///
1853 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1854 /// if there is no class with the given name.
1855 ///
1856 /// \returns The declaration of the named Objective-C class, or NULL if the
1857 /// class could not be found.
1859  SourceLocation IdLoc,
1860  bool DoTypoCorrection) {
1861  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1862  // creation from this context.
1863  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1864 
1865  if (!IDecl && DoTypoCorrection) {
1866  // Perform typo correction at the given location, but only if we
1867  // find an Objective-C class name.
1868  if (TypoCorrection C = CorrectTypo(
1869  DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1870  llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1871  CTK_ErrorRecovery)) {
1872  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1873  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1874  Id = IDecl->getIdentifier();
1875  }
1876  }
1877  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1878  // This routine must always return a class definition, if any.
1879  if (Def && Def->getDefinition())
1880  Def = Def->getDefinition();
1881  return Def;
1882 }
1883 
1884 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1885 /// from S, where a non-field would be declared. This routine copes
1886 /// with the difference between C and C++ scoping rules in structs and
1887 /// unions. For example, the following code is well-formed in C but
1888 /// ill-formed in C++:
1889 /// @code
1890 /// struct S6 {
1891 /// enum { BAR } e;
1892 /// };
1893 ///
1894 /// void test_S6() {
1895 /// struct S6 a;
1896 /// a.e = BAR;
1897 /// }
1898 /// @endcode
1899 /// For the declaration of BAR, this routine will return a different
1900 /// scope. The scope S will be the scope of the unnamed enumeration
1901 /// within S6. In C++, this routine will return the scope associated
1902 /// with S6, because the enumeration's scope is a transparent
1903 /// context but structures can contain non-field names. In C, this
1904 /// routine will return the translation unit scope, since the
1905 /// enumeration's scope is a transparent context and structures cannot
1906 /// contain non-field names.
1908  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1909  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1910  (S->isClassScope() && !getLangOpts().CPlusPlus))
1911  S = S->getParent();
1912  return S;
1913 }
1914 
1915 /// Looks up the declaration of "struct objc_super" and
1916 /// saves it for later use in building builtin declaration of
1917 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1918 /// pre-existing declaration exists no action takes place.
1919 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1920  IdentifierInfo *II) {
1921  if (!II->isStr("objc_msgSendSuper"))
1922  return;
1923  ASTContext &Context = ThisSema.Context;
1924 
1925  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1927  ThisSema.LookupName(Result, S);
1928  if (Result.getResultKind() == LookupResult::Found)
1929  if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1930  Context.setObjCSuperType(Context.getTagDeclType(TD));
1931 }
1932 
1933 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1935  switch (Error) {
1936  case ASTContext::GE_None:
1937  return "";
1939  return BuiltinInfo.getHeaderName(ID);
1941  return "stdio.h";
1943  return "setjmp.h";
1945  return "ucontext.h";
1946  }
1947  llvm_unreachable("unhandled error kind");
1948 }
1949 
1950 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1951 /// file scope. lazily create a decl for it. ForRedeclaration is true
1952 /// if we're creating this built-in in anticipation of redeclaring the
1953 /// built-in.
1955  Scope *S, bool ForRedeclaration,
1956  SourceLocation Loc) {
1957  LookupPredefedObjCSuperType(*this, S, II);
1958 
1960  QualType R = Context.GetBuiltinType(ID, Error);
1961  if (Error) {
1962  if (ForRedeclaration)
1963  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1964  << getHeaderName(Context.BuiltinInfo, ID, Error)
1965  << Context.BuiltinInfo.getName(ID);
1966  return nullptr;
1967  }
1968 
1969  if (!ForRedeclaration &&
1970  (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1971  Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1972  Diag(Loc, diag::ext_implicit_lib_function_decl)
1973  << Context.BuiltinInfo.getName(ID) << R;
1974  if (Context.BuiltinInfo.getHeaderName(ID) &&
1975  !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1976  Diag(Loc, diag::note_include_header_or_declare)
1977  << Context.BuiltinInfo.getHeaderName(ID)
1978  << Context.BuiltinInfo.getName(ID);
1979  }
1980 
1981  if (R.isNull())
1982  return nullptr;
1983 
1985  if (getLangOpts().CPlusPlus) {
1986  LinkageSpecDecl *CLinkageDecl =
1987  LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1988  LinkageSpecDecl::lang_c, false);
1989  CLinkageDecl->setImplicit();
1990  Parent->addDecl(CLinkageDecl);
1991  Parent = CLinkageDecl;
1992  }
1993 
1994  FunctionDecl *New = FunctionDecl::Create(Context,
1995  Parent,
1996  Loc, Loc, II, R, /*TInfo=*/nullptr,
1997  SC_Extern,
1998  false,
1999  R->isFunctionProtoType());
2000  New->setImplicit();
2001 
2002  // Create Decl objects for each parameter, adding them to the
2003  // FunctionDecl.
2004  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2006  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2007  ParmVarDecl *parm =
2009  nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2010  SC_None, nullptr);
2011  parm->setScopeInfo(0, i);
2012  Params.push_back(parm);
2013  }
2014  New->setParams(Params);
2015  }
2016 
2017  AddKnownFunctionAttributes(New);
2018  RegisterLocallyScopedExternCDecl(New, S);
2019 
2020  // TUScope is the translation-unit scope to insert this function into.
2021  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2022  // relate Scopes to DeclContexts, and probably eliminate CurContext
2023  // entirely, but we're not there yet.
2024  DeclContext *SavedContext = CurContext;
2025  CurContext = Parent;
2026  PushOnScopeChains(New, TUScope);
2027  CurContext = SavedContext;
2028  return New;
2029 }
2030 
2031 /// Typedef declarations don't have linkage, but they still denote the same
2032 /// entity if their types are the same.
2033 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2034 /// isSameEntity.
2038  // This is only interesting when modules are enabled.
2039  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2040  return;
2041 
2042  // Empty sets are uninteresting.
2043  if (Previous.empty())
2044  return;
2045 
2046  LookupResult::Filter Filter = Previous.makeFilter();
2047  while (Filter.hasNext()) {
2048  NamedDecl *Old = Filter.next();
2049 
2050  // Non-hidden declarations are never ignored.
2051  if (S.isVisible(Old))
2052  continue;
2053 
2054  // Declarations of the same entity are not ignored, even if they have
2055  // different linkages.
2056  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2057  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2058  Decl->getUnderlyingType()))
2059  continue;
2060 
2061  // If both declarations give a tag declaration a typedef name for linkage
2062  // purposes, then they declare the same entity.
2063  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2065  continue;
2066  }
2067 
2068  Filter.erase();
2069  }
2070 
2071  Filter.done();
2072 }
2073 
2075  QualType OldType;
2076  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2077  OldType = OldTypedef->getUnderlyingType();
2078  else
2079  OldType = Context.getTypeDeclType(Old);
2080  QualType NewType = New->getUnderlyingType();
2081 
2082  if (NewType->isVariablyModifiedType()) {
2083  // Must not redefine a typedef with a variably-modified type.
2084  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2085  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2086  << Kind << NewType;
2087  if (Old->getLocation().isValid())
2088  notePreviousDefinition(Old, New->getLocation());
2089  New->setInvalidDecl();
2090  return true;
2091  }
2092 
2093  if (OldType != NewType &&
2094  !OldType->isDependentType() &&
2095  !NewType->isDependentType() &&
2096  !Context.hasSameType(OldType, NewType)) {
2097  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2098  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2099  << Kind << NewType << OldType;
2100  if (Old->getLocation().isValid())
2101  notePreviousDefinition(Old, New->getLocation());
2102  New->setInvalidDecl();
2103  return true;
2104  }
2105  return false;
2106 }
2107 
2108 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2109 /// same name and scope as a previous declaration 'Old'. Figure out
2110 /// how to resolve this situation, merging decls or emitting
2111 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2112 ///
2114  LookupResult &OldDecls) {
2115  // If the new decl is known invalid already, don't bother doing any
2116  // merging checks.
2117  if (New->isInvalidDecl()) return;
2118 
2119  // Allow multiple definitions for ObjC built-in typedefs.
2120  // FIXME: Verify the underlying types are equivalent!
2121  if (getLangOpts().ObjC) {
2122  const IdentifierInfo *TypeID = New->getIdentifier();
2123  switch (TypeID->getLength()) {
2124  default: break;
2125  case 2:
2126  {
2127  if (!TypeID->isStr("id"))
2128  break;
2129  QualType T = New->getUnderlyingType();
2130  if (!T->isPointerType())
2131  break;
2132  if (!T->isVoidPointerType()) {
2133  QualType PT = T->getAs<PointerType>()->getPointeeType();
2134  if (!PT->isStructureType())
2135  break;
2136  }
2137  Context.setObjCIdRedefinitionType(T);
2138  // Install the built-in type for 'id', ignoring the current definition.
2139  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2140  return;
2141  }
2142  case 5:
2143  if (!TypeID->isStr("Class"))
2144  break;
2146  // Install the built-in type for 'Class', ignoring the current definition.
2147  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2148  return;
2149  case 3:
2150  if (!TypeID->isStr("SEL"))
2151  break;
2153  // Install the built-in type for 'SEL', ignoring the current definition.
2154  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2155  return;
2156  }
2157  // Fall through - the typedef name was not a builtin type.
2158  }
2159 
2160  // Verify the old decl was also a type.
2161  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2162  if (!Old) {
2163  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2164  << New->getDeclName();
2165 
2166  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2167  if (OldD->getLocation().isValid())
2168  notePreviousDefinition(OldD, New->getLocation());
2169 
2170  return New->setInvalidDecl();
2171  }
2172 
2173  // If the old declaration is invalid, just give up here.
2174  if (Old->isInvalidDecl())
2175  return New->setInvalidDecl();
2176 
2177  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2179  auto *NewTag = New->getAnonDeclWithTypedefName();
2180  NamedDecl *Hidden = nullptr;
2181  if (OldTag && NewTag &&
2182  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2183  !hasVisibleDefinition(OldTag, &Hidden)) {
2184  // There is a definition of this tag, but it is not visible. Use it
2185  // instead of our tag.
2186  New->setTypeForDecl(OldTD->getTypeForDecl());
2187  if (OldTD->isModed())
2188  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2189  OldTD->getUnderlyingType());
2190  else
2191  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2192 
2193  // Make the old tag definition visible.
2194  makeMergedDefinitionVisible(Hidden);
2195 
2196  // If this was an unscoped enumeration, yank all of its enumerators
2197  // out of the scope.
2198  if (isa<EnumDecl>(NewTag)) {
2199  Scope *EnumScope = getNonFieldDeclScope(S);
2200  for (auto *D : NewTag->decls()) {
2201  auto *ED = cast<EnumConstantDecl>(D);
2202  assert(EnumScope->isDeclScope(ED));
2203  EnumScope->RemoveDecl(ED);
2204  IdResolver.RemoveDecl(ED);
2205  ED->getLexicalDeclContext()->removeDecl(ED);
2206  }
2207  }
2208  }
2209  }
2210 
2211  // If the typedef types are not identical, reject them in all languages and
2212  // with any extensions enabled.
2213  if (isIncompatibleTypedef(Old, New))
2214  return;
2215 
2216  // The types match. Link up the redeclaration chain and merge attributes if
2217  // the old declaration was a typedef.
2218  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2219  New->setPreviousDecl(Typedef);
2220  mergeDeclAttributes(New, Old);
2221  }
2222 
2223  if (getLangOpts().MicrosoftExt)
2224  return;
2225 
2226  if (getLangOpts().CPlusPlus) {
2227  // C++ [dcl.typedef]p2:
2228  // In a given non-class scope, a typedef specifier can be used to
2229  // redefine the name of any type declared in that scope to refer
2230  // to the type to which it already refers.
2231  if (!isa<CXXRecordDecl>(CurContext))
2232  return;
2233 
2234  // C++0x [dcl.typedef]p4:
2235  // In a given class scope, a typedef specifier can be used to redefine
2236  // any class-name declared in that scope that is not also a typedef-name
2237  // to refer to the type to which it already refers.
2238  //
2239  // This wording came in via DR424, which was a correction to the
2240  // wording in DR56, which accidentally banned code like:
2241  //
2242  // struct S {
2243  // typedef struct A { } A;
2244  // };
2245  //
2246  // in the C++03 standard. We implement the C++0x semantics, which
2247  // allow the above but disallow
2248  //
2249  // struct S {
2250  // typedef int I;
2251  // typedef int I;
2252  // };
2253  //
2254  // since that was the intent of DR56.
2255  if (!isa<TypedefNameDecl>(Old))
2256  return;
2257 
2258  Diag(New->getLocation(), diag::err_redefinition)
2259  << New->getDeclName();
2260  notePreviousDefinition(Old, New->getLocation());
2261  return New->setInvalidDecl();
2262  }
2263 
2264  // Modules always permit redefinition of typedefs, as does C11.
2265  if (getLangOpts().Modules || getLangOpts().C11)
2266  return;
2267 
2268  // If we have a redefinition of a typedef in C, emit a warning. This warning
2269  // is normally mapped to an error, but can be controlled with
2270  // -Wtypedef-redefinition. If either the original or the redefinition is
2271  // in a system header, don't emit this for compatibility with GCC.
2272  if (getDiagnostics().getSuppressSystemWarnings() &&
2273  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2274  (Old->isImplicit() ||
2275  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2276  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2277  return;
2278 
2279  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2280  << New->getDeclName();
2281  notePreviousDefinition(Old, New->getLocation());
2282 }
2283 
2284 /// DeclhasAttr - returns true if decl Declaration already has the target
2285 /// attribute.
2286 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2287  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2288  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2289  for (const auto *i : D->attrs())
2290  if (i->getKind() == A->getKind()) {
2291  if (Ann) {
2292  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2293  return true;
2294  continue;
2295  }
2296  // FIXME: Don't hardcode this check
2297  if (OA && isa<OwnershipAttr>(i))
2298  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2299  return true;
2300  }
2301 
2302  return false;
2303 }
2304 
2306  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2307  return VD->isThisDeclarationADefinition();
2308  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2309  return TD->isCompleteDefinition() || TD->isBeingDefined();
2310  return true;
2311 }
2312 
2313 /// Merge alignment attributes from \p Old to \p New, taking into account the
2314 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2315 ///
2316 /// \return \c true if any attributes were added to \p New.
2317 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2318  // Look for alignas attributes on Old, and pick out whichever attribute
2319  // specifies the strictest alignment requirement.
2320  AlignedAttr *OldAlignasAttr = nullptr;
2321  AlignedAttr *OldStrictestAlignAttr = nullptr;
2322  unsigned OldAlign = 0;
2323  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2324  // FIXME: We have no way of representing inherited dependent alignments
2325  // in a case like:
2326  // template<int A, int B> struct alignas(A) X;
2327  // template<int A, int B> struct alignas(B) X {};
2328  // For now, we just ignore any alignas attributes which are not on the
2329  // definition in such a case.
2330  if (I->isAlignmentDependent())
2331  return false;
2332 
2333  if (I->isAlignas())
2334  OldAlignasAttr = I;
2335 
2336  unsigned Align = I->getAlignment(S.Context);
2337  if (Align > OldAlign) {
2338  OldAlign = Align;
2339  OldStrictestAlignAttr = I;
2340  }
2341  }
2342 
2343  // Look for alignas attributes on New.
2344  AlignedAttr *NewAlignasAttr = nullptr;
2345  unsigned NewAlign = 0;
2346  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2347  if (I->isAlignmentDependent())
2348  return false;
2349 
2350  if (I->isAlignas())
2351  NewAlignasAttr = I;
2352 
2353  unsigned Align = I->getAlignment(S.Context);
2354  if (Align > NewAlign)
2355  NewAlign = Align;
2356  }
2357 
2358  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2359  // Both declarations have 'alignas' attributes. We require them to match.
2360  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2361  // fall short. (If two declarations both have alignas, they must both match
2362  // every definition, and so must match each other if there is a definition.)
2363 
2364  // If either declaration only contains 'alignas(0)' specifiers, then it
2365  // specifies the natural alignment for the type.
2366  if (OldAlign == 0 || NewAlign == 0) {
2367  QualType Ty;
2368  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2369  Ty = VD->getType();
2370  else
2371  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2372 
2373  if (OldAlign == 0)
2374  OldAlign = S.Context.getTypeAlign(Ty);
2375  if (NewAlign == 0)
2376  NewAlign = S.Context.getTypeAlign(Ty);
2377  }
2378 
2379  if (OldAlign != NewAlign) {
2380  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2381  << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2382  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2383  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2384  }
2385  }
2386 
2387  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2388  // C++11 [dcl.align]p6:
2389  // if any declaration of an entity has an alignment-specifier,
2390  // every defining declaration of that entity shall specify an
2391  // equivalent alignment.
2392  // C11 6.7.5/7:
2393  // If the definition of an object does not have an alignment
2394  // specifier, any other declaration of that object shall also
2395  // have no alignment specifier.
2396  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2397  << OldAlignasAttr;
2398  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2399  << OldAlignasAttr;
2400  }
2401 
2402  bool AnyAdded = false;
2403 
2404  // Ensure we have an attribute representing the strictest alignment.
2405  if (OldAlign > NewAlign) {
2406  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2407  Clone->setInherited(true);
2408  New->addAttr(Clone);
2409  AnyAdded = true;
2410  }
2411 
2412  // Ensure we have an alignas attribute if the old declaration had one.
2413  if (OldAlignasAttr && !NewAlignasAttr &&
2414  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2415  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2416  Clone->setInherited(true);
2417  New->addAttr(Clone);
2418  AnyAdded = true;
2419  }
2420 
2421  return AnyAdded;
2422 }
2423 
2424 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2425  const InheritableAttr *Attr,
2427  // This function copies an attribute Attr from a previous declaration to the
2428  // new declaration D if the new declaration doesn't itself have that attribute
2429  // yet or if that attribute allows duplicates.
2430  // If you're adding a new attribute that requires logic different from
2431  // "use explicit attribute on decl if present, else use attribute from
2432  // previous decl", for example if the attribute needs to be consistent
2433  // between redeclarations, you need to call a custom merge function here.
2434  InheritableAttr *NewAttr = nullptr;
2435  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2436  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2437  NewAttr = S.mergeAvailabilityAttr(
2438  D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2439  AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2440  AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2441  AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2442  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2443  NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444  AttrSpellingListIndex);
2445  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2446  NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2447  AttrSpellingListIndex);
2448  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2449  NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2450  AttrSpellingListIndex);
2451  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2452  NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2453  AttrSpellingListIndex);
2454  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2455  NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2456  FA->getFormatIdx(), FA->getFirstArg(),
2457  AttrSpellingListIndex);
2458  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2459  NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2460  AttrSpellingListIndex);
2461  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2462  NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2463  AttrSpellingListIndex);
2464  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2465  NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2466  AttrSpellingListIndex,
2467  IA->getSemanticSpelling());
2468  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2469  NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2470  &S.Context.Idents.get(AA->getSpelling()),
2471  AttrSpellingListIndex);
2472  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2473  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2474  isa<CUDAGlobalAttr>(Attr))) {
2475  // CUDA target attributes are part of function signature for
2476  // overloading purposes and must not be merged.
2477  return false;
2478  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2479  NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2480  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2481  NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2482  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2483  NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2484  else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2485  NewAttr = S.mergeCommonAttr(D, *CommonA);
2486  else if (isa<AlignedAttr>(Attr))
2487  // AlignedAttrs are handled separately, because we need to handle all
2488  // such attributes on a declaration at the same time.
2489  NewAttr = nullptr;
2490  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2491  (AMK == Sema::AMK_Override ||
2493  NewAttr = nullptr;
2494  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2495  NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2496  UA->getGuid());
2497  else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2498  NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2499  else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2500  NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2501  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2502  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2503 
2504  if (NewAttr) {
2505  NewAttr->setInherited(true);
2506  D->addAttr(NewAttr);
2507  if (isa<MSInheritanceAttr>(NewAttr))
2508  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2509  return true;
2510  }
2511 
2512  return false;
2513 }
2514 
2515 static const NamedDecl *getDefinition(const Decl *D) {
2516  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2517  return TD->getDefinition();
2518  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2519  const VarDecl *Def = VD->getDefinition();
2520  if (Def)
2521  return Def;
2522  return VD->getActingDefinition();
2523  }
2524  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2525  return FD->getDefinition();
2526  return nullptr;
2527 }
2528 
2529 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2530  for (const auto *Attribute : D->attrs())
2531  if (Attribute->getKind() == Kind)
2532  return true;
2533  return false;
2534 }
2535 
2536 /// checkNewAttributesAfterDef - If we already have a definition, check that
2537 /// there are no new attributes in this declaration.
2538 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2539  if (!New->hasAttrs())
2540  return;
2541 
2542  const NamedDecl *Def = getDefinition(Old);
2543  if (!Def || Def == New)
2544  return;
2545 
2546  AttrVec &NewAttributes = New->getAttrs();
2547  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2548  const Attr *NewAttribute = NewAttributes[I];
2549 
2550  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2551  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2552  Sema::SkipBodyInfo SkipBody;
2553  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2554 
2555  // If we're skipping this definition, drop the "alias" attribute.
2556  if (SkipBody.ShouldSkip) {
2557  NewAttributes.erase(NewAttributes.begin() + I);
2558  --E;
2559  continue;
2560  }
2561  } else {
2562  VarDecl *VD = cast<VarDecl>(New);
2563  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2565  ? diag::err_alias_after_tentative
2566  : diag::err_redefinition;
2567  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2568  if (Diag == diag::err_redefinition)
2569  S.notePreviousDefinition(Def, VD->getLocation());
2570  else
2571  S.Diag(Def->getLocation(), diag::note_previous_definition);
2572  VD->setInvalidDecl();
2573  }
2574  ++I;
2575  continue;
2576  }
2577 
2578  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2579  // Tentative definitions are only interesting for the alias check above.
2580  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2581  ++I;
2582  continue;
2583  }
2584  }
2585 
2586  if (hasAttribute(Def, NewAttribute->getKind())) {
2587  ++I;
2588  continue; // regular attr merging will take care of validating this.
2589  }
2590 
2591  if (isa<C11NoReturnAttr>(NewAttribute)) {
2592  // C's _Noreturn is allowed to be added to a function after it is defined.
2593  ++I;
2594  continue;
2595  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2596  if (AA->isAlignas()) {
2597  // C++11 [dcl.align]p6:
2598  // if any declaration of an entity has an alignment-specifier,
2599  // every defining declaration of that entity shall specify an
2600  // equivalent alignment.
2601  // C11 6.7.5/7:
2602  // If the definition of an object does not have an alignment
2603  // specifier, any other declaration of that object shall also
2604  // have no alignment specifier.
2605  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2606  << AA;
2607  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2608  << AA;
2609  NewAttributes.erase(NewAttributes.begin() + I);
2610  --E;
2611  continue;
2612  }
2613  }
2614 
2615  S.Diag(NewAttribute->getLocation(),
2616  diag::warn_attribute_precede_definition);
2617  S.Diag(Def->getLocation(), diag::note_previous_definition);
2618  NewAttributes.erase(NewAttributes.begin() + I);
2619  --E;
2620  }
2621 }
2622 
2623 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2625  AvailabilityMergeKind AMK) {
2626  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2627  UsedAttr *NewAttr = OldAttr->clone(Context);
2628  NewAttr->setInherited(true);
2629  New->addAttr(NewAttr);
2630  }
2631 
2632  if (!Old->hasAttrs() && !New->hasAttrs())
2633  return;
2634 
2635  // Attributes declared post-definition are currently ignored.
2636  checkNewAttributesAfterDef(*this, New, Old);
2637 
2638  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2639  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2640  if (OldA->getLabel() != NewA->getLabel()) {
2641  // This redeclaration changes __asm__ label.
2642  Diag(New->getLocation(), diag::err_different_asm_label);
2643  Diag(OldA->getLocation(), diag::note_previous_declaration);
2644  }
2645  } else if (Old->isUsed()) {
2646  // This redeclaration adds an __asm__ label to a declaration that has
2647  // already been ODR-used.
2648  Diag(New->getLocation(), diag::err_late_asm_label_name)
2649  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2650  }
2651  }
2652 
2653  // Re-declaration cannot add abi_tag's.
2654  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2655  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2656  for (const auto &NewTag : NewAbiTagAttr->tags()) {
2657  if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2658  NewTag) == OldAbiTagAttr->tags_end()) {
2659  Diag(NewAbiTagAttr->getLocation(),
2660  diag::err_new_abi_tag_on_redeclaration)
2661  << NewTag;
2662  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2663  }
2664  }
2665  } else {
2666  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2667  Diag(Old->getLocation(), diag::note_previous_declaration);
2668  }
2669  }
2670 
2671  // This redeclaration adds a section attribute.
2672  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2673  if (auto *VD = dyn_cast<VarDecl>(New)) {
2674  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2675  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2676  Diag(Old->getLocation(), diag::note_previous_declaration);
2677  }
2678  }
2679  }
2680 
2681  // Redeclaration adds code-seg attribute.
2682  const auto *NewCSA = New->getAttr<CodeSegAttr>();
2683  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2684  !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2685  Diag(New->getLocation(), diag::warn_mismatched_section)
2686  << 0 /*codeseg*/;
2687  Diag(Old->getLocation(), diag::note_previous_declaration);
2688  }
2689 
2690  if (!Old->hasAttrs())
2691  return;
2692 
2693  bool foundAny = New->hasAttrs();
2694 
2695  // Ensure that any moving of objects within the allocated map is done before
2696  // we process them.
2697  if (!foundAny) New->setAttrs(AttrVec());
2698 
2699  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2700  // Ignore deprecated/unavailable/availability attributes if requested.
2701  AvailabilityMergeKind LocalAMK = AMK_None;
2702  if (isa<DeprecatedAttr>(I) ||
2703  isa<UnavailableAttr>(I) ||
2704  isa<AvailabilityAttr>(I)) {
2705  switch (AMK) {
2706  case AMK_None:
2707  continue;
2708 
2709  case AMK_Redeclaration:
2710  case AMK_Override:
2711  case AMK_ProtocolImplementation:
2712  LocalAMK = AMK;
2713  break;
2714  }
2715  }
2716 
2717  // Already handled.
2718  if (isa<UsedAttr>(I))
2719  continue;
2720 
2721  if (mergeDeclAttribute(*this, New, I, LocalAMK))
2722  foundAny = true;
2723  }
2724 
2725  if (mergeAlignedAttrs(*this, New, Old))
2726  foundAny = true;
2727 
2728  if (!foundAny) New->dropAttrs();
2729 }
2730 
2731 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2732 /// to the new one.
2734  const ParmVarDecl *oldDecl,
2735  Sema &S) {
2736  // C++11 [dcl.attr.depend]p2:
2737  // The first declaration of a function shall specify the
2738  // carries_dependency attribute for its declarator-id if any declaration
2739  // of the function specifies the carries_dependency attribute.
2740  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2741  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2742  S.Diag(CDA->getLocation(),
2743  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2744  // Find the first declaration of the parameter.
2745  // FIXME: Should we build redeclaration chains for function parameters?
2746  const FunctionDecl *FirstFD =
2747  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2748  const ParmVarDecl *FirstVD =
2749  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2750  S.Diag(FirstVD->getLocation(),
2751  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2752  }
2753 
2754  if (!oldDecl->hasAttrs())
2755  return;
2756 
2757  bool foundAny = newDecl->hasAttrs();
2758 
2759  // Ensure that any moving of objects within the allocated map is
2760  // done before we process them.
2761  if (!foundAny) newDecl->setAttrs(AttrVec());
2762 
2763  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2764  if (!DeclHasAttr(newDecl, I)) {
2765  InheritableAttr *newAttr =
2766  cast<InheritableParamAttr>(I->clone(S.Context));
2767  newAttr->setInherited(true);
2768  newDecl->addAttr(newAttr);
2769  foundAny = true;
2770  }
2771  }
2772 
2773  if (!foundAny) newDecl->dropAttrs();
2774 }
2775 
2776 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2777  const ParmVarDecl *OldParam,
2778  Sema &S) {
2779  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2780  if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2781  if (*Oldnullability != *Newnullability) {
2782  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2784  *Newnullability,
2786  != 0))
2788  *Oldnullability,
2790  != 0));
2791  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2792  }
2793  } else {
2794  QualType NewT = NewParam->getType();
2795  NewT = S.Context.getAttributedType(
2796  AttributedType::getNullabilityAttrKind(*Oldnullability),
2797  NewT, NewT);
2798  NewParam->setType(NewT);
2799  }
2800  }
2801 }
2802 
2803 namespace {
2804 
2805 /// Used in MergeFunctionDecl to keep track of function parameters in
2806 /// C.
2807 struct GNUCompatibleParamWarning {
2808  ParmVarDecl *OldParm;
2809  ParmVarDecl *NewParm;
2810  QualType PromotedType;
2811 };
2812 
2813 } // end anonymous namespace
2814 
2815 /// getSpecialMember - get the special member enum for a method.
2817  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2818  if (Ctor->isDefaultConstructor())
2820 
2821  if (Ctor->isCopyConstructor())
2822  return Sema::CXXCopyConstructor;
2823 
2824  if (Ctor->isMoveConstructor())
2825  return Sema::CXXMoveConstructor;
2826  } else if (isa<CXXDestructorDecl>(MD)) {
2827  return Sema::CXXDestructor;
2828  } else if (MD->isCopyAssignmentOperator()) {
2829  return Sema::CXXCopyAssignment;
2830  } else if (MD->isMoveAssignmentOperator()) {
2831  return Sema::CXXMoveAssignment;
2832  }
2833 
2834  return Sema::CXXInvalid;
2835 }
2836 
2837 // Determine whether the previous declaration was a definition, implicit
2838 // declaration, or a declaration.
2839 template <typename T>
2840 static std::pair<diag::kind, SourceLocation>
2841 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2842  diag::kind PrevDiag;
2843  SourceLocation OldLocation = Old->getLocation();
2844  if (Old->isThisDeclarationADefinition())
2845  PrevDiag = diag::note_previous_definition;
2846  else if (Old->isImplicit()) {
2847  PrevDiag = diag::note_previous_implicit_declaration;
2848  if (OldLocation.isInvalid())
2849  OldLocation = New->getLocation();
2850  } else
2851  PrevDiag = diag::note_previous_declaration;
2852  return std::make_pair(PrevDiag, OldLocation);
2853 }
2854 
2855 /// canRedefineFunction - checks if a function can be redefined. Currently,
2856 /// only extern inline functions can be redefined, and even then only in
2857 /// GNU89 mode.
2858 static bool canRedefineFunction(const FunctionDecl *FD,
2859  const LangOptions& LangOpts) {
2860  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2861  !LangOpts.CPlusPlus &&
2862  FD->isInlineSpecified() &&
2863  FD->getStorageClass() == SC_Extern);
2864 }
2865 
2867  const AttributedType *AT = T->getAs<AttributedType>();
2868  while (AT && !AT->isCallingConv())
2869  AT = AT->getModifiedType()->getAs<AttributedType>();
2870  return AT;
2871 }
2872 
2873 template <typename T>
2874 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2875  const DeclContext *DC = Old->getDeclContext();
2876  if (DC->isRecord())
2877  return false;
2878 
2879  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2880  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2881  return true;
2882  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2883  return true;
2884  return false;
2885 }
2886 
2887 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2888 static bool isExternC(VarTemplateDecl *) { return false; }
2889 
2890 /// Check whether a redeclaration of an entity introduced by a
2891 /// using-declaration is valid, given that we know it's not an overload
2892 /// (nor a hidden tag declaration).
2893 template<typename ExpectedDecl>
2895  ExpectedDecl *New) {
2896  // C++11 [basic.scope.declarative]p4:
2897  // Given a set of declarations in a single declarative region, each of
2898  // which specifies the same unqualified name,
2899  // -- they shall all refer to the same entity, or all refer to functions
2900  // and function templates; or
2901  // -- exactly one declaration shall declare a class name or enumeration
2902  // name that is not a typedef name and the other declarations shall all
2903  // refer to the same variable or enumerator, or all refer to functions
2904  // and function templates; in this case the class name or enumeration
2905  // name is hidden (3.3.10).
2906 
2907  // C++11 [namespace.udecl]p14:
2908  // If a function declaration in namespace scope or block scope has the
2909  // same name and the same parameter-type-list as a function introduced
2910  // by a using-declaration, and the declarations do not declare the same
2911  // function, the program is ill-formed.
2912 
2913  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2914  if (Old &&
2915  !Old->getDeclContext()->getRedeclContext()->Equals(
2916  New->getDeclContext()->getRedeclContext()) &&
2917  !(isExternC(Old) && isExternC(New)))
2918  Old = nullptr;
2919 
2920  if (!Old) {
2921  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2922  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2923  S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2924  return true;
2925  }
2926  return false;
2927 }
2928 
2930  const FunctionDecl *B) {
2931  assert(A->getNumParams() == B->getNumParams());
2932 
2933  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2934  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2935  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2936  if (AttrA == AttrB)
2937  return true;
2938  return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2939  };
2940 
2941  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2942 }
2943 
2944 /// If necessary, adjust the semantic declaration context for a qualified
2945 /// declaration to name the correct inline namespace within the qualifier.
2947  DeclaratorDecl *OldD) {
2948  // The only case where we need to update the DeclContext is when
2949  // redeclaration lookup for a qualified name finds a declaration
2950  // in an inline namespace within the context named by the qualifier:
2951  //
2952  // inline namespace N { int f(); }
2953  // int ::f(); // Sema DC needs adjusting from :: to N::.
2954  //
2955  // For unqualified declarations, the semantic context *can* change
2956  // along the redeclaration chain (for local extern declarations,
2957  // extern "C" declarations, and friend declarations in particular).
2958  if (!NewD->getQualifier())
2959  return;
2960 
2961  // NewD is probably already in the right context.
2962  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2963  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2964  if (NamedDC->Equals(SemaDC))
2965  return;
2966 
2967  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2968  NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2969  "unexpected context for redeclaration");
2970 
2971  auto *LexDC = NewD->getLexicalDeclContext();
2972  auto FixSemaDC = [=](NamedDecl *D) {
2973  if (!D)
2974  return;
2975  D->setDeclContext(SemaDC);
2976  D->setLexicalDeclContext(LexDC);
2977  };
2978 
2979  FixSemaDC(NewD);
2980  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2981  FixSemaDC(FD->getDescribedFunctionTemplate());
2982  else if (auto *VD = dyn_cast<VarDecl>(NewD))
2983  FixSemaDC(VD->getDescribedVarTemplate());
2984 }
2985 
2986 /// MergeFunctionDecl - We just parsed a function 'New' from
2987 /// declarator D which has the same name and scope as a previous
2988 /// declaration 'Old'. Figure out how to resolve this situation,
2989 /// merging decls or emitting diagnostics as appropriate.
2990 ///
2991 /// In C++, New and Old must be declarations that are not
2992 /// overloaded. Use IsOverload to determine whether New and Old are
2993 /// overloaded, and to select the Old declaration that New should be
2994 /// merged with.
2995 ///
2996 /// Returns true if there was an error, false otherwise.
2998  Scope *S, bool MergeTypeWithOld) {
2999  // Verify the old decl was also a function.
3000  FunctionDecl *Old = OldD->getAsFunction();
3001  if (!Old) {
3002  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3003  if (New->getFriendObjectKind()) {
3004  Diag(New->getLocation(), diag::err_using_decl_friend);
3005  Diag(Shadow->getTargetDecl()->getLocation(),
3006  diag::note_using_decl_target);
3007  Diag(Shadow->getUsingDecl()->getLocation(),
3008  diag::note_using_decl) << 0;
3009  return true;
3010  }
3011 
3012  // Check whether the two declarations might declare the same function.
3013  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3014  return true;
3015  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3016  } else {
3017  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3018  << New->getDeclName();
3019  notePreviousDefinition(OldD, New->getLocation());
3020  return true;
3021  }
3022  }
3023 
3024  // If the old declaration is invalid, just give up here.
3025  if (Old->isInvalidDecl())
3026  return true;
3027 
3028  // Disallow redeclaration of some builtins.
3029  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3030  Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3031  Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3032  << Old << Old->getType();
3033  return true;
3034  }
3035 
3036  diag::kind PrevDiag;
3037  SourceLocation OldLocation;
3038  std::tie(PrevDiag, OldLocation) =
3040 
3041  // Don't complain about this if we're in GNU89 mode and the old function
3042  // is an extern inline function.
3043  // Don't complain about specializations. They are not supposed to have
3044  // storage classes.
3045  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3046  New->getStorageClass() == SC_Static &&
3047  Old->hasExternalFormalLinkage() &&
3049  !canRedefineFunction(Old, getLangOpts())) {
3050  if (getLangOpts().MicrosoftExt) {
3051  Diag(New->getLocation(), diag::ext_static_non_static) << New;
3052  Diag(OldLocation, PrevDiag);
3053  } else {
3054  Diag(New->getLocation(), diag::err_static_non_static) << New;
3055  Diag(OldLocation, PrevDiag);
3056  return true;
3057  }
3058  }
3059 
3060  if (New->hasAttr<InternalLinkageAttr>() &&
3061  !Old->hasAttr<InternalLinkageAttr>()) {
3062  Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3063  << New->getDeclName();
3064  notePreviousDefinition(Old, New->getLocation());
3065  New->dropAttr<InternalLinkageAttr>();
3066  }
3067 
3068  if (CheckRedeclarationModuleOwnership(New, Old))
3069  return true;
3070 
3071  if (!getLangOpts().CPlusPlus) {
3072  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3073  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3074  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3075  << New << OldOvl;
3076 
3077  // Try our best to find a decl that actually has the overloadable
3078  // attribute for the note. In most cases (e.g. programs with only one
3079  // broken declaration/definition), this won't matter.
3080  //
3081  // FIXME: We could do this if we juggled some extra state in
3082  // OverloadableAttr, rather than just removing it.
3083  const Decl *DiagOld = Old;
3084  if (OldOvl) {
3085  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3086  const auto *A = D->getAttr<OverloadableAttr>();
3087  return A && !A->isImplicit();
3088  });
3089  // If we've implicitly added *all* of the overloadable attrs to this
3090  // chain, emitting a "previous redecl" note is pointless.
3091  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3092  }
3093 
3094  if (DiagOld)
3095  Diag(DiagOld->getLocation(),
3096  diag::note_attribute_overloadable_prev_overload)
3097  << OldOvl;
3098 
3099  if (OldOvl)
3100  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3101  else
3102  New->dropAttr<OverloadableAttr>();
3103  }
3104  }
3105 
3106  // If a function is first declared with a calling convention, but is later
3107  // declared or defined without one, all following decls assume the calling
3108  // convention of the first.
3109  //
3110  // It's OK if a function is first declared without a calling convention,
3111  // but is later declared or defined with the default calling convention.
3112  //
3113  // To test if either decl has an explicit calling convention, we look for
3114  // AttributedType sugar nodes on the type as written. If they are missing or
3115  // were canonicalized away, we assume the calling convention was implicit.
3116  //
3117  // Note also that we DO NOT return at this point, because we still have
3118  // other tests to run.
3119  QualType OldQType = Context.getCanonicalType(Old->getType());
3120  QualType NewQType = Context.getCanonicalType(New->getType());
3121  const FunctionType *OldType = cast<FunctionType>(OldQType);
3122  const FunctionType *NewType = cast<FunctionType>(NewQType);
3123  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3124  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3125  bool RequiresAdjustment = false;
3126 
3127  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3128  FunctionDecl *First = Old->getFirstDecl();
3129  const FunctionType *FT =
3131  FunctionType::ExtInfo FI = FT->getExtInfo();
3132  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3133  if (!NewCCExplicit) {
3134  // Inherit the CC from the previous declaration if it was specified
3135  // there but not here.
3136  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3137  RequiresAdjustment = true;
3138  } else {
3139  // Calling conventions aren't compatible, so complain.
3140  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3141  Diag(New->getLocation(), diag::err_cconv_change)
3142  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3143  << !FirstCCExplicit
3144  << (!FirstCCExplicit ? "" :
3145  FunctionType::getNameForCallConv(FI.getCC()));
3146 
3147  // Put the note on the first decl, since it is the one that matters.
3148  Diag(First->getLocation(), diag::note_previous_declaration);
3149  return true;
3150  }
3151  }
3152 
3153  // FIXME: diagnose the other way around?
3154  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3155  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3156  RequiresAdjustment = true;
3157  }
3158 
3159  // Merge regparm attribute.
3160  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3161  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3162  if (NewTypeInfo.getHasRegParm()) {
3163  Diag(New->getLocation(), diag::err_regparm_mismatch)
3164  << NewType->getRegParmType()
3165  << OldType->getRegParmType();
3166  Diag(OldLocation, diag::note_previous_declaration);
3167  return true;
3168  }
3169 
3170  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3171  RequiresAdjustment = true;
3172  }
3173 
3174  // Merge ns_returns_retained attribute.
3175  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3176  if (NewTypeInfo.getProducesResult()) {
3177  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3178  << "'ns_returns_retained'";
3179  Diag(OldLocation, diag::note_previous_declaration);
3180  return true;
3181  }
3182 
3183  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3184  RequiresAdjustment = true;
3185  }
3186 
3187  if (OldTypeInfo.getNoCallerSavedRegs() !=
3188  NewTypeInfo.getNoCallerSavedRegs()) {
3189  if (NewTypeInfo.getNoCallerSavedRegs()) {
3190  AnyX86NoCallerSavedRegistersAttr *Attr =
3191  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3192  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3193  Diag(OldLocation, diag::note_previous_declaration);
3194  return true;
3195  }
3196 
3197  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3198  RequiresAdjustment = true;
3199  }
3200 
3201  if (RequiresAdjustment) {
3202  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3203  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3204  New->setType(QualType(AdjustedType, 0));
3205  NewQType = Context.getCanonicalType(New->getType());
3206  NewType = cast<FunctionType>(NewQType);
3207  }
3208 
3209  // If this redeclaration makes the function inline, we may need to add it to
3210  // UndefinedButUsed.
3211  if (!Old->isInlined() && New->isInlined() &&
3212  !New->hasAttr<GNUInlineAttr>() &&
3213  !getLangOpts().GNUInline &&
3214  Old->isUsed(false) &&
3215  !Old->isDefined() && !New->isThisDeclarationADefinition())
3216  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3217  SourceLocation()));
3218 
3219  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3220  // about it.
3221  if (New->hasAttr<GNUInlineAttr>() &&
3222  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3223  UndefinedButUsed.erase(Old->getCanonicalDecl());
3224  }
3225 
3226  // If pass_object_size params don't match up perfectly, this isn't a valid
3227  // redeclaration.
3228  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3229  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3230  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3231  << New->getDeclName();
3232  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3233  return true;
3234  }
3235 
3236  if (getLangOpts().CPlusPlus) {
3237  // C++1z [over.load]p2
3238  // Certain function declarations cannot be overloaded:
3239  // -- Function declarations that differ only in the return type,
3240  // the exception specification, or both cannot be overloaded.
3241 
3242  // Check the exception specifications match. This may recompute the type of
3243  // both Old and New if it resolved exception specifications, so grab the
3244  // types again after this. Because this updates the type, we do this before
3245  // any of the other checks below, which may update the "de facto" NewQType
3246  // but do not necessarily update the type of New.
3247  if (CheckEquivalentExceptionSpec(Old, New))
3248  return true;
3249  OldQType = Context.getCanonicalType(Old->getType());
3250  NewQType = Context.getCanonicalType(New->getType());
3251 
3252  // Go back to the type source info to compare the declared return types,
3253  // per C++1y [dcl.type.auto]p13:
3254  // Redeclarations or specializations of a function or function template
3255  // with a declared return type that uses a placeholder type shall also
3256  // use that placeholder, not a deduced type.
3257  QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3258  QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3259  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3260  canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3261  OldDeclaredReturnType)) {
3262  QualType ResQT;
3263  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3264  OldDeclaredReturnType->isObjCObjectPointerType())
3265  // FIXME: This does the wrong thing for a deduced return type.
3266  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3267  if (ResQT.isNull()) {
3268  if (New->isCXXClassMember() && New->isOutOfLine())
3269  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3270  << New << New->getReturnTypeSourceRange();
3271  else
3272  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3273  << New->getReturnTypeSourceRange();
3274  Diag(OldLocation, PrevDiag) << Old << Old->getType()
3275  << Old->getReturnTypeSourceRange();
3276  return true;
3277  }
3278  else
3279  NewQType = ResQT;
3280  }
3281 
3282  QualType OldReturnType = OldType->getReturnType();
3283  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3284  if (OldReturnType != NewReturnType) {
3285  // If this function has a deduced return type and has already been
3286  // defined, copy the deduced value from the old declaration.
3287  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3288  if (OldAT && OldAT->isDeduced()) {
3289  New->setType(
3290  SubstAutoType(New->getType(),
3291  OldAT->isDependentType() ? Context.DependentTy
3292  : OldAT->getDeducedType()));
3293  NewQType = Context.getCanonicalType(
3294  SubstAutoType(NewQType,
3295  OldAT->isDependentType() ? Context.DependentTy
3296  : OldAT->getDeducedType()));
3297  }
3298  }
3299 
3300  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3301  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3302  if (OldMethod && NewMethod) {
3303  // Preserve triviality.
3304  NewMethod->setTrivial(OldMethod->isTrivial());
3305 
3306  // MSVC allows explicit template specialization at class scope:
3307  // 2 CXXMethodDecls referring to the same function will be injected.
3308  // We don't want a redeclaration error.
3309  bool IsClassScopeExplicitSpecialization =
3310  OldMethod->isFunctionTemplateSpecialization() &&
3311  NewMethod->isFunctionTemplateSpecialization();
3312  bool isFriend = NewMethod->getFriendObjectKind();
3313 
3314  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3315  !IsClassScopeExplicitSpecialization) {
3316  // -- Member function declarations with the same name and the
3317  // same parameter types cannot be overloaded if any of them
3318  // is a static member function declaration.
3319  if (OldMethod->isStatic() != NewMethod->isStatic()) {
3320  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3321  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3322  return true;
3323  }
3324 
3325  // C++ [class.mem]p1:
3326  // [...] A member shall not be declared twice in the
3327  // member-specification, except that a nested class or member
3328  // class template can be declared and then later defined.
3329  if (!inTemplateInstantiation()) {
3330  unsigned NewDiag;
3331  if (isa<CXXConstructorDecl>(OldMethod))
3332  NewDiag = diag::err_constructor_redeclared;
3333  else if (isa<CXXDestructorDecl>(NewMethod))
3334  NewDiag = diag::err_destructor_redeclared;
3335  else if (isa<CXXConversionDecl>(NewMethod))
3336  NewDiag = diag::err_conv_function_redeclared;
3337  else
3338  NewDiag = diag::err_member_redeclared;
3339 
3340  Diag(New->getLocation(), NewDiag);
3341  } else {
3342  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3343  << New << New->getType();
3344  }
3345  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3346  return true;
3347 
3348  // Complain if this is an explicit declaration of a special
3349  // member that was initially declared implicitly.
3350  //
3351  // As an exception, it's okay to befriend such methods in order
3352  // to permit the implicit constructor/destructor/operator calls.
3353  } else if (OldMethod->isImplicit()) {
3354  if (isFriend) {
3355  NewMethod->setImplicit();
3356  } else {
3357  Diag(NewMethod->getLocation(),
3358  diag::err_definition_of_implicitly_declared_member)
3359  << New << getSpecialMember(OldMethod);
3360  return true;
3361  }
3362  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3363  Diag(NewMethod->getLocation(),
3364  diag::err_definition_of_explicitly_defaulted_member)
3365  << getSpecialMember(OldMethod);
3366  return true;
3367  }
3368  }
3369 
3370  // C++11 [dcl.attr.noreturn]p1:
3371  // The first declaration of a function shall specify the noreturn
3372  // attribute if any declaration of that function specifies the noreturn
3373  // attribute.
3374  const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3375  if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3376  Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3377  Diag(Old->getFirstDecl()->getLocation(),
3378  diag::note_noreturn_missing_first_decl);
3379  }
3380 
3381  // C++11 [dcl.attr.depend]p2:
3382  // The first declaration of a function shall specify the
3383  // carries_dependency attribute for its declarator-id if any declaration
3384  // of the function specifies the carries_dependency attribute.
3385  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3386  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3387  Diag(CDA->getLocation(),
3388  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3389  Diag(Old->getFirstDecl()->getLocation(),
3390  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3391  }
3392 
3393  // (C++98 8.3.5p3):
3394  // All declarations for a function shall agree exactly in both the
3395  // return type and the parameter-type-list.
3396  // We also want to respect all the extended bits except noreturn.
3397 
3398  // noreturn should now match unless the old type info didn't have it.
3399  QualType OldQTypeForComparison = OldQType;
3400  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3401  auto *OldType = OldQType->castAs<FunctionProtoType>();
3402  const FunctionType *OldTypeForComparison
3403  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3404  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3405  assert(OldQTypeForComparison.isCanonical());
3406  }
3407 
3408  if (haveIncompatibleLanguageLinkages(Old, New)) {
3409  // As a special case, retain the language linkage from previous
3410  // declarations of a friend function as an extension.
3411  //
3412  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3413  // and is useful because there's otherwise no way to specify language
3414  // linkage within class scope.
3415  //
3416  // Check cautiously as the friend object kind isn't yet complete.
3417  if (New->getFriendObjectKind() != Decl::FOK_None) {
3418  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3419  Diag(OldLocation, PrevDiag);
3420  } else {
3421  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3422  Diag(OldLocation, PrevDiag);
3423  return true;
3424  }
3425  }
3426 
3427  if (OldQTypeForComparison == NewQType)
3428  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3429 
3430  // If the types are imprecise (due to dependent constructs in friends or
3431  // local extern declarations), it's OK if they differ. We'll check again
3432  // during instantiation.
3433  if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3434  return false;
3435 
3436  // Fall through for conflicting redeclarations and redefinitions.
3437  }
3438 
3439  // C: Function types need to be compatible, not identical. This handles
3440  // duplicate function decls like "void f(int); void f(enum X);" properly.
3441  if (!getLangOpts().CPlusPlus &&
3442  Context.typesAreCompatible(OldQType, NewQType)) {
3443  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3444  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3445  const FunctionProtoType *OldProto = nullptr;
3446  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3447  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3448  // The old declaration provided a function prototype, but the
3449  // new declaration does not. Merge in the prototype.
3450  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3451  SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3452  NewQType =
3453  Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3454  OldProto->getExtProtoInfo());
3455  New->setType(NewQType);
3456  New->setHasInheritedPrototype();
3457 
3458  // Synthesize parameters with the same types.
3460  for (const auto &ParamType : OldProto->param_types()) {
3461  ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3462  SourceLocation(), nullptr,
3463  ParamType, /*TInfo=*/nullptr,
3464  SC_None, nullptr);
3465  Param->setScopeInfo(0, Params.size());
3466  Param->setImplicit();
3467  Params.push_back(Param);
3468  }
3469 
3470  New->setParams(Params);
3471  }
3472 
3473  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3474  }
3475 
3476  // GNU C permits a K&R definition to follow a prototype declaration
3477  // if the declared types of the parameters in the K&R definition
3478  // match the types in the prototype declaration, even when the
3479  // promoted types of the parameters from the K&R definition differ
3480  // from the types in the prototype. GCC then keeps the types from
3481  // the prototype.
3482  //
3483  // If a variadic prototype is followed by a non-variadic K&R definition,
3484  // the K&R definition becomes variadic. This is sort of an edge case, but
3485  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3486  // C99 6.9.1p8.
3487  if (!getLangOpts().CPlusPlus &&
3488  Old->hasPrototype() && !New->hasPrototype() &&
3489  New->getType()->getAs<FunctionProtoType>() &&
3490  Old->getNumParams() == New->getNumParams()) {
3491  SmallVector<QualType, 16> ArgTypes;
3493  const FunctionProtoType *OldProto
3494  = Old->getType()->getAs<FunctionProtoType>();
3495  const FunctionProtoType *NewProto
3496  = New->getType()->getAs<FunctionProtoType>();
3497 
3498  // Determine whether this is the GNU C extension.
3499  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3500  NewProto->getReturnType());
3501  bool LooseCompatible = !MergedReturn.isNull();
3502  for (unsigned Idx = 0, End = Old->getNumParams();
3503  LooseCompatible && Idx != End; ++Idx) {
3504  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3505  ParmVarDecl *NewParm = New->getParamDecl(Idx);
3506  if (Context.typesAreCompatible(OldParm->getType(),
3507  NewProto->getParamType(Idx))) {
3508  ArgTypes.push_back(NewParm->getType());
3509  } else if (Context.typesAreCompatible(OldParm->getType(),
3510  NewParm->getType(),
3511  /*CompareUnqualified=*/true)) {
3512  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3513  NewProto->getParamType(Idx) };
3514  Warnings.push_back(Warn);
3515  ArgTypes.push_back(NewParm->getType());
3516  } else
3517  LooseCompatible = false;
3518  }
3519 
3520  if (LooseCompatible) {
3521  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3522  Diag(Warnings[Warn].NewParm->getLocation(),
3523  diag::ext_param_promoted_not_compatible_with_prototype)
3524  << Warnings[Warn].PromotedType
3525  << Warnings[Warn].OldParm->getType();
3526  if (Warnings[Warn].OldParm->getLocation().isValid())
3527  Diag(Warnings[Warn].OldParm->getLocation(),
3528  diag::note_previous_declaration);
3529  }
3530 
3531  if (MergeTypeWithOld)
3532  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3533  OldProto->getExtProtoInfo()));
3534  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3535  }
3536 
3537  // Fall through to diagnose conflicting types.
3538  }
3539 
3540  // A function that has already been declared has been redeclared or
3541  // defined with a different type; show an appropriate diagnostic.
3542 
3543  // If the previous declaration was an implicitly-generated builtin
3544  // declaration, then at the very least we should use a specialized note.
3545  unsigned BuiltinID;
3546  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3547  // If it's actually a library-defined builtin function like 'malloc'
3548  // or 'printf', just warn about the incompatible redeclaration.
3549  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3550  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3551  Diag(OldLocation, diag::note_previous_builtin_declaration)
3552  << Old << Old->getType();
3553 
3554  // If this is a global redeclaration, just forget hereafter
3555  // about the "builtin-ness" of the function.
3556  //
3557  // Doing this for local extern declarations is problematic. If
3558  // the builtin declaration remains visible, a second invalid
3559  // local declaration will produce a hard error; if it doesn't
3560  // remain visible, a single bogus local redeclaration (which is
3561  // actually only a warning) could break all the downstream code.
3563  New->getIdentifier()->revertBuiltin();
3564 
3565  return false;
3566  }
3567 
3568  PrevDiag = diag::note_previous_builtin_declaration;
3569  }
3570 
3571  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3572  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3573  return true;
3574 }
3575 
3576 /// Completes the merge of two function declarations that are
3577 /// known to be compatible.
3578 ///
3579 /// This routine handles the merging of attributes and other
3580 /// properties of function declarations from the old declaration to
3581 /// the new declaration, once we know that New is in fact a
3582 /// redeclaration of Old.
3583 ///
3584 /// \returns false
3586  Scope *S, bool MergeTypeWithOld) {
3587  // Merge the attributes
3588  mergeDeclAttributes(New, Old);
3589 
3590  // Merge "pure" flag.
3591  if (Old->isPure())
3592  New->setPure();
3593 
3594  // Merge "used" flag.
3595  if (Old->getMostRecentDecl()->isUsed(false))
3596  New->setIsUsed();
3597 
3598  // Merge attributes from the parameters. These can mismatch with K&R
3599  // declarations.
3600  if (New->getNumParams() == Old->getNumParams())
3601  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3602  ParmVarDecl *NewParam = New->getParamDecl(i);
3603  ParmVarDecl *OldParam = Old->getParamDecl(i);
3604  mergeParamDeclAttributes(NewParam, OldParam, *this);
3605  mergeParamDeclTypes(NewParam, OldParam, *this);
3606  }
3607 
3608  if (getLangOpts().CPlusPlus)
3609  return MergeCXXFunctionDecl(New, Old, S);
3610 
3611  // Merge the function types so the we get the composite types for the return
3612  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3613  // was visible.
3614  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3615  if (!Merged.isNull() && MergeTypeWithOld)
3616  New->setType(Merged);
3617 
3618  return false;
3619 }
3620 
3622  ObjCMethodDecl *oldMethod) {
3623  // Merge the attributes, including deprecated/unavailable
3624  AvailabilityMergeKind MergeKind =
3625  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3626  ? AMK_ProtocolImplementation
3627  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3628  : AMK_Override;
3629 
3630  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3631 
3632  // Merge attributes from the parameters.
3634  oe = oldMethod->param_end();
3636  ni = newMethod->param_begin(), ne = newMethod->param_end();
3637  ni != ne && oi != oe; ++ni, ++oi)
3638  mergeParamDeclAttributes(*ni, *oi, *this);
3639 
3640  CheckObjCMethodOverride(newMethod, oldMethod);
3641 }
3642 
3643 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3644  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3645 
3647  ? diag::err_redefinition_different_type
3648  : diag::err_redeclaration_different_type)
3649  << New->getDeclName() << New->getType() << Old->getType();
3650 
3651  diag::kind PrevDiag;
3652  SourceLocation OldLocation;
3653  std::tie(PrevDiag, OldLocation)
3655  S.Diag(OldLocation, PrevDiag);
3656  New->setInvalidDecl();
3657 }
3658 
3659 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3660 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3661 /// emitting diagnostics as appropriate.
3662 ///
3663 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3664 /// to here in AddInitializerToDecl. We can't check them before the initializer
3665 /// is attached.
3667  bool MergeTypeWithOld) {
3668  if (New->isInvalidDecl() || Old->isInvalidDecl())
3669  return;
3670 
3671  QualType MergedT;
3672  if (getLangOpts().CPlusPlus) {
3673  if (New->getType()->isUndeducedType()) {
3674  // We don't know what the new type is until the initializer is attached.
3675  return;
3676  } else if (Context.hasSameType(New->getType(), Old->getType())) {
3677  // These could still be something that needs exception specs checked.
3678  return MergeVarDeclExceptionSpecs(New, Old);
3679  }
3680  // C++ [basic.link]p10:
3681  // [...] the types specified by all declarations referring to a given
3682  // object or function shall be identical, except that declarations for an
3683  // array object can specify array types that differ by the presence or
3684  // absence of a major array bound (8.3.4).
3685  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3686  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3687  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3688 
3689  // We are merging a variable declaration New into Old. If it has an array
3690  // bound, and that bound differs from Old's bound, we should diagnose the
3691  // mismatch.
3692  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3693  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3694  PrevVD = PrevVD->getPreviousDecl()) {
3695  const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3696  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3697  continue;
3698 
3699  if (!Context.hasSameType(NewArray, PrevVDTy))
3700  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3701  }
3702  }
3703 
3704  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3705  if (Context.hasSameType(OldArray->getElementType(),
3706  NewArray->getElementType()))
3707  MergedT = New->getType();
3708  }
3709  // FIXME: Check visibility. New is hidden but has a complete type. If New
3710  // has no array bound, it should not inherit one from Old, if Old is not
3711  // visible.
3712  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3713  if (Context.hasSameType(OldArray->getElementType(),
3714  NewArray->getElementType()))
3715  MergedT = Old->getType();
3716  }
3717  }
3718  else if (New->getType()->isObjCObjectPointerType() &&
3719  Old->getType()->isObjCObjectPointerType()) {
3720  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3721  Old->getType());
3722  }
3723  } else {
3724  // C 6.2.7p2:
3725  // All declarations that refer to the same object or function shall have
3726  // compatible type.
3727  MergedT = Context.mergeTypes(New->getType(), Old->getType());
3728  }
3729  if (MergedT.isNull()) {
3730  // It's OK if we couldn't merge types if either type is dependent, for a
3731  // block-scope variable. In other cases (static data members of class
3732  // templates, variable templates, ...), we require the types to be
3733  // equivalent.
3734  // FIXME: The C++ standard doesn't say anything about this.
3735  if ((New->getType()->isDependentType() ||
3736  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3737  // If the old type was dependent, we can't merge with it, so the new type
3738  // becomes dependent for now. We'll reproduce the original type when we
3739  // instantiate the TypeSourceInfo for the variable.
3740  if (!New->getType()->isDependentType() && MergeTypeWithOld)
3741  New->setType(Context.DependentTy);
3742  return;
3743  }
3744  return diagnoseVarDeclTypeMismatch(*this, New, Old);
3745  }
3746 
3747  // Don't actually update the type on the new declaration if the old
3748  // declaration was an extern declaration in a different scope.
3749  if (MergeTypeWithOld)
3750  New->setType(MergedT);
3751 }
3752 
3753 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3755  // C11 6.2.7p4:
3756  // For an identifier with internal or external linkage declared
3757  // in a scope in which a prior declaration of that identifier is
3758  // visible, if the prior declaration specifies internal or
3759  // external linkage, the type of the identifier at the later
3760  // declaration becomes the composite type.
3761  //
3762  // If the variable isn't visible, we do not merge with its type.
3763  if (Previous.isShadowed())
3764  return false;
3765 
3766  if (S.getLangOpts().CPlusPlus) {
3767  // C++11 [dcl.array]p3:
3768  // If there is a preceding declaration of the entity in the same
3769  // scope in which the bound was specified, an omitted array bound
3770  // is taken to be the same as in that earlier declaration.
3771  return NewVD->isPreviousDeclInSameBlockScope() ||
3772  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3774  } else {
3775  // If the old declaration was function-local, don't merge with its
3776  // type unless we're in the same function.
3777  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3778  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3779  }
3780 }
3781 
3782 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3783 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3784 /// situation, merging decls or emitting diagnostics as appropriate.
3785 ///
3786 /// Tentative definition rules (C99 6.9.2p2) are checked by
3787 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3788 /// definitions here, since the initializer hasn't been attached.
3789 ///
3791  // If the new decl is already invalid, don't do any other checking.
3792  if (New->isInvalidDecl())
3793  return;
3794 
3795  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3796  return;
3797 
3798  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3799 
3800  // Verify the old decl was also a variable or variable template.
3801  VarDecl *Old = nullptr;
3802  VarTemplateDecl *OldTemplate = nullptr;
3803  if (Previous.isSingleResult()) {
3804  if (NewTemplate) {
3805  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3806  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3807 
3808  if (auto *Shadow =
3809  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3810  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3811  return New->setInvalidDecl();
3812  } else {
3813  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3814 
3815  if (auto *Shadow =
3816  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3817  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3818  return New->setInvalidDecl();
3819  }
3820  }
3821  if (!Old) {
3822  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3823  << New->getDeclName();
3824  notePreviousDefinition(Previous.getRepresentativeDecl(),
3825  New->getLocation());
3826  return New->setInvalidDecl();
3827  }
3828 
3829  // Ensure the template parameters are compatible.
3830  if (NewTemplate &&
3831  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3832  OldTemplate->getTemplateParameters(),
3833  /*Complain=*/true, TPL_TemplateMatch))
3834  return New->setInvalidDecl();
3835 
3836  // C++ [class.mem]p1:
3837  // A member shall not be declared twice in the member-specification [...]
3838  //
3839  // Here, we need only consider static data members.
3840  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3841  Diag(New->getLocation(), diag::err_duplicate_member)
3842  << New->getIdentifier();
3843  Diag(Old->getLocation(), diag::note_previous_declaration);
3844  New->setInvalidDecl();
3845  }
3846 
3847  mergeDeclAttributes(New, Old);
3848  // Warn if an already-declared variable is made a weak_import in a subsequent
3849  // declaration
3850  if (New->hasAttr<WeakImportAttr>() &&
3851  Old->getStorageClass() == SC_None &&
3852  !Old->hasAttr<WeakImportAttr>()) {
3853  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3854  notePreviousDefinition(Old, New->getLocation());
3855  // Remove weak_import attribute on new declaration.
3856  New->dropAttr<WeakImportAttr>();
3857  }
3858 
3859  if (New->hasAttr<InternalLinkageAttr>() &&
3860  !Old->hasAttr<InternalLinkageAttr>()) {
3861  Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3862  << New->getDeclName();
3863  notePreviousDefinition(Old, New->getLocation());
3864  New->dropAttr<InternalLinkageAttr>();
3865  }
3866 
3867  // Merge the types.
3868  VarDecl *MostRecent = Old->getMostRecentDecl();
3869  if (MostRecent != Old) {
3870  MergeVarDeclTypes(New, MostRecent,
3871  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3872  if (New->isInvalidDecl())
3873  return;
3874  }
3875 
3876  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3877  if (New->isInvalidDecl())
3878  return;
3879 
3880  diag::kind PrevDiag;
3881  SourceLocation OldLocation;
3882  std::tie(PrevDiag, OldLocation) =
3884 
3885  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3886  if (New->getStorageClass() == SC_Static &&
3887  !New->isStaticDataMember() &&
3888  Old->hasExternalFormalLinkage()) {
3889  if (getLangOpts().MicrosoftExt) {
3890  Diag(New->getLocation(), diag::ext_static_non_static)
3891  << New->getDeclName();
3892  Diag(OldLocation, PrevDiag);
3893  } else {
3894  Diag(New->getLocation(), diag::err_static_non_static)
3895  << New->getDeclName();
3896  Diag(OldLocation, PrevDiag);
3897  return New->setInvalidDecl();
3898  }
3899  }
3900  // C99 6.2.2p4:
3901  // For an identifier declared with the storage-class specifier
3902  // extern in a scope in which a prior declaration of that
3903  // identifier is visible,23) if the prior declaration specifies
3904  // internal or external linkage, the linkage of the identifier at
3905  // the later declaration is the same as the linkage specified at
3906  // the prior declaration. If no prior declaration is visible, or
3907  // if the prior declaration specifies no linkage, then the
3908  // identifier has external linkage.
3909  if (New->hasExternalStorage() && Old->hasLinkage())
3910  /* Okay */;
3911  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3912  !New->isStaticDataMember() &&
3914  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3915  Diag(OldLocation, PrevDiag);
3916  return New->setInvalidDecl();
3917  }
3918 
3919  // Check if extern is followed by non-extern and vice-versa.
3920  if (New->hasExternalStorage() &&
3921  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3922  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3923  Diag(OldLocation, PrevDiag);
3924  return New->setInvalidDecl();
3925  }
3926  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3927  !New->hasExternalStorage()) {
3928  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3929  Diag(OldLocation, PrevDiag);
3930  return New->setInvalidDecl();
3931  }
3932 
3933  if (CheckRedeclarationModuleOwnership(New, Old))
3934  return;
3935 
3936  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3937 
3938  // FIXME: The test for external storage here seems wrong? We still
3939  // need to check for mismatches.
3940  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3941  // Don't complain about out-of-line definitions of static members.
3942  !(Old->getLexicalDeclContext()->isRecord() &&
3943  !New->getLexicalDeclContext()->isRecord())) {
3944  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3945  Diag(OldLocation, PrevDiag);
3946  return New->setInvalidDecl();
3947  }
3948 
3949  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3950  if (VarDecl *Def = Old->getDefinition()) {
3951  // C++1z [dcl.fcn.spec]p4:
3952  // If the definition of a variable appears in a translation unit before
3953  // its first declaration as inline, the program is ill-formed.
3954  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3955  Diag(Def->getLocation(), diag::note_previous_definition);
3956  }
3957  }
3958 
3959  // If this redeclaration makes the variable inline, we may need to add it to
3960  // UndefinedButUsed.
3961  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3962  !Old->getDefinition() && !New->isThisDeclarationADefinition())
3963  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3964  SourceLocation()));
3965 
3966  if (New->getTLSKind() != Old->getTLSKind()) {
3967  if (!Old->getTLSKind()) {
3968  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3969  Diag(OldLocation, PrevDiag);
3970  } else if (!New->getTLSKind()) {
3971  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3972  Diag(OldLocation, PrevDiag);
3973  } else {
3974  // Do not allow redeclaration to change the variable between requiring
3975  // static and dynamic initialization.
3976  // FIXME: GCC allows this, but uses the TLS keyword on the first
3977  // declaration to determine the kind. Do we need to be compatible here?
3978  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3979  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3980  Diag(OldLocation, PrevDiag);
3981  }
3982  }
3983 
3984  // C++ doesn't have tentative definitions, so go right ahead and check here.
3985  if (getLangOpts().CPlusPlus &&
3987  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3988  Old->getCanonicalDecl()->isConstexpr()) {
3989  // This definition won't be a definition any more once it's been merged.
3990  Diag(New->getLocation(),
3991  diag::warn_deprecated_redundant_constexpr_static_def);
3992  } else if (VarDecl *Def = Old->getDefinition()) {
3993  if (checkVarDeclRedefinition(Def, New))
3994  return;
3995  }
3996  }
3997 
3998  if (haveIncompatibleLanguageLinkages(Old, New)) {
3999  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4000  Diag(OldLocation, PrevDiag);
4001  New->setInvalidDecl();
4002  return;
4003  }
4004 
4005  // Merge "used" flag.
4006  if (Old->getMostRecentDecl()->isUsed(false))
4007  New->setIsUsed();
4008 
4009  // Keep a chain of previous declarations.
4010  New->setPreviousDecl(Old);
4011  if (NewTemplate)
4012  NewTemplate->setPreviousDecl(OldTemplate);
4014 
4015  // Inherit access appropriately.
4016  New->setAccess(Old->getAccess());
4017  if (NewTemplate)
4018  NewTemplate->setAccess(New->getAccess());
4019 
4020  if (Old->isInline())
4021  New->setImplicitlyInline();
4022 }
4023 
4025  SourceManager &SrcMgr = getSourceManager();
4026  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4027  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4028  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4029  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4030  auto &HSI = PP.getHeaderSearchInfo();
4031  StringRef HdrFilename =
4032  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4033 
4034  auto noteFromModuleOrInclude = [&](Module *Mod,
4035  SourceLocation IncLoc) -> bool {
4036  // Redefinition errors with modules are common with non modular mapped
4037  // headers, example: a non-modular header H in module A that also gets
4038  // included directly in a TU. Pointing twice to the same header/definition
4039  // is confusing, try to get better diagnostics when modules is on.
4040  if (IncLoc.isValid()) {
4041  if (Mod) {
4042  Diag(IncLoc, diag::note_redefinition_modules_same_file)
4043  << HdrFilename.str() << Mod->getFullModuleName();
4044  if (!Mod->DefinitionLoc.isInvalid())
4045  Diag(Mod->DefinitionLoc, diag::note_defined_here)
4046  << Mod->getFullModuleName();
4047  } else {
4048  Diag(IncLoc, diag::note_redefinition_include_same_file)
4049  << HdrFilename.str();
4050  }
4051  return true;
4052  }
4053 
4054  return false;
4055  };
4056 
4057  // Is it the same file and same offset? Provide more information on why
4058  // this leads to a redefinition error.
4059  bool EmittedDiag = false;
4060  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4061  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4062  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4063  EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4064  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4065 
4066  // If the header has no guards, emit a note suggesting one.
4067  if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4068  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4069 
4070  if (EmittedDiag)
4071  return;
4072  }
4073 
4074  // Redefinition coming from different files or couldn't do better above.
4075  if (Old->getLocation().isValid())
4076  Diag(Old->getLocation(), diag::note_previous_definition);
4077 }
4078 
4079 /// We've just determined that \p Old and \p New both appear to be definitions
4080 /// of the same variable. Either diagnose or fix the problem.
4082  if (!hasVisibleDefinition(Old) &&
4083  (New->getFormalLinkage() == InternalLinkage ||
4084  New->isInline() ||
4085  New->getDescribedVarTemplate() ||
4087  New->getDeclContext()->isDependentContext())) {
4088  // The previous definition is hidden, and multiple definitions are
4089  // permitted (in separate TUs). Demote this to a declaration.
4091 
4092  // Make the canonical definition visible.
4093  if (auto *OldTD = Old->getDescribedVarTemplate())
4094  makeMergedDefinitionVisible(OldTD);
4095  makeMergedDefinitionVisible(Old);
4096  return false;
4097  } else {
4098  Diag(New->getLocation(), diag::err_redefinition) << New;
4099  notePreviousDefinition(Old, New->getLocation());
4100  New->setInvalidDecl();
4101  return true;
4102  }
4103 }
4104 
4105 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4106 /// no declarator (e.g. "struct foo;") is parsed.
4107 Decl *
4109  RecordDecl *&AnonRecord) {
4110  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4111  AnonRecord);
4112 }
4113 
4114 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4115 // disambiguate entities defined in different scopes.
4116 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4117 // compatibility.
4118 // We will pick our mangling number depending on which version of MSVC is being
4119 // targeted.
4120 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4122  ? S->getMSCurManglingNumber()
4123  : S->getMSLastManglingNumber();
4124 }
4125 
4126 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4127  if (!Context.getLangOpts().CPlusPlus)
4128  return;
4129 
4130  if (isa<CXXRecordDecl>(Tag->getParent())) {
4131  // If this tag is the direct child of a class, number it if
4132  // it is anonymous.
4133  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4134  return;
4135  MangleNumberingContext &MCtx =
4136  Context.getManglingNumberContext(Tag->getParent());
4137  Context.setManglingNumber(
4138  Tag, MCtx.getManglingNumber(
4139  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4140  return;
4141  }
4142 
4143  // If this tag isn't a direct child of a class, number it if it is local.
4144  Decl *ManglingContextDecl;
4145  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4146  Tag->getDeclContext(), ManglingContextDecl)) {
4147  Context.setManglingNumber(
4148  Tag, MCtx->getManglingNumber(
4149  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4150  }
4151 }
4152 
4154  TypedefNameDecl *NewTD) {
4155  if (TagFromDeclSpec->isInvalidDecl())
4156  return;
4157 
4158  // Do nothing if the tag already has a name for linkage purposes.
4159  if (TagFromDeclSpec->hasNameForLinkage())
4160  return;
4161 
4162  // A well-formed anonymous tag must always be a TUK_Definition.
4163  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4164 
4165  // The type must match the tag exactly; no qualifiers allowed.
4166  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4167  Context.getTagDeclType(TagFromDeclSpec))) {
4168  if (getLangOpts().CPlusPlus)
4169  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4170  return;
4171  }
4172 
4173  // If we've already computed linkage for the anonymous tag, then
4174  // adding a typedef name for the anonymous decl can change that
4175  // linkage, which might be a serious problem. Diagnose this as
4176  // unsupported and ignore the typedef name. TODO: we should
4177  // pursue this as a language defect and establish a formal rule
4178  // for how to handle it.
4179  if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4180  Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4181 
4182  SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4183  tagLoc = getLocForEndOfToken(tagLoc);
4184 
4185  llvm::SmallString<40> textToInsert;
4186  textToInsert += ' ';
4187  textToInsert += NewTD->getIdentifier()->getName();
4188  Diag(tagLoc, diag::note_typedef_changes_linkage)
4189  << FixItHint::CreateInsertion(tagLoc, textToInsert);
4190  return;
4191  }
4192 
4193  // Otherwise, set this is the anon-decl typedef for the tag.
4194  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4195 }
4196 
4198  switch (T) {
4199  case DeclSpec::TST_class:
4200  return 0;
4201  case DeclSpec::TST_struct:
4202  return 1;
4204  return 2;
4205  case DeclSpec::TST_union:
4206  return 3;
4207  case DeclSpec::TST_enum:
4208  return 4;
4209  default:
4210  llvm_unreachable("unexpected type specifier");
4211  }
4212 }
4213 
4214 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4215 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4216 /// parameters to cope with template friend declarations.
4217 Decl *
4219  MultiTemplateParamsArg TemplateParams,
4220  bool IsExplicitInstantiation,
4221  RecordDecl *&AnonRecord) {
4222  Decl *TagD = nullptr;
4223  TagDecl *Tag = nullptr;
4224  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4229  TagD = DS.getRepAsDecl();
4230 
4231  if (!TagD) // We probably had an error
4232  return nullptr;
4233 
4234  // Note that the above type specs guarantee that the
4235  // type rep is a Decl, whereas in many of the others
4236  // it's a Type.
4237  if (isa<TagDecl>(TagD))
4238  Tag = cast<TagDecl>(TagD);
4239  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4240  Tag = CTD->getTemplatedDecl();
4241  }
4242 
4243  if (Tag) {
4244  handleTagNumbering(Tag, S);
4245  Tag->setFreeStanding();
4246  if (Tag->isInvalidDecl())
4247  return Tag;
4248  }
4249 
4250  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4251  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4252  // or incomplete types shall not be restrict-qualified."
4253  if (TypeQuals & DeclSpec::TQ_restrict)
4254  Diag(DS.getRestrictSpecLoc(),
4255  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4256  << DS.getSourceRange();
4257  }
4258 
4259  if (DS.isInlineSpecified())
4260  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4261  << getLangOpts().CPlusPlus17;
4262 
4263  if (DS.isConstexprSpecified()) {
4264  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4265  // and definitions of functions and variables.
4266  if (Tag)
4267  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4269  else
4270  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4271  // Don't emit warnings after this error.
4272  return TagD;
4273  }
4274 
4275  DiagnoseFunctionSpecifiers(DS);
4276 
4277  if (DS.isFriendSpecified()) {
4278  // If we're dealing with a decl but not a TagDecl, assume that
4279  // whatever routines created it handled the friendship aspect.
4280  if (TagD && !Tag)
4281  return nullptr;
4282  return ActOnFriendTypeDecl(S, DS, TemplateParams);
4283  }
4284 
4285  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4286  bool IsExplicitSpecialization =
4287  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4288  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4289  !IsExplicitInstantiation && !IsExplicitSpecialization &&
4290  !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4291  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4292  // nested-name-specifier unless it is an explicit instantiation
4293  // or an explicit specialization.
4294  //
4295  // FIXME: We allow class template partial specializations here too, per the
4296  // obvious intent of DR1819.
4297  //
4298  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4299  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4301  return nullptr;
4302  }
4303 
4304  // Track whether this decl-specifier declares anything.
4305  bool DeclaresAnything = true;
4306 
4307  // Handle anonymous struct definitions.
4308  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4309  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4311  if (getLangOpts().CPlusPlus ||
4312  Record->getDeclContext()->isRecord()) {
4313  // If CurContext is a DeclContext that can contain statements,
4314  // RecursiveASTVisitor won't visit the decls that
4315  // BuildAnonymousStructOrUnion() will put into CurContext.
4316  // Also store them here so that they can be part of the
4317  // DeclStmt that gets created in this case.
4318  // FIXME: Also return the IndirectFieldDecls created by
4319  // BuildAnonymousStructOr union, for the same reason?
4320  if (CurContext->isFunctionOrMethod())
4321  AnonRecord = Record;
4322  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4323  Context.getPrintingPolicy());
4324  }
4325 
4326  DeclaresAnything = false;
4327  }
4328  }
4329 
4330  // C11 6.7.2.1p2:
4331  // A struct-declaration that does not declare an anonymous structure or
4332  // anonymous union shall contain a struct-declarator-list.
4333  //
4334  // This rule also existed in C89 and C99; the grammar for struct-declaration
4335  // did not permit a struct-declaration without a struct-declarator-list.
4336  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4338  // Check for Microsoft C extension: anonymous struct/union member.
4339  // Handle 2 kinds of anonymous struct/union:
4340  // struct STRUCT;
4341  // union UNION;
4342  // and
4343  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4344  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4345  if ((Tag && Tag->getDeclName()) ||
4347  RecordDecl *Record = nullptr;
4348  if (Tag)
4349  Record = dyn_cast<RecordDecl>(Tag);
4350  else if (const RecordType *RT =
4352  Record = RT->getDecl();
4353  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4354  Record = UT->getDecl();
4355 
4356  if (Record && getLangOpts().MicrosoftExt) {
4357  Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4358  << Record->isUnion() << DS.getSourceRange();
4359  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4360  }
4361 
4362  DeclaresAnything = false;
4363  }
4364  }
4365 
4366  // Skip all the checks below if we have a type error.
4367  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4368  (TagD && TagD->isInvalidDecl()))
4369  return TagD;
4370 
4371  if (getLangOpts().CPlusPlus &&
4373  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4374  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4375  !Enum->getIdentifier() && !Enum->isInvalidDecl())
4376  DeclaresAnything = false;
4377 
4378  if (!DS.isMissingDeclaratorOk()) {
4379  // Customize diagnostic for a typedef missing a name.
4381  Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4382  << DS.getSourceRange();
4383  else
4384  DeclaresAnything = false;
4385  }
4386 
4387  if (DS.isModulePrivateSpecified() &&
4388  Tag && Tag->getDeclContext()->isFunctionOrMethod())
4389  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4390  << Tag->getTagKind()
4392 
4393  ActOnDocumentableDecl(TagD);
4394 
4395  // C 6.7/2:
4396  // A declaration [...] shall declare at least a declarator [...], a tag,
4397  // or the members of an enumeration.
4398  // C++ [dcl.dcl]p3:
4399  // [If there are no declarators], and except for the declaration of an
4400  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4401  // names into the program, or shall redeclare a name introduced by a
4402  // previous declaration.
4403  if (!DeclaresAnything) {
4404  // In C, we allow this as a (popular) extension / bug. Don't bother
4405  // producing further diagnostics for redundant qualifiers after this.
4406  Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4407  return TagD;
4408  }
4409 
4410  // C++ [dcl.stc]p1:
4411  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4412  // init-declarator-list of the declaration shall not be empty.
4413  // C++ [dcl.fct.spec]p1:
4414  // If a cv-qualifier appears in a decl-specifier-seq, the
4415  // init-declarator-list of the declaration shall not be empty.
4416  //
4417  // Spurious qualifiers here appear to be valid in C.
4418  unsigned DiagID = diag::warn_standalone_specifier;
4419  if (getLangOpts().CPlusPlus)
4420  DiagID = diag::ext_standalone_specifier;
4421 
4422  // Note that a linkage-specification sets a storage class, but
4423  // 'extern "C" struct foo;' is actually valid and not theoretically
4424  // useless.
4425  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4426  if (SCS == DeclSpec::SCS_mutable)
4427  // Since mutable is not a viable storage class specifier in C, there is
4428  // no reason to treat it as an extension. Instead, diagnose as an error.
4429  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4430  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4431  Diag(DS.getStorageClassSpecLoc(), DiagID)
4433  }
4434 
4435  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4436  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4437  << DeclSpec::getSpecifierName(TSCS);
4438  if (DS.getTypeQualifiers()) {
4440  Diag(DS.getConstSpecLoc(), DiagID) << "const";
4442  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4443  // Restrict is covered above.
4445  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4447  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4448  }
4449 
4450  // Warn about ignored type attributes, for example:
4451  // __attribute__((aligned)) struct A;
4452  // Attributes should be placed after tag to apply to type declaration.
4453  if (!DS.getAttributes().empty()) {
4454  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4455  if (TypeSpecType == DeclSpec::TST_class ||
4456  TypeSpecType == DeclSpec::TST_struct ||
4457  TypeSpecType == DeclSpec::TST_interface ||
4458  TypeSpecType == DeclSpec::TST_union ||
4459  TypeSpecType == DeclSpec::TST_enum) {
4460  for (const ParsedAttr &AL : DS.getAttributes())
4461  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4462  << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4463  }
4464  }
4465 
4466  return TagD;
4467 }
4468 
4469 /// We are trying to inject an anonymous member into the given scope;
4470 /// check if there's an existing declaration that can't be overloaded.
4471 ///
4472 /// \return true if this is a forbidden redeclaration
4473 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4474  Scope *S,
4475  DeclContext *Owner,
4476  DeclarationName Name,
4477  SourceLocation NameLoc,
4478  bool IsUnion) {
4479  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4481  if (!SemaRef.LookupName(R, S)) return false;
4482 
4483  // Pick a representative declaration.
4485  assert(PrevDecl && "Expected a non-null Decl");
4486 
4487  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4488  return false;
4489 
4490  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4491  << IsUnion << Name;
4492  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4493 
4494  return true;
4495 }
4496 
4497 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4498 /// anonymous struct or union AnonRecord into the owning context Owner
4499 /// and scope S. This routine will be invoked just after we realize
4500 /// that an unnamed union or struct is actually an anonymous union or
4501 /// struct, e.g.,
4502 ///
4503 /// @code
4504 /// union {
4505 /// int i;
4506 /// float f;
4507 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4508 /// // f into the surrounding scope.x
4509 /// @endcode
4510 ///
4511 /// This routine is recursive, injecting the names of nested anonymous
4512 /// structs/unions into the owning context and scope as well.
4513 static bool
4515  RecordDecl *AnonRecord, AccessSpecifier AS,
4516  SmallVectorImpl<NamedDecl *> &Chaining) {
4517  bool Invalid = false;
4518 
4519  // Look every FieldDecl and IndirectFieldDecl with a name.
4520  for (auto *D : AnonRecord->decls()) {
4521  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4522  cast<NamedDecl>(D)->getDeclName()) {
4523  ValueDecl *VD = cast<ValueDecl>(D);
4524  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4525  VD->getLocation(),
4526  AnonRecord->isUnion())) {
4527  // C++ [class.union]p2:
4528  // The names of the members of an anonymous union shall be
4529  // distinct from the names of any other entity in the
4530  // scope in which the anonymous union is declared.
4531  Invalid = true;
4532  } else {
4533  // C++ [class.union]p2:
4534  // For the purpose of name lookup, after the anonymous union
4535  // definition, the members of the anonymous union are
4536  // considered to have been defined in the scope in which the
4537  // anonymous union is declared.
4538  unsigned OldChainingSize = Chaining.size();
4539  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4540  Chaining.append(IF->chain_begin(), IF->chain_end());
4541  else
4542  Chaining.push_back(VD);
4543 
4544  assert(Chaining.size() >= 2);
4545  NamedDecl **NamedChain =
4546  new (SemaRef.Context)NamedDecl*[Chaining.size()];
4547  for (unsigned i = 0; i < Chaining.size(); i++)
4548  NamedChain[i] = Chaining[i];
4549 
4551  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4552  VD->getType(), {NamedChain, Chaining.size()});
4553 
4554  for (const auto *Attr : VD->attrs())
4555  IndirectField->addAttr(Attr->clone(SemaRef.Context));
4556 
4557  IndirectField->setAccess(AS);
4558  IndirectField->setImplicit();
4559  SemaRef.PushOnScopeChains(IndirectField, S);
4560 
4561  // That includes picking up the appropriate access specifier.
4562  if (AS != AS_none) IndirectField->setAccess(AS);
4563 
4564  Chaining.resize(OldChainingSize);
4565  }
4566  }
4567  }
4568 
4569  return Invalid;
4570 }
4571 
4572 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4573 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4574 /// illegal input values are mapped to SC_None.
4575 static StorageClass
4577  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4578  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4579  "Parser allowed 'typedef' as storage class VarDecl.");
4580  switch (StorageClassSpec) {
4581  case DeclSpec::SCS_unspecified: return SC_None;
4582  case DeclSpec::SCS_extern:
4583  if (DS.isExternInLinkageSpec())
4584  return SC_None;
4585  return SC_Extern;
4586  case DeclSpec::SCS_static: return SC_Static;
4587  case DeclSpec::SCS_auto: return SC_Auto;
4588  case DeclSpec::SCS_register: return SC_Register;
4590  // Illegal SCSs map to None: error reporting is up to the caller.
4591  case DeclSpec::SCS_mutable: // Fall through.
4592  case DeclSpec::SCS_typedef: return SC_None;
4593  }
4594  llvm_unreachable("unknown storage class specifier");
4595 }
4596 
4598  assert(Record->hasInClassInitializer());
4599 
4600  for (const auto *I : Record->decls()) {
4601  const auto *FD = dyn_cast<FieldDecl>(I);
4602  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4603  FD = IFD->getAnonField();
4604  if (FD && FD->hasInClassInitializer())
4605  return FD->getLocation();
4606  }
4607 
4608  llvm_unreachable("couldn't find in-class initializer");
4609 }
4610 
4612  SourceLocation DefaultInitLoc) {
4613  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4614  return;
4615 
4616  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4617  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4618 }
4619 
4621  CXXRecordDecl *AnonUnion) {
4622  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4623  return;
4624 
4625  checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4626 }
4627 
4628 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4629 /// anonymous structure or union. Anonymous unions are a C++ feature
4630 /// (C++ [class.union]) and a C11 feature; anonymous structures
4631 /// are a C11 feature and GNU C++ extension.
4633  AccessSpecifier AS,
4634  RecordDecl *Record,
4635  const PrintingPolicy &Policy) {
4636  DeclContext *Owner = Record->getDeclContext();
4637 
4638  // Diagnose whether this anonymous struct/union is an extension.
4639  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4640  Diag(Record->getLocation(), diag::ext_anonymous_union);
4641  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4642  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4643  else if (!Record->isUnion() && !getLangOpts().C11)
4644  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4645 
4646  // C and C++ require different kinds of checks for anonymous
4647  // structs/unions.
4648  bool Invalid = false;
4649  if (getLangOpts().CPlusPlus) {
4650  const char *PrevSpec = nullptr;
4651  unsigned DiagID;
4652  if (Record->isUnion()) {
4653  // C++ [class.union]p6:
4654  // C++17 [class.union.anon]p2:
4655  // Anonymous unions declared in a named namespace or in the
4656  // global namespace shall be declared static.
4657  DeclContext *OwnerScope = Owner->getRedeclContext();
4659  (OwnerScope->isTranslationUnit() ||
4660  (OwnerScope->isNamespace() &&
4661  !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4662  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4663  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4664 
4665  // Recover by adding 'static'.
4667  PrevSpec, DiagID, Policy);
4668  }
4669  // C++ [class.union]p6:
4670  // A storage class is not allowed in a declaration of an
4671  // anonymous union in a class scope.
4673  isa<RecordDecl>(Owner)) {
4675  diag::err_anonymous_union_with_storage_spec)
4677 
4678  // Recover by removing the storage specifier.
4680  SourceLocation(),
4681  PrevSpec, DiagID, Context.getPrintingPolicy());
4682  }
4683  }
4684 
4685  // Ignore const/volatile/restrict qualifiers.
4686  if (DS.getTypeQualifiers()) {
4688  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4689  << Record->isUnion() << "const"
4692  Diag(DS.getVolatileSpecLoc(),
4693  diag::ext_anonymous_struct_union_qualified)
4694  << Record->isUnion() << "volatile"
4697  Diag(DS.getRestrictSpecLoc(),
4698  diag::ext_anonymous_struct_union_qualified)
4699  << Record->isUnion() << "restrict"
4702  Diag(DS.getAtomicSpecLoc(),
4703  diag::ext_anonymous_struct_union_qualified)
4704  << Record->isUnion() << "_Atomic"
4708  diag::ext_anonymous_struct_union_qualified)
4709  << Record->isUnion() << "__unaligned"
4711 
4712  DS.ClearTypeQualifiers();
4713  }
4714 
4715  // C++ [class.union]p2:
4716  // The member-specification of an anonymous union shall only
4717  // define non-static data members. [Note: nested types and
4718  // functions cannot be declared within an anonymous union. ]
4719  for (auto *Mem : Record->decls()) {
4720  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4721  // C++ [class.union]p3:
4722  // An anonymous union shall not have private or protected
4723  // members (clause 11).
4724  assert(FD->getAccess() != AS_none);
4725  if (FD->getAccess() != AS_public) {
4726  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4727  << Record->isUnion() << (FD->getAccess() == AS_protected);
4728  Invalid = true;
4729  }
4730 
4731  // C++ [class.union]p1
4732  // An object of a class with a non-trivial constructor, a non-trivial
4733  // copy constructor, a non-trivial destructor, or a non-trivial copy
4734  // assignment operator cannot be a member of a union, nor can an
4735  // array of such objects.
4736  if (CheckNontrivialField(FD))
4737  Invalid = true;
4738  } else if (Mem->isImplicit()) {
4739  // Any implicit members are fine.
4740  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4741  // This is a type that showed up in an
4742  // elaborated-type-specifier inside the anonymous struct or
4743  // union, but which actually declares a type outside of the
4744  // anonymous struct or union. It's okay.
4745  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4746  if (!MemRecord->isAnonymousStructOrUnion() &&
4747  MemRecord->getDeclName()) {
4748  // Visual C++ allows type definition in anonymous struct or union.
4749  if (getLangOpts().MicrosoftExt)
4750  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4751  << Record->isUnion();
4752  else {
4753  // This is a nested type declaration.
4754  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4755  << Record->isUnion();
4756  Invalid = true;
4757  }
4758  } else {
4759  // This is an anonymous type definition within another anonymous type.
4760  // This is a popular extension, provided by Plan9, MSVC and GCC, but
4761  // not part of standard C++.
4762  Diag(MemRecord->getLocation(),
4763  diag::ext_anonymous_record_with_anonymous_type)
4764  << Record->isUnion();
4765  }
4766  } else if (isa<AccessSpecDecl>(Mem)) {
4767  // Any access specifier is fine.
4768  } else if (isa<StaticAssertDecl>(Mem)) {
4769  // In C++1z, static_assert declarations are also fine.
4770  } else {
4771  // We have something that isn't a non-static data
4772  // member. Complain about it.
4773  unsigned DK = diag::err_anonymous_record_bad_member;
4774  if (isa<TypeDecl>(Mem))
4775  DK = diag::err_anonymous_record_with_type;
4776  else if (isa<FunctionDecl>(Mem))
4777  DK = diag::err_anonymous_record_with_function;
4778  else if (isa<VarDecl>(Mem))
4779  DK = diag::err_anonymous_record_with_static;
4780 
4781  // Visual C++ allows type definition in anonymous struct or union.
4782  if (getLangOpts().MicrosoftExt &&
4783  DK == diag::err_anonymous_record_with_type)
4784  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4785  << Record->isUnion();
4786  else {
4787  Diag(Mem->getLocation(), DK) << Record->isUnion();
4788  Invalid = true;
4789  }
4790  }
4791  }
4792 
4793  // C++11 [class.union]p8 (DR1460):
4794  // At most one variant member of a union may have a
4795  // brace-or-equal-initializer.
4796  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4797  Owner->isRecord())
4798  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4799  cast<CXXRecordDecl>(Record));
4800  }
4801 
4802  if (!Record->isUnion() && !Owner->isRecord()) {
4803  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4804  << getLangOpts().CPlusPlus;
4805  Invalid = true;
4806  }
4807 
4808  // Mock up a declarator.
4810  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4811  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4812 
4813  // Create a declaration for this anonymous struct/union.
4814  NamedDecl *Anon = nullptr;
4815  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4816  Anon = FieldDecl::Create(
4817  Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4818  /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4819  /*BitWidth=*/nullptr, /*Mutable=*/false,
4820  /*InitStyle=*/ICIS_NoInit);
4821  Anon->setAccess(AS);
4822  if (getLangOpts().CPlusPlus)
4823  FieldCollector->Add(cast<FieldDecl>(Anon));
4824  } else {
4825  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4827  if (SCSpec == DeclSpec::SCS_mutable) {
4828  // mutable can only appear on non-static class members, so it's always
4829  // an error here
4830  Diag(Record->getLocation(), diag::err_mutable_nonmember);
4831  Invalid = true;
4832  SC = SC_None;
4833  }
4834 
4835  Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4836  Record->getLocation(), /*IdentifierInfo=*/nullptr,
4837  Context.getTypeDeclType(Record), TInfo, SC);
4838 
4839  // Default-initialize the implicit variable. This initialization will be
4840  // trivial in almost all cases, except if a union member has an in-class
4841  // initializer:
4842  // union { int n = 0; };
4843  ActOnUninitializedDecl(Anon);
4844  }
4845  Anon->setImplicit();
4846 
4847  // Mark this as an anonymous struct/union type.
4848  Record->setAnonymousStructOrUnion(true);
4849 
4850  // Add the anonymous struct/union object to the current
4851  // context. We'll be referencing this object when we refer to one of
4852  // its members.
4853  Owner->addDecl(Anon);
4854 
4855  // Inject the members of the anonymous struct/union into the owning
4856  // context and into the identifier resolver chain for name lookup
4857  // purposes.
4859  Chain.push_back(Anon);
4860 
4861  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4862  Invalid = true;
4863 
4864  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4865  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4866  Decl *ManglingContextDecl;
4867  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4868  NewVD->getDeclContext(), ManglingContextDecl)) {
4869  Context.setManglingNumber(
4870  NewVD, MCtx->getManglingNumber(
4871  NewVD, getMSManglingNumber(getLangOpts(), S)));
4872  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4873  }
4874  }
4875  }
4876 
4877  if (Invalid)
4878  Anon->setInvalidDecl();
4879 
4880  return Anon;
4881 }
4882 
4883 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4884 /// Microsoft C anonymous structure.
4885 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4886 /// Example:
4887 ///
4888 /// struct A { int a; };
4889 /// struct B { struct A; int b; };
4890 ///
4891 /// void foo() {
4892 /// B var;
4893 /// var.a = 3;
4894 /// }
4895 ///
4897  RecordDecl *Record) {
4898  assert(Record && "expected a record!");
4899 
4900  // Mock up a declarator.
4902  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4903  assert(TInfo && "couldn't build declarator info for anonymous struct");
4904 
4905  auto *ParentDecl = cast<RecordDecl>(CurContext);
4906  QualType RecTy = Context.getTypeDeclType(Record);
4907 
4908  // Create a declaration for this anonymous struct.
4909  NamedDecl *Anon =
4910  FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4911  /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4912  /*BitWidth=*/nullptr, /*Mutable=*/false,
4913  /*InitStyle=*/ICIS_NoInit);
4914  Anon->setImplicit();
4915 
4916  // Add the anonymous struct object to the current context.
4917  CurContext->addDecl(Anon);
4918 
4919  // Inject the members of the anonymous struct into the current
4920  // context and into the identifier resolver chain for name lookup
4921  // purposes.
4923  Chain.push_back(Anon);
4924 
4925  RecordDecl *RecordDef = Record->getDefinition();
4926  if (RequireCompleteType(Anon->getLocation(), RecTy,
4927  diag::err_field_incomplete) ||
4928  InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4929  AS_none, Chain)) {
4930  Anon->setInvalidDecl();
4931  ParentDecl->setInvalidDecl();
4932  }
4933 
4934  return Anon;
4935 }
4936 
4937 /// GetNameForDeclarator - Determine the full declaration name for the
4938 /// given Declarator.
4940  return GetNameFromUnqualifiedId(D.getName());
4941 }
4942 
4943 /// Retrieves the declaration name from a parsed unqualified-id.
4946  DeclarationNameInfo NameInfo;
4947  NameInfo.setLoc(Name.StartLocation);
4948 
4949  switch (Name.getKind()) {
4950 
4953  NameInfo.setName(Name.Identifier);
4954  return NameInfo;
4955 
4957  // C++ [temp.deduct.guide]p3:
4958  // The simple-template-id shall name a class template specialization.
4959  // The template-name shall be the same identifier as the template-name
4960  // of the simple-template-id.
4961  // These together intend to imply that the template-name shall name a
4962  // class template.
4963  // FIXME: template<typename T> struct X {};
4964  // template<typename T> using Y = X<T>;
4965  // Y(int) -> Y<int>;
4966  // satisfies these rules but does not name a class template.
4967  TemplateName TN = Name.TemplateName.get().get();
4968  auto *Template = TN.getAsTemplateDecl();
4969  if (!Template || !isa<ClassTemplateDecl>(Template)) {
4970  Diag(Name.StartLocation,
4971  diag::err_deduction_guide_name_not_class_template)
4972  << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4973  if (Template)
4974  Diag(Template->getLocation(), diag::note_template_decl_here);
4975  return DeclarationNameInfo();
4976  }
4977 
4978  NameInfo.setName(
4979  Context.DeclarationNames.getCXXDeductionGuideName(Template));
4980  return NameInfo;
4981  }
4982 
4984  NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4989  = Name.EndLocation.getRawEncoding();
4990  return NameInfo;
4991 
4994  Name.Identifier));
4996  return NameInfo;
4997 
4999  TypeSourceInfo *TInfo;
5000  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5001  if (Ty.isNull())
5002  return DeclarationNameInfo();
5004  Context.getCanonicalType(Ty)));
5005  NameInfo.setNamedTypeInfo(TInfo);
5006  return NameInfo;
5007  }
5008 
5010  TypeSourceInfo *TInfo;
5011  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5012  if (Ty.isNull())
5013  return DeclarationNameInfo();
5015  Context.getCanonicalType(Ty)));
5016  NameInfo.setNamedTypeInfo(TInfo);
5017  return NameInfo;
5018  }
5019 
5021  // In well-formed code, we can only have a constructor
5022  // template-id that refers to the current context, so go there
5023  // to find the actual type being constructed.
5024  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5025  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5026  return DeclarationNameInfo();
5027 
5028  // Determine the type of the class being constructed.
5029  QualType CurClassType = Context.getTypeDeclType(CurClass);
5030 
5031  // FIXME: Check two things: that the template-id names the same type as
5032  // CurClassType, and that the template-id does not occur when the name
5033  // was qualified.
5034 
5036  Context.getCanonicalType(CurClassType)));
5037  // FIXME: should we retrieve TypeSourceInfo?
5038  NameInfo.setNamedTypeInfo(nullptr);
5039  return NameInfo;
5040  }
5041 
5043  TypeSourceInfo *TInfo;
5044  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5045  if (Ty.isNull())
5046  return DeclarationNameInfo();
5048  Context.getCanonicalType(Ty)));
5049  NameInfo.setNamedTypeInfo(TInfo);
5050  return NameInfo;
5051  }
5052 
5054  TemplateName TName = Name.TemplateId->Template.get();
5055  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5056  return Context.getNameForTemplate(TName, TNameLoc);
5057  }
5058 
5059  } // switch (Name.getKind())
5060 
5061  llvm_unreachable("Unknown name kind");
5062 }
5063 
5065  do {
5066  if (Ty->isPointerType() || Ty->isReferenceType())
5067  Ty = Ty->getPointeeType();
5068  else if (Ty->isArrayType())
5069  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5070  else
5071  return Ty.withoutLocalFastQualifiers();
5072  } while (true);
5073 }
5074 
5075 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5076 /// and Definition have "nearly" matching parameters. This heuristic is
5077 /// used to improve diagnostics in the case where an out-of-line function
5078 /// definition doesn't match any declaration within the class or namespace.
5079 /// Also sets Params to the list of indices to the parameters that differ
5080 /// between the declaration and the definition. If hasSimilarParameters
5081 /// returns true and Params is empty, then all of the parameters match.
5082 static bool hasSimilarParameters(ASTContext &Context,
5083  FunctionDecl *Declaration,
5084  FunctionDecl *Definition,
5085  SmallVectorImpl<unsigned> &Params) {
5086  Params.clear();
5087  if (Declaration->param_size() != Definition->param_size())
5088  return false;
5089  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5090  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5091  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5092 
5093  // The parameter types are identical
5094  if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5095  continue;
5096 
5097  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5098  QualType DefParamBaseTy = getCoreType(DefParamTy);
5099  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5100  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5101 
5102  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5103  (DeclTyName && DeclTyName == DefTyName))
5104  Params.push_back(Idx);
5105  else // The two parameters aren't even close
5106  return false;
5107  }
5108 
5109  return true;
5110 }
5111 
5112 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5113 /// declarator needs to be rebuilt in the current instantiation.
5114 /// Any bits of declarator which appear before the name are valid for
5115 /// consideration here. That's specifically the type in the decl spec
5116 /// and the base type in any member-pointer chunks.
5118  DeclarationName Name) {
5119  // The types we specifically need to rebuild are:
5120  // - typenames, typeofs, and decltypes
5121  // - types which will become injected class names
5122  // Of course, we also need to rebuild any type referencing such a
5123  // type. It's safest to just say "dependent", but we call out a
5124  // few cases here.
5125 
5126  DeclSpec &DS = D.getMutableDeclSpec();
5127  switch (DS.getTypeSpecType()) {
5131  case DeclSpec::TST_atomic: {
5132  // Grab the type from the parser.
5133  TypeSourceInfo *TSI = nullptr;
5134  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5135  if (T.isNull() || !T->isDependentType()) break;
5136 
5137  // Make sure there's a type source info. This isn't really much
5138  // of a waste; most dependent types should have type source info
5139  // attached already.
5140  if (!TSI)
5142 
5143  // Rebuild the type in the current instantiation.
5144  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5145  if (!TSI) return true;
5146 
5147  // Store the new type back in the decl spec.
5148  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5149  DS.UpdateTypeRep(LocType);
5150  break;
5151  }
5152 
5154  case DeclSpec::TST_typeofExpr: {
5155  Expr *E = DS.getRepAsExpr();
5157  if (Result.isInvalid()) return true;
5158  DS.UpdateExprRep(Result.get());
5159  break;
5160  }
5161 
5162  default:
5163  // Nothing to do for these decl specs.
5164  break;
5165  }
5166 
5167  // It doesn't matter what order we do this in.
5168  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5169  DeclaratorChunk &Chunk = D.getTypeObject(I);
5170 
5171  // The only type information in the declarator which can come
5172  // before the declaration name is the base type of a member
5173  // pointer.
5174  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5175  continue;
5176 
5177  // Rebuild the scope specifier in-place.
5178  CXXScopeSpec &SS = Chunk.Mem.Scope();
5180  return true;
5181  }
5182 
5183  return false;
5184 }
5185 
5188  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5189 
5190  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5191  Dcl && Dcl->getDeclContext()->isFileContext())
5193 
5194  if (getLangOpts().OpenCL)
5195  setCurrentOpenCLExtensionForDecl(Dcl);
5196 
5197  return Dcl;
5198 }
5199 
5200 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5201 /// If T is the name of a class, then each of the following shall have a
5202 /// name different from T:
5203 /// - every static data member of class T;
5204 /// - every member function of class T
5205 /// - every member of class T that is itself a type;
5206 /// \returns true if the declaration name violates these rules.
5208  DeclarationNameInfo NameInfo) {
5209  DeclarationName Name = NameInfo.getName();
5210 
5211  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5212  while (Record && Record->isAnonymousStructOrUnion())
5213  Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5214  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5215  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5216  return true;
5217  }
5218 
5219  return false;
5220 }
5221 
5222 /// Diagnose a declaration whose declarator-id has the given
5223 /// nested-name-specifier.
5224 ///
5225 /// \param SS The nested-name-specifier of the declarator-id.
5226 ///
5227 /// \param DC The declaration context to which the nested-name-specifier
5228 /// resolves.
5229 ///
5230 /// \param Name The name of the entity being declared.
5231 ///
5232 /// \param Loc The location of the name of the entity being declared.
5233 ///
5234 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5235 /// we're declaring an explicit / partial specialization / instantiation.
5236 ///
5237 /// \returns true if we cannot safely recover from this error, false otherwise.
5239  DeclarationName Name,
5240  SourceLocation Loc, bool IsTemplateId) {
5241  DeclContext *Cur = CurContext;
5242  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5243  Cur = Cur->getParent();
5244 
5245  // If the user provided a superfluous scope specifier that refers back to the
5246  // class in which the entity is already declared, diagnose and ignore it.
5247  //
5248  // class X {
5249  // void X::f();
5250  // };
5251  //
5252  // Note, it was once ill-formed to give redundant qualification in all
5253  // contexts, but that rule was removed by DR482.
5254  if (Cur->Equals(DC)) {
5255  if (Cur->isRecord()) {
5256  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5257  : diag::err_member_extra_qualification)
5258  << Name << FixItHint::CreateRemoval(SS.getRange());
5259  SS.clear();
5260  } else {
5261  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5262  }
5263  return false;
5264  }
5265 
5266  // Check whether the qualifying scope encloses the scope of the original
5267  // declaration. For a template-id, we perform the checks in
5268  // CheckTemplateSpecializationScope.
5269  if (!Cur->Encloses(DC) && !IsTemplateId) {
5270  if (Cur->isRecord())
5271  Diag(Loc, diag::err_member_qualification)
5272  << Name << SS.getRange();
5273  else if (isa<TranslationUnitDecl>(DC))
5274  Diag(Loc, diag::err_invalid_declarator_global_scope)
5275  << Name << SS.getRange();
5276  else if (isa<FunctionDecl>(Cur))
5277  Diag(Loc, diag::err_invalid_declarator_in_function)
5278  << Name << SS.getRange();
5279  else if (isa<BlockDecl>(Cur))
5280  Diag(Loc, diag::err_invalid_declarator_in_block)
5281  << Name << SS.getRange();
5282  else
5283  Diag(Loc, diag::err_invalid_declarator_scope)
5284  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5285 
5286  return true;
5287  }
5288 
5289  if (Cur->isRecord()) {
5290  // Cannot qualify members within a class.
5291  Diag(Loc, diag::err_member_qualification)
5292  << Name << SS.getRange();
5293  SS.clear();
5294 
5295  // C++ constructors and destructors with incorrect scopes can break
5296  // our AST invariants by having the wrong underlying types. If
5297  // that's the case, then drop this declaration entirely.
5300  !Context.hasSameType(Name.getCXXNameType(),
5301  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5302  return true;
5303 
5304  return false;
5305  }
5306 
5307  // C++11 [dcl.meaning]p1:
5308  // [...] "The nested-name-specifier of the qualified declarator-id shall
5309  // not begin with a decltype-specifer"
5310  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5311  while (SpecLoc.getPrefix())
5312  SpecLoc = SpecLoc.getPrefix();
5313  if (dyn_cast_or_null<DecltypeType>(
5314  SpecLoc.getNestedNameSpecifier()->getAsType()))
5315  Diag(Loc, diag::err_decltype_in_declarator)
5316  << SpecLoc.getTypeLoc().getSourceRange();
5317 
5318  return false;
5319 }
5320 
5322  MultiTemplateParamsArg TemplateParamLists) {
5323  // TODO: consider using NameInfo for diagnostic.
5324  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5325  DeclarationName Name = NameInfo.getName();
5326 
5327  // All of these full declarators require an identifier. If it doesn't have
5328  // one, the ParsedFreeStandingDeclSpec action should be used.
5329  if (D.isDecompositionDeclarator()) {
5330  return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5331  } else if (!Name) {
5332  if (!D.isInvalidType()) // Reject this if we think it is valid.
5333  Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5334  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5335  return nullptr;
5336  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5337  return nullptr;
5338 
5339  // The scope passed in may not be a decl scope. Zip up the scope tree until
5340  // we find one that is.
5341  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5342  (S->getFlags() & Scope::TemplateParamScope) != 0)
5343  S = S->getParent();
5344 
5345  DeclContext *DC = CurContext;
5346  if (D.getCXXScopeSpec().isInvalid())
5347  D.setInvalidType();
5348  else if (D.getCXXScopeSpec().isSet()) {
5349  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5350  UPPC_DeclarationQualifier))
5351  return nullptr;
5352 
5353  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5354  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5355  if (!DC || isa<EnumDecl>(DC)) {
5356  // If we could not compute the declaration context, it's because the
5357  // declaration context is dependent but does not refer to a class,
5358  // class template, or class template partial specialization. Complain
5359  // and return early, to avoid the coming semantic disaster.
5360  Diag(D.getIdentifierLoc(),
5361  diag::err_template_qualified_declarator_no_match)
5362  << D.getCXXScopeSpec().getScopeRep()
5363  << D.getCXXScopeSpec().getRange();
5364  return nullptr;
5365  }
5366  bool IsDependentContext = DC->isDependentContext();
5367 
5368  if (!IsDependentContext &&
5369  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5370  return nullptr;
5371 
5372  // If a class is incomplete, do not parse entities inside it.
5373  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5374  Diag(D.getIdentifierLoc(),
5375  diag::err_member_def_undefined_record)
5376  << Name << DC << D.getCXXScopeSpec().getRange();
5377  return nullptr;
5378  }
5379  if (!D.getDeclSpec().isFriendSpecified()) {
5380  if (diagnoseQualifiedDeclaration(
5381  D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5383  if (DC->isRecord())
5384  return nullptr;
5385 
5386  D.setInvalidType();
5387  }
5388  }
5389 
5390  // Check whether we need to rebuild the type of the given
5391  // declaration in the current instantiation.
5392  if (EnteringContext && IsDependentContext &&
5393  TemplateParamLists.size() != 0) {
5394  ContextRAII SavedContext(*this, DC);
5395  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5396  D.setInvalidType();
5397  }
5398  }
5399 
5400  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5401  QualType R = TInfo->getType();
5402 
5403  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5404  UPPC_DeclarationType))
5405  D.setInvalidType();
5406 
5407  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5408  forRedeclarationInCurContext());
5409 
5410  // See if this is a redefinition of a variable in the same scope.
5411  if (!D.getCXXScopeSpec().isSet()) {
5412  bool IsLinkageLookup = false;
5413  bool CreateBuiltins = false;
5414 
5415  // If the declaration we're planning to build will be a function
5416  // or object with linkage, then look for another declaration with
5417  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5418  //
5419  // If the declaration we're planning to build will be declared with
5420  // external linkage in the translation unit, create any builtin with
5421  // the same name.
5423  /* Do nothing*/;
5424  else if (CurContext->isFunctionOrMethod() &&
5426  R->isFunctionType())) {
5427  IsLinkageLookup = true;
5428  CreateBuiltins =
5429  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5430  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5432  CreateBuiltins = true;
5433 
5434  if (IsLinkageLookup) {
5435  Previous.clear(LookupRedeclarationWithLinkage);
5436  Previous.setRedeclarationKind(ForExternalRedeclaration);
5437  }
5438 
5439  LookupName(Previous, S, CreateBuiltins);
5440  } else { // Something like "int foo::x;"
5441  LookupQualifiedName(Previous, DC);
5442 
5443  // C++ [dcl.meaning]p1:
5444  // When the declarator-id is qualified, the declaration shall refer to a
5445  // previously declared member of the class or namespace to which the
5446  // qualifier refers (or, in the case of a namespace, of an element of the
5447  // inline namespace set of that namespace (7.3.1)) or to a specialization
5448  // thereof; [...]
5449  //
5450  // Note that we already checked the context above, and that we do not have
5451  // enough information to make sure that Previous contains the declaration
5452  // we want to match. For example, given:
5453  //
5454  // class X {
5455  // void f();
5456  // void f(float);
5457  // };
5458  //
5459  // void X::f(int) { } // ill-formed
5460  //
5461  // In this case, Previous will point to the overload set
5462  // containing the two f's declared in X, but neither of them
5463  // matches.
5464 
5465  // C++ [dcl.meaning]p1:
5466  // [...] the member shall not merely have been introduced by a
5467  // using-declaration in the scope of the class or namespace nominated by
5468  // the nested-name-specifier of the declarator-id.
5469  RemoveUsingDecls(Previous);
5470  }
5471 
5472  if (Previous.isSingleResult() &&
5473  Previous.getFoundDecl()->isTemplateParameter()) {
5474  // Maybe we will complain about the shadowed template parameter.
5475  if (!D.isInvalidType())
5476  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5477  Previous.getFoundDecl());
5478 
5479  // Just pretend that we didn't see the previous declaration.
5480  Previous.clear();
5481  }
5482 
5483  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5484  // Forget that the previous declaration is the injected-class-name.
5485  Previous.clear();
5486 
5487  // In C++, the previous declaration we find might be a tag type
5488  // (class or enum). In this case, the new declaration will hide the
5489  // tag type. Note that this applies to functions, function templates, and
5490  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5491  if (Previous.isSingleTagDecl() &&
5493  (TemplateParamLists.size() == 0 || R->isFunctionType()))
5494  Previous.clear();
5495 
5496  // Check that there are no default arguments other than in the parameters
5497  // of a function declaration (C++ only).
5498  if (getLangOpts().CPlusPlus)
5499  CheckExtraCXXDefaultArguments(D);
5500 
5501  NamedDecl *New;
5502 
5503  bool AddToScope = true;
5504  if