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