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