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