xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision a03411e84728e9b267056fd31c7d1d9d1dc1b01e)
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"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/TargetParser/Triple.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <functional>
54 #include <optional>
55 #include <unordered_map>
56 
57 using namespace clang;
58 using namespace sema;
59 
60 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
61   if (OwnedType) {
62     Decl *Group[2] = { OwnedType, Ptr };
63     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
64   }
65 
66   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
67 }
68 
69 namespace {
70 
71 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
72  public:
73    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
74                         bool AllowTemplates = false,
75                         bool AllowNonTemplates = true)
76        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
77          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
78      WantExpressionKeywords = false;
79      WantCXXNamedCasts = false;
80      WantRemainingKeywords = false;
81   }
82 
83   bool ValidateCandidate(const TypoCorrection &candidate) override {
84     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
85       if (!AllowInvalidDecl && ND->isInvalidDecl())
86         return false;
87 
88       if (getAsTypeTemplateDecl(ND))
89         return AllowTemplates;
90 
91       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
92       if (!IsType)
93         return false;
94 
95       if (AllowNonTemplates)
96         return true;
97 
98       // An injected-class-name of a class template (specialization) is valid
99       // as a template or as a non-template.
100       if (AllowTemplates) {
101         auto *RD = dyn_cast<CXXRecordDecl>(ND);
102         if (!RD || !RD->isInjectedClassName())
103           return false;
104         RD = cast<CXXRecordDecl>(RD->getDeclContext());
105         return RD->getDescribedClassTemplate() ||
106                isa<ClassTemplateSpecializationDecl>(RD);
107       }
108 
109       return false;
110     }
111 
112     return !WantClassName && candidate.isKeyword();
113   }
114 
115   std::unique_ptr<CorrectionCandidateCallback> clone() override {
116     return std::make_unique<TypeNameValidatorCCC>(*this);
117   }
118 
119  private:
120   bool AllowInvalidDecl;
121   bool WantClassName;
122   bool AllowTemplates;
123   bool AllowNonTemplates;
124 };
125 
126 } // end anonymous namespace
127 
128 /// Determine whether the token kind starts a simple-type-specifier.
129 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
130   switch (Kind) {
131   // FIXME: Take into account the current language when deciding whether a
132   // token kind is a valid type specifier
133   case tok::kw_short:
134   case tok::kw_long:
135   case tok::kw___int64:
136   case tok::kw___int128:
137   case tok::kw_signed:
138   case tok::kw_unsigned:
139   case tok::kw_void:
140   case tok::kw_char:
141   case tok::kw_int:
142   case tok::kw_half:
143   case tok::kw_float:
144   case tok::kw_double:
145   case tok::kw___bf16:
146   case tok::kw__Float16:
147   case tok::kw___float128:
148   case tok::kw___ibm128:
149   case tok::kw_wchar_t:
150   case tok::kw_bool:
151 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152 #include "clang/Basic/TransformTypeTraits.def"
153   case tok::kw___auto_type:
154     return true;
155 
156   case tok::annot_typename:
157   case tok::kw_char16_t:
158   case tok::kw_char32_t:
159   case tok::kw_typeof:
160   case tok::annot_decltype:
161   case tok::kw_decltype:
162     return getLangOpts().CPlusPlus;
163 
164   case tok::kw_char8_t:
165     return getLangOpts().Char8;
166 
167   default:
168     break;
169   }
170 
171   return false;
172 }
173 
174 namespace {
175 enum class UnqualifiedTypeNameLookupResult {
176   NotFound,
177   FoundNonType,
178   FoundType
179 };
180 } // end anonymous namespace
181 
182 /// Tries to perform unqualified lookup of the type decls in bases for
183 /// dependent class.
184 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185 /// type decl, \a FoundType if only type decls are found.
186 static UnqualifiedTypeNameLookupResult
187 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
188                                 SourceLocation NameLoc,
189                                 const CXXRecordDecl *RD) {
190   if (!RD->hasDefinition())
191     return UnqualifiedTypeNameLookupResult::NotFound;
192   // Look for type decls in base classes.
193   UnqualifiedTypeNameLookupResult FoundTypeDecl =
194       UnqualifiedTypeNameLookupResult::NotFound;
195   for (const auto &Base : RD->bases()) {
196     const CXXRecordDecl *BaseRD = nullptr;
197     if (auto *BaseTT = Base.getType()->getAs<TagType>())
198       BaseRD = BaseTT->getAsCXXRecordDecl();
199     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
200       // Look for type decls in dependent base classes that have known primary
201       // templates.
202       if (!TST || !TST->isDependentType())
203         continue;
204       auto *TD = TST->getTemplateName().getAsTemplateDecl();
205       if (!TD)
206         continue;
207       if (auto *BasePrimaryTemplate =
208           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
209         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
210           BaseRD = BasePrimaryTemplate;
211         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
212           if (const ClassTemplatePartialSpecializationDecl *PS =
213                   CTD->findPartialSpecialization(Base.getType()))
214             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
215               BaseRD = PS;
216         }
217       }
218     }
219     if (BaseRD) {
220       for (NamedDecl *ND : BaseRD->lookup(&II)) {
221         if (!isa<TypeDecl>(ND))
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224       }
225       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
226         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
227         case UnqualifiedTypeNameLookupResult::FoundNonType:
228           return UnqualifiedTypeNameLookupResult::FoundNonType;
229         case UnqualifiedTypeNameLookupResult::FoundType:
230           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
231           break;
232         case UnqualifiedTypeNameLookupResult::NotFound:
233           break;
234         }
235       }
236     }
237   }
238 
239   return FoundTypeDecl;
240 }
241 
242 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
243                                                       const IdentifierInfo &II,
244                                                       SourceLocation NameLoc) {
245   // Lookup in the parent class template context, if any.
246   const CXXRecordDecl *RD = nullptr;
247   UnqualifiedTypeNameLookupResult FoundTypeDecl =
248       UnqualifiedTypeNameLookupResult::NotFound;
249   for (DeclContext *DC = S.CurContext;
250        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
251        DC = DC->getParent()) {
252     // Look for type decls in dependent base classes that have known primary
253     // templates.
254     RD = dyn_cast<CXXRecordDecl>(DC);
255     if (RD && RD->getDescribedClassTemplate())
256       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
257   }
258   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259     return nullptr;
260 
261   // We found some types in dependent base classes.  Recover as if the user
262   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
263   // lookup during template instantiation.
264   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
265 
266   ASTContext &Context = S.Context;
267   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
268                                           cast<Type>(Context.getRecordType(RD)));
269   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
270 
271   CXXScopeSpec SS;
272   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
273 
274   TypeLocBuilder Builder;
275   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
276   DepTL.setNameLoc(NameLoc);
277   DepTL.setElaboratedKeywordLoc(SourceLocation());
278   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
279   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
280 }
281 
282 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
283 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
284                                  SourceLocation NameLoc,
285                                  bool WantNontrivialTypeSourceInfo = true) {
286   switch (T->getTypeClass()) {
287   case Type::DeducedTemplateSpecialization:
288   case Type::Enum:
289   case Type::InjectedClassName:
290   case Type::Record:
291   case Type::Typedef:
292   case Type::UnresolvedUsing:
293   case Type::Using:
294     break;
295   // These can never be qualified so an ElaboratedType node
296   // would carry no additional meaning.
297   case Type::ObjCInterface:
298   case Type::ObjCTypeParam:
299   case Type::TemplateTypeParm:
300     return ParsedType::make(T);
301   default:
302     llvm_unreachable("Unexpected Type Class");
303   }
304 
305   if (!SS || SS->isEmpty())
306     return ParsedType::make(
307         S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
308 
309   QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
310   if (!WantNontrivialTypeSourceInfo)
311     return ParsedType::make(ElTy);
312 
313   TypeLocBuilder Builder;
314   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
315   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
316   ElabTL.setElaboratedKeywordLoc(SourceLocation());
317   ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
318   return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
319 }
320 
321 /// If the identifier refers to a type name within this scope,
322 /// return the declaration of that type.
323 ///
324 /// This routine performs ordinary name lookup of the identifier II
325 /// within the given scope, with optional C++ scope specifier SS, to
326 /// determine whether the name refers to a type. If so, returns an
327 /// opaque pointer (actually a QualType) corresponding to that
328 /// type. Otherwise, returns NULL.
329 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
330                              Scope *S, CXXScopeSpec *SS, bool isClassName,
331                              bool HasTrailingDot, ParsedType ObjectTypePtr,
332                              bool IsCtorOrDtorName,
333                              bool WantNontrivialTypeSourceInfo,
334                              bool IsClassTemplateDeductionContext,
335                              ImplicitTypenameContext AllowImplicitTypename,
336                              IdentifierInfo **CorrectedII) {
337   // FIXME: Consider allowing this outside C++1z mode as an extension.
338   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
339                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
340                               !isClassName && !HasTrailingDot;
341 
342   // Determine where we will perform name lookup.
343   DeclContext *LookupCtx = nullptr;
344   if (ObjectTypePtr) {
345     QualType ObjectType = ObjectTypePtr.get();
346     if (ObjectType->isRecordType())
347       LookupCtx = computeDeclContext(ObjectType);
348   } else if (SS && SS->isNotEmpty()) {
349     LookupCtx = computeDeclContext(*SS, false);
350 
351     if (!LookupCtx) {
352       if (isDependentScopeSpecifier(*SS)) {
353         // C++ [temp.res]p3:
354         //   A qualified-id that refers to a type and in which the
355         //   nested-name-specifier depends on a template-parameter (14.6.2)
356         //   shall be prefixed by the keyword typename to indicate that the
357         //   qualified-id denotes a type, forming an
358         //   elaborated-type-specifier (7.1.5.3).
359         //
360         // We therefore do not perform any name lookup if the result would
361         // refer to a member of an unknown specialization.
362         // In C++2a, in several contexts a 'typename' is not required. Also
363         // allow this as an extension.
364         if (AllowImplicitTypename == ImplicitTypenameContext::No &&
365             !isClassName && !IsCtorOrDtorName)
366           return nullptr;
367         bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
368         if (IsImplicitTypename) {
369           SourceLocation QualifiedLoc = SS->getRange().getBegin();
370           if (getLangOpts().CPlusPlus20)
371             Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
372           else
373             Diag(QualifiedLoc, diag::ext_implicit_typename)
374                 << SS->getScopeRep() << II.getName()
375                 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
376         }
377 
378         // We know from the grammar that this name refers to a type,
379         // so build a dependent node to describe the type.
380         if (WantNontrivialTypeSourceInfo)
381           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
382                                    (ImplicitTypenameContext)IsImplicitTypename)
383               .get();
384 
385         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
386         QualType T =
387             CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
388                               SourceLocation(), QualifierLoc, II, NameLoc);
389         return ParsedType::make(T);
390       }
391 
392       return nullptr;
393     }
394 
395     if (!LookupCtx->isDependentContext() &&
396         RequireCompleteDeclContext(*SS, LookupCtx))
397       return nullptr;
398   }
399 
400   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
401   // lookup for class-names.
402   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
403                                       LookupOrdinaryName;
404   LookupResult Result(*this, &II, NameLoc, Kind);
405   if (LookupCtx) {
406     // Perform "qualified" name lookup into the declaration context we
407     // computed, which is either the type of the base of a member access
408     // expression or the declaration context associated with a prior
409     // nested-name-specifier.
410     LookupQualifiedName(Result, LookupCtx);
411 
412     if (ObjectTypePtr && Result.empty()) {
413       // C++ [basic.lookup.classref]p3:
414       //   If the unqualified-id is ~type-name, the type-name is looked up
415       //   in the context of the entire postfix-expression. If the type T of
416       //   the object expression is of a class type C, the type-name is also
417       //   looked up in the scope of class C. At least one of the lookups shall
418       //   find a name that refers to (possibly cv-qualified) T.
419       LookupName(Result, S);
420     }
421   } else {
422     // Perform unqualified name lookup.
423     LookupName(Result, S);
424 
425     // For unqualified lookup in a class template in MSVC mode, look into
426     // dependent base classes where the primary class template is known.
427     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
428       if (ParsedType TypeInBase =
429               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
430         return TypeInBase;
431     }
432   }
433 
434   NamedDecl *IIDecl = nullptr;
435   UsingShadowDecl *FoundUsingShadow = nullptr;
436   switch (Result.getResultKind()) {
437   case LookupResult::NotFound:
438   case LookupResult::NotFoundInCurrentInstantiation:
439     if (CorrectedII) {
440       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
441                                AllowDeducedTemplate);
442       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
443                                               S, SS, CCC, CTK_ErrorRecovery);
444       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
445       TemplateTy Template;
446       bool MemberOfUnknownSpecialization;
447       UnqualifiedId TemplateName;
448       TemplateName.setIdentifier(NewII, NameLoc);
449       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
450       CXXScopeSpec NewSS, *NewSSPtr = SS;
451       if (SS && NNS) {
452         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
453         NewSSPtr = &NewSS;
454       }
455       if (Correction && (NNS || NewII != &II) &&
456           // Ignore a correction to a template type as the to-be-corrected
457           // identifier is not a template (typo correction for template names
458           // is handled elsewhere).
459           !(getLangOpts().CPlusPlus && NewSSPtr &&
460             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
461                            Template, MemberOfUnknownSpecialization))) {
462         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
463                                     isClassName, HasTrailingDot, ObjectTypePtr,
464                                     IsCtorOrDtorName,
465                                     WantNontrivialTypeSourceInfo,
466                                     IsClassTemplateDeductionContext);
467         if (Ty) {
468           diagnoseTypo(Correction,
469                        PDiag(diag::err_unknown_type_or_class_name_suggest)
470                          << Result.getLookupName() << isClassName);
471           if (SS && NNS)
472             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
473           *CorrectedII = NewII;
474           return Ty;
475         }
476       }
477     }
478     // If typo correction failed or was not performed, fall through
479     [[fallthrough]];
480   case LookupResult::FoundOverloaded:
481   case LookupResult::FoundUnresolvedValue:
482     Result.suppressDiagnostics();
483     return nullptr;
484 
485   case LookupResult::Ambiguous:
486     // Recover from type-hiding ambiguities by hiding the type.  We'll
487     // do the lookup again when looking for an object, and we can
488     // diagnose the error then.  If we don't do this, then the error
489     // about hiding the type will be immediately followed by an error
490     // that only makes sense if the identifier was treated like a type.
491     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
492       Result.suppressDiagnostics();
493       return nullptr;
494     }
495 
496     // Look to see if we have a type anywhere in the list of results.
497     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
498          Res != ResEnd; ++Res) {
499       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
500       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
501               RealRes) ||
502           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
503         if (!IIDecl ||
504             // Make the selection of the recovery decl deterministic.
505             RealRes->getLocation() < IIDecl->getLocation()) {
506           IIDecl = RealRes;
507           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
508         }
509       }
510     }
511 
512     if (!IIDecl) {
513       // None of the entities we found is a type, so there is no way
514       // to even assume that the result is a type. In this case, don't
515       // complain about the ambiguity. The parser will either try to
516       // perform this lookup again (e.g., as an object name), which
517       // will produce the ambiguity, or will complain that it expected
518       // a type name.
519       Result.suppressDiagnostics();
520       return nullptr;
521     }
522 
523     // We found a type within the ambiguous lookup; diagnose the
524     // ambiguity and then return that type. This might be the right
525     // answer, or it might not be, but it suppresses any attempt to
526     // perform the name lookup again.
527     break;
528 
529   case LookupResult::Found:
530     IIDecl = Result.getFoundDecl();
531     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
532     break;
533   }
534 
535   assert(IIDecl && "Didn't find decl");
536 
537   QualType T;
538   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
539     // C++ [class.qual]p2: A lookup that would find the injected-class-name
540     // instead names the constructors of the class, except when naming a class.
541     // This is ill-formed when we're not actually forming a ctor or dtor name.
542     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
543     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
544     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
545         FoundRD->isInjectedClassName() &&
546         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
547       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
548           << &II << /*Type*/1;
549 
550     DiagnoseUseOfDecl(IIDecl, NameLoc);
551 
552     T = Context.getTypeDeclType(TD);
553     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
554   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
555     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
556     if (!HasTrailingDot)
557       T = Context.getObjCInterfaceType(IDecl);
558     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
559   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
560     (void)DiagnoseUseOfDecl(UD, NameLoc);
561     // Recover with 'int'
562     return ParsedType::make(Context.IntTy);
563   } else if (AllowDeducedTemplate) {
564     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
565       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
566       TemplateName Template =
567           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
568       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
569                                                        false);
570       // Don't wrap in a further UsingType.
571       FoundUsingShadow = nullptr;
572     }
573   }
574 
575   if (T.isNull()) {
576     // If it's not plausibly a type, suppress diagnostics.
577     Result.suppressDiagnostics();
578     return nullptr;
579   }
580 
581   if (FoundUsingShadow)
582     T = Context.getUsingType(FoundUsingShadow, T);
583 
584   return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
585 }
586 
587 // Builds a fake NNS for the given decl context.
588 static NestedNameSpecifier *
589 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
590   for (;; DC = DC->getLookupParent()) {
591     DC = DC->getPrimaryContext();
592     auto *ND = dyn_cast<NamespaceDecl>(DC);
593     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
594       return NestedNameSpecifier::Create(Context, nullptr, ND);
595     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
596       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
597                                          RD->getTypeForDecl());
598     else if (isa<TranslationUnitDecl>(DC))
599       return NestedNameSpecifier::GlobalSpecifier(Context);
600   }
601   llvm_unreachable("something isn't in TU scope?");
602 }
603 
604 /// Find the parent class with dependent bases of the innermost enclosing method
605 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
606 /// up allowing unqualified dependent type names at class-level, which MSVC
607 /// correctly rejects.
608 static const CXXRecordDecl *
609 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
610   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
611     DC = DC->getPrimaryContext();
612     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
613       if (MD->getParent()->hasAnyDependentBases())
614         return MD->getParent();
615   }
616   return nullptr;
617 }
618 
619 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
620                                           SourceLocation NameLoc,
621                                           bool IsTemplateTypeArg) {
622   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
623 
624   NestedNameSpecifier *NNS = nullptr;
625   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
626     // If we weren't able to parse a default template argument, delay lookup
627     // until instantiation time by making a non-dependent DependentTypeName. We
628     // pretend we saw a NestedNameSpecifier referring to the current scope, and
629     // lookup is retried.
630     // FIXME: This hurts our diagnostic quality, since we get errors like "no
631     // type named 'Foo' in 'current_namespace'" when the user didn't write any
632     // name specifiers.
633     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
634     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
635   } else if (const CXXRecordDecl *RD =
636                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
637     // Build a DependentNameType that will perform lookup into RD at
638     // instantiation time.
639     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
640                                       RD->getTypeForDecl());
641 
642     // Diagnose that this identifier was undeclared, and retry the lookup during
643     // template instantiation.
644     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
645                                                                       << RD;
646   } else {
647     // This is not a situation that we should recover from.
648     return ParsedType();
649   }
650 
651   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
652 
653   // Build type location information.  We synthesized the qualifier, so we have
654   // to build a fake NestedNameSpecifierLoc.
655   NestedNameSpecifierLocBuilder NNSLocBuilder;
656   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
657   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
658 
659   TypeLocBuilder Builder;
660   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
661   DepTL.setNameLoc(NameLoc);
662   DepTL.setElaboratedKeywordLoc(SourceLocation());
663   DepTL.setQualifierLoc(QualifierLoc);
664   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
665 }
666 
667 /// isTagName() - This method is called *for error recovery purposes only*
668 /// to determine if the specified name is a valid tag name ("struct foo").  If
669 /// so, this returns the TST for the tag corresponding to it (TST_enum,
670 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
671 /// cases in C where the user forgot to specify the tag.
672 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
673   // Do a tag name lookup in this scope.
674   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
675   LookupName(R, S, false);
676   R.suppressDiagnostics();
677   if (R.getResultKind() == LookupResult::Found)
678     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
679       switch (TD->getTagKind()) {
680       case TTK_Struct: return DeclSpec::TST_struct;
681       case TTK_Interface: return DeclSpec::TST_interface;
682       case TTK_Union:  return DeclSpec::TST_union;
683       case TTK_Class:  return DeclSpec::TST_class;
684       case TTK_Enum:   return DeclSpec::TST_enum;
685       }
686     }
687 
688   return DeclSpec::TST_unspecified;
689 }
690 
691 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
692 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
693 /// then downgrade the missing typename error to a warning.
694 /// This is needed for MSVC compatibility; Example:
695 /// @code
696 /// template<class T> class A {
697 /// public:
698 ///   typedef int TYPE;
699 /// };
700 /// template<class T> class B : public A<T> {
701 /// public:
702 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
703 /// };
704 /// @endcode
705 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
706   if (CurContext->isRecord()) {
707     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
708       return true;
709 
710     const Type *Ty = SS->getScopeRep()->getAsType();
711 
712     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
713     for (const auto &Base : RD->bases())
714       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
715         return true;
716     return S->isFunctionPrototypeScope();
717   }
718   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
719 }
720 
721 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
722                                    SourceLocation IILoc,
723                                    Scope *S,
724                                    CXXScopeSpec *SS,
725                                    ParsedType &SuggestedType,
726                                    bool IsTemplateName) {
727   // Don't report typename errors for editor placeholders.
728   if (II->isEditorPlaceholder())
729     return;
730   // We don't have anything to suggest (yet).
731   SuggestedType = nullptr;
732 
733   // There may have been a typo in the name of the type. Look up typo
734   // results, in case we have something that we can suggest.
735   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
736                            /*AllowTemplates=*/IsTemplateName,
737                            /*AllowNonTemplates=*/!IsTemplateName);
738   if (TypoCorrection Corrected =
739           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
740                       CCC, CTK_ErrorRecovery)) {
741     // FIXME: Support error recovery for the template-name case.
742     bool CanRecover = !IsTemplateName;
743     if (Corrected.isKeyword()) {
744       // We corrected to a keyword.
745       diagnoseTypo(Corrected,
746                    PDiag(IsTemplateName ? diag::err_no_template_suggest
747                                         : diag::err_unknown_typename_suggest)
748                        << II);
749       II = Corrected.getCorrectionAsIdentifierInfo();
750     } else {
751       // We found a similarly-named type or interface; suggest that.
752       if (!SS || !SS->isSet()) {
753         diagnoseTypo(Corrected,
754                      PDiag(IsTemplateName ? diag::err_no_template_suggest
755                                           : diag::err_unknown_typename_suggest)
756                          << II, CanRecover);
757       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
758         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
759         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
760                                 II->getName().equals(CorrectedStr);
761         diagnoseTypo(Corrected,
762                      PDiag(IsTemplateName
763                                ? diag::err_no_member_template_suggest
764                                : diag::err_unknown_nested_typename_suggest)
765                          << II << DC << DroppedSpecifier << SS->getRange(),
766                      CanRecover);
767       } else {
768         llvm_unreachable("could not have corrected a typo here");
769       }
770 
771       if (!CanRecover)
772         return;
773 
774       CXXScopeSpec tmpSS;
775       if (Corrected.getCorrectionSpecifier())
776         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
777                           SourceRange(IILoc));
778       // FIXME: Support class template argument deduction here.
779       SuggestedType =
780           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
781                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
782                       /*IsCtorOrDtorName=*/false,
783                       /*WantNontrivialTypeSourceInfo=*/true);
784     }
785     return;
786   }
787 
788   if (getLangOpts().CPlusPlus && !IsTemplateName) {
789     // See if II is a class template that the user forgot to pass arguments to.
790     UnqualifiedId Name;
791     Name.setIdentifier(II, IILoc);
792     CXXScopeSpec EmptySS;
793     TemplateTy TemplateResult;
794     bool MemberOfUnknownSpecialization;
795     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
796                        Name, nullptr, true, TemplateResult,
797                        MemberOfUnknownSpecialization) == TNK_Type_template) {
798       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
799       return;
800     }
801   }
802 
803   // FIXME: Should we move the logic that tries to recover from a missing tag
804   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
805 
806   if (!SS || (!SS->isSet() && !SS->isInvalid()))
807     Diag(IILoc, IsTemplateName ? diag::err_no_template
808                                : diag::err_unknown_typename)
809         << II;
810   else if (DeclContext *DC = computeDeclContext(*SS, false))
811     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
812                                : diag::err_typename_nested_not_found)
813         << II << DC << SS->getRange();
814   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
815     SuggestedType =
816         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817   } else if (isDependentScopeSpecifier(*SS)) {
818     unsigned DiagID = diag::err_typename_missing;
819     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
820       DiagID = diag::ext_typename_missing;
821 
822     Diag(SS->getRange().getBegin(), DiagID)
823       << SS->getScopeRep() << II->getName()
824       << SourceRange(SS->getRange().getBegin(), IILoc)
825       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
826     SuggestedType = ActOnTypenameType(S, SourceLocation(),
827                                       *SS, *II, IILoc).get();
828   } else {
829     assert(SS && SS->isInvalid() &&
830            "Invalid scope specifier has already been diagnosed");
831   }
832 }
833 
834 /// Determine whether the given result set contains either a type name
835 /// or
836 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
837   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
838                        NextToken.is(tok::less);
839 
840   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
841     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
842       return true;
843 
844     if (CheckTemplate && isa<TemplateDecl>(*I))
845       return true;
846   }
847 
848   return false;
849 }
850 
851 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
852                                     Scope *S, CXXScopeSpec &SS,
853                                     IdentifierInfo *&Name,
854                                     SourceLocation NameLoc) {
855   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
856   SemaRef.LookupParsedName(R, S, &SS);
857   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
858     StringRef FixItTagName;
859     switch (Tag->getTagKind()) {
860       case TTK_Class:
861         FixItTagName = "class ";
862         break;
863 
864       case TTK_Enum:
865         FixItTagName = "enum ";
866         break;
867 
868       case TTK_Struct:
869         FixItTagName = "struct ";
870         break;
871 
872       case TTK_Interface:
873         FixItTagName = "__interface ";
874         break;
875 
876       case TTK_Union:
877         FixItTagName = "union ";
878         break;
879     }
880 
881     StringRef TagName = FixItTagName.drop_back();
882     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
883       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
884       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
885 
886     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
887          I != IEnd; ++I)
888       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
889         << Name << TagName;
890 
891     // Replace lookup results with just the tag decl.
892     Result.clear(Sema::LookupTagName);
893     SemaRef.LookupParsedName(Result, S, &SS);
894     return true;
895   }
896 
897   return false;
898 }
899 
900 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
901                                             IdentifierInfo *&Name,
902                                             SourceLocation NameLoc,
903                                             const Token &NextToken,
904                                             CorrectionCandidateCallback *CCC) {
905   DeclarationNameInfo NameInfo(Name, NameLoc);
906   ObjCMethodDecl *CurMethod = getCurMethodDecl();
907 
908   assert(NextToken.isNot(tok::coloncolon) &&
909          "parse nested name specifiers before calling ClassifyName");
910   if (getLangOpts().CPlusPlus && SS.isSet() &&
911       isCurrentClassName(*Name, S, &SS)) {
912     // Per [class.qual]p2, this names the constructors of SS, not the
913     // injected-class-name. We don't have a classification for that.
914     // There's not much point caching this result, since the parser
915     // will reject it later.
916     return NameClassification::Unknown();
917   }
918 
919   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
920   LookupParsedName(Result, S, &SS, !CurMethod);
921 
922   if (SS.isInvalid())
923     return NameClassification::Error();
924 
925   // For unqualified lookup in a class template in MSVC mode, look into
926   // dependent base classes where the primary class template is known.
927   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
928     if (ParsedType TypeInBase =
929             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
930       return TypeInBase;
931   }
932 
933   // Perform lookup for Objective-C instance variables (including automatically
934   // synthesized instance variables), if we're in an Objective-C method.
935   // FIXME: This lookup really, really needs to be folded in to the normal
936   // unqualified lookup mechanism.
937   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
938     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
939     if (Ivar.isInvalid())
940       return NameClassification::Error();
941     if (Ivar.isUsable())
942       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
943 
944     // We defer builtin creation until after ivar lookup inside ObjC methods.
945     if (Result.empty())
946       LookupBuiltin(Result);
947   }
948 
949   bool SecondTry = false;
950   bool IsFilteredTemplateName = false;
951 
952 Corrected:
953   switch (Result.getResultKind()) {
954   case LookupResult::NotFound:
955     // If an unqualified-id is followed by a '(', then we have a function
956     // call.
957     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
958       // In C++, this is an ADL-only call.
959       // FIXME: Reference?
960       if (getLangOpts().CPlusPlus)
961         return NameClassification::UndeclaredNonType();
962 
963       // C90 6.3.2.2:
964       //   If the expression that precedes the parenthesized argument list in a
965       //   function call consists solely of an identifier, and if no
966       //   declaration is visible for this identifier, the identifier is
967       //   implicitly declared exactly as if, in the innermost block containing
968       //   the function call, the declaration
969       //
970       //     extern int identifier ();
971       //
972       //   appeared.
973       //
974       // We also allow this in C99 as an extension. However, this is not
975       // allowed in all language modes as functions without prototypes may not
976       // be supported.
977       if (getLangOpts().implicitFunctionsAllowed()) {
978         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
979           return NameClassification::NonType(D);
980       }
981     }
982 
983     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
984       // In C++20 onwards, this could be an ADL-only call to a function
985       // template, and we're required to assume that this is a template name.
986       //
987       // FIXME: Find a way to still do typo correction in this case.
988       TemplateName Template =
989           Context.getAssumedTemplateName(NameInfo.getName());
990       return NameClassification::UndeclaredTemplate(Template);
991     }
992 
993     // In C, we first see whether there is a tag type by the same name, in
994     // which case it's likely that the user just forgot to write "enum",
995     // "struct", or "union".
996     if (!getLangOpts().CPlusPlus && !SecondTry &&
997         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
998       break;
999     }
1000 
1001     // Perform typo correction to determine if there is another name that is
1002     // close to this name.
1003     if (!SecondTry && CCC) {
1004       SecondTry = true;
1005       if (TypoCorrection Corrected =
1006               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1007                           &SS, *CCC, CTK_ErrorRecovery)) {
1008         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1009         unsigned QualifiedDiag = diag::err_no_member_suggest;
1010 
1011         NamedDecl *FirstDecl = Corrected.getFoundDecl();
1012         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1013         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1014             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1015           UnqualifiedDiag = diag::err_no_template_suggest;
1016           QualifiedDiag = diag::err_no_member_template_suggest;
1017         } else if (UnderlyingFirstDecl &&
1018                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
1019                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1020                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1021           UnqualifiedDiag = diag::err_unknown_typename_suggest;
1022           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1023         }
1024 
1025         if (SS.isEmpty()) {
1026           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1027         } else {// FIXME: is this even reachable? Test it.
1028           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1029           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1030                                   Name->getName().equals(CorrectedStr);
1031           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1032                                     << Name << computeDeclContext(SS, false)
1033                                     << DroppedSpecifier << SS.getRange());
1034         }
1035 
1036         // Update the name, so that the caller has the new name.
1037         Name = Corrected.getCorrectionAsIdentifierInfo();
1038 
1039         // Typo correction corrected to a keyword.
1040         if (Corrected.isKeyword())
1041           return Name;
1042 
1043         // Also update the LookupResult...
1044         // FIXME: This should probably go away at some point
1045         Result.clear();
1046         Result.setLookupName(Corrected.getCorrection());
1047         if (FirstDecl)
1048           Result.addDecl(FirstDecl);
1049 
1050         // If we found an Objective-C instance variable, let
1051         // LookupInObjCMethod build the appropriate expression to
1052         // reference the ivar.
1053         // FIXME: This is a gross hack.
1054         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1055           DeclResult R =
1056               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1057           if (R.isInvalid())
1058             return NameClassification::Error();
1059           if (R.isUsable())
1060             return NameClassification::NonType(Ivar);
1061         }
1062 
1063         goto Corrected;
1064       }
1065     }
1066 
1067     // We failed to correct; just fall through and let the parser deal with it.
1068     Result.suppressDiagnostics();
1069     return NameClassification::Unknown();
1070 
1071   case LookupResult::NotFoundInCurrentInstantiation: {
1072     // We performed name lookup into the current instantiation, and there were
1073     // dependent bases, so we treat this result the same way as any other
1074     // dependent nested-name-specifier.
1075 
1076     // C++ [temp.res]p2:
1077     //   A name used in a template declaration or definition and that is
1078     //   dependent on a template-parameter is assumed not to name a type
1079     //   unless the applicable name lookup finds a type name or the name is
1080     //   qualified by the keyword typename.
1081     //
1082     // FIXME: If the next token is '<', we might want to ask the parser to
1083     // perform some heroics to see if we actually have a
1084     // template-argument-list, which would indicate a missing 'template'
1085     // keyword here.
1086     return NameClassification::DependentNonType();
1087   }
1088 
1089   case LookupResult::Found:
1090   case LookupResult::FoundOverloaded:
1091   case LookupResult::FoundUnresolvedValue:
1092     break;
1093 
1094   case LookupResult::Ambiguous:
1095     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1096         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1097                                       /*AllowDependent=*/false)) {
1098       // C++ [temp.local]p3:
1099       //   A lookup that finds an injected-class-name (10.2) can result in an
1100       //   ambiguity in certain cases (for example, if it is found in more than
1101       //   one base class). If all of the injected-class-names that are found
1102       //   refer to specializations of the same class template, and if the name
1103       //   is followed by a template-argument-list, the reference refers to the
1104       //   class template itself and not a specialization thereof, and is not
1105       //   ambiguous.
1106       //
1107       // This filtering can make an ambiguous result into an unambiguous one,
1108       // so try again after filtering out template names.
1109       FilterAcceptableTemplateNames(Result);
1110       if (!Result.isAmbiguous()) {
1111         IsFilteredTemplateName = true;
1112         break;
1113       }
1114     }
1115 
1116     // Diagnose the ambiguity and return an error.
1117     return NameClassification::Error();
1118   }
1119 
1120   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1121       (IsFilteredTemplateName ||
1122        hasAnyAcceptableTemplateNames(
1123            Result, /*AllowFunctionTemplates=*/true,
1124            /*AllowDependent=*/false,
1125            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1126                getLangOpts().CPlusPlus20))) {
1127     // C++ [temp.names]p3:
1128     //   After name lookup (3.4) finds that a name is a template-name or that
1129     //   an operator-function-id or a literal- operator-id refers to a set of
1130     //   overloaded functions any member of which is a function template if
1131     //   this is followed by a <, the < is always taken as the delimiter of a
1132     //   template-argument-list and never as the less-than operator.
1133     // C++2a [temp.names]p2:
1134     //   A name is also considered to refer to a template if it is an
1135     //   unqualified-id followed by a < and name lookup finds either one
1136     //   or more functions or finds nothing.
1137     if (!IsFilteredTemplateName)
1138       FilterAcceptableTemplateNames(Result);
1139 
1140     bool IsFunctionTemplate;
1141     bool IsVarTemplate;
1142     TemplateName Template;
1143     if (Result.end() - Result.begin() > 1) {
1144       IsFunctionTemplate = true;
1145       Template = Context.getOverloadedTemplateName(Result.begin(),
1146                                                    Result.end());
1147     } else if (!Result.empty()) {
1148       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1149           *Result.begin(), /*AllowFunctionTemplates=*/true,
1150           /*AllowDependent=*/false));
1151       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1152       IsVarTemplate = isa<VarTemplateDecl>(TD);
1153 
1154       UsingShadowDecl *FoundUsingShadow =
1155           dyn_cast<UsingShadowDecl>(*Result.begin());
1156       assert(!FoundUsingShadow ||
1157              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1158       Template =
1159           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1160       if (SS.isNotEmpty())
1161         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1162                                                     /*TemplateKeyword=*/false,
1163                                                     Template);
1164     } else {
1165       // All results were non-template functions. This is a function template
1166       // name.
1167       IsFunctionTemplate = true;
1168       Template = Context.getAssumedTemplateName(NameInfo.getName());
1169     }
1170 
1171     if (IsFunctionTemplate) {
1172       // Function templates always go through overload resolution, at which
1173       // point we'll perform the various checks (e.g., accessibility) we need
1174       // to based on which function we selected.
1175       Result.suppressDiagnostics();
1176 
1177       return NameClassification::FunctionTemplate(Template);
1178     }
1179 
1180     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1181                          : NameClassification::TypeTemplate(Template);
1182   }
1183 
1184   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1185     QualType T = Context.getTypeDeclType(Type);
1186     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1187       T = Context.getUsingType(USD, T);
1188     return buildNamedType(*this, &SS, T, NameLoc);
1189   };
1190 
1191   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1192   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1193     DiagnoseUseOfDecl(Type, NameLoc);
1194     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1195     return BuildTypeFor(Type, *Result.begin());
1196   }
1197 
1198   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1199   if (!Class) {
1200     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1201     if (ObjCCompatibleAliasDecl *Alias =
1202             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1203       Class = Alias->getClassInterface();
1204   }
1205 
1206   if (Class) {
1207     DiagnoseUseOfDecl(Class, NameLoc);
1208 
1209     if (NextToken.is(tok::period)) {
1210       // Interface. <something> is parsed as a property reference expression.
1211       // Just return "unknown" as a fall-through for now.
1212       Result.suppressDiagnostics();
1213       return NameClassification::Unknown();
1214     }
1215 
1216     QualType T = Context.getObjCInterfaceType(Class);
1217     return ParsedType::make(T);
1218   }
1219 
1220   if (isa<ConceptDecl>(FirstDecl))
1221     return NameClassification::Concept(
1222         TemplateName(cast<TemplateDecl>(FirstDecl)));
1223 
1224   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1225     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1226     return NameClassification::Error();
1227   }
1228 
1229   // We can have a type template here if we're classifying a template argument.
1230   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1231       !isa<VarTemplateDecl>(FirstDecl))
1232     return NameClassification::TypeTemplate(
1233         TemplateName(cast<TemplateDecl>(FirstDecl)));
1234 
1235   // Check for a tag type hidden by a non-type decl in a few cases where it
1236   // seems likely a type is wanted instead of the non-type that was found.
1237   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1238   if ((NextToken.is(tok::identifier) ||
1239        (NextIsOp &&
1240         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1241       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1242     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1243     DiagnoseUseOfDecl(Type, NameLoc);
1244     return BuildTypeFor(Type, *Result.begin());
1245   }
1246 
1247   // If we already know which single declaration is referenced, just annotate
1248   // that declaration directly. Defer resolving even non-overloaded class
1249   // member accesses, as we need to defer certain access checks until we know
1250   // the context.
1251   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1252   if (Result.isSingleResult() && !ADL &&
1253       (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1254     return NameClassification::NonType(Result.getRepresentativeDecl());
1255 
1256   // Otherwise, this is an overload set that we will need to resolve later.
1257   Result.suppressDiagnostics();
1258   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1259       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1260       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1261       Result.begin(), Result.end()));
1262 }
1263 
1264 ExprResult
1265 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1266                                              SourceLocation NameLoc) {
1267   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1268   CXXScopeSpec SS;
1269   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1270   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1271 }
1272 
1273 ExprResult
1274 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1275                                             IdentifierInfo *Name,
1276                                             SourceLocation NameLoc,
1277                                             bool IsAddressOfOperand) {
1278   DeclarationNameInfo NameInfo(Name, NameLoc);
1279   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1280                                     NameInfo, IsAddressOfOperand,
1281                                     /*TemplateArgs=*/nullptr);
1282 }
1283 
1284 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1285                                               NamedDecl *Found,
1286                                               SourceLocation NameLoc,
1287                                               const Token &NextToken) {
1288   if (getCurMethodDecl() && SS.isEmpty())
1289     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1290       return BuildIvarRefExpr(S, NameLoc, Ivar);
1291 
1292   // Reconstruct the lookup result.
1293   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1294   Result.addDecl(Found);
1295   Result.resolveKind();
1296 
1297   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1298   return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1299 }
1300 
1301 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1302   // For an implicit class member access, transform the result into a member
1303   // access expression if necessary.
1304   auto *ULE = cast<UnresolvedLookupExpr>(E);
1305   if ((*ULE->decls_begin())->isCXXClassMember()) {
1306     CXXScopeSpec SS;
1307     SS.Adopt(ULE->getQualifierLoc());
1308 
1309     // Reconstruct the lookup result.
1310     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1311                         LookupOrdinaryName);
1312     Result.setNamingClass(ULE->getNamingClass());
1313     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1314       Result.addDecl(*I, I.getAccess());
1315     Result.resolveKind();
1316     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1317                                            nullptr, S);
1318   }
1319 
1320   // Otherwise, this is already in the form we needed, and no further checks
1321   // are necessary.
1322   return ULE;
1323 }
1324 
1325 Sema::TemplateNameKindForDiagnostics
1326 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1327   auto *TD = Name.getAsTemplateDecl();
1328   if (!TD)
1329     return TemplateNameKindForDiagnostics::DependentTemplate;
1330   if (isa<ClassTemplateDecl>(TD))
1331     return TemplateNameKindForDiagnostics::ClassTemplate;
1332   if (isa<FunctionTemplateDecl>(TD))
1333     return TemplateNameKindForDiagnostics::FunctionTemplate;
1334   if (isa<VarTemplateDecl>(TD))
1335     return TemplateNameKindForDiagnostics::VarTemplate;
1336   if (isa<TypeAliasTemplateDecl>(TD))
1337     return TemplateNameKindForDiagnostics::AliasTemplate;
1338   if (isa<TemplateTemplateParmDecl>(TD))
1339     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1340   if (isa<ConceptDecl>(TD))
1341     return TemplateNameKindForDiagnostics::Concept;
1342   return TemplateNameKindForDiagnostics::DependentTemplate;
1343 }
1344 
1345 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1346   assert(DC->getLexicalParent() == CurContext &&
1347       "The next DeclContext should be lexically contained in the current one.");
1348   CurContext = DC;
1349   S->setEntity(DC);
1350 }
1351 
1352 void Sema::PopDeclContext() {
1353   assert(CurContext && "DeclContext imbalance!");
1354 
1355   CurContext = CurContext->getLexicalParent();
1356   assert(CurContext && "Popped translation unit!");
1357 }
1358 
1359 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1360                                                                     Decl *D) {
1361   // Unlike PushDeclContext, the context to which we return is not necessarily
1362   // the containing DC of TD, because the new context will be some pre-existing
1363   // TagDecl definition instead of a fresh one.
1364   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1365   CurContext = cast<TagDecl>(D)->getDefinition();
1366   assert(CurContext && "skipping definition of undefined tag");
1367   // Start lookups from the parent of the current context; we don't want to look
1368   // into the pre-existing complete definition.
1369   S->setEntity(CurContext->getLookupParent());
1370   return Result;
1371 }
1372 
1373 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1374   CurContext = static_cast<decltype(CurContext)>(Context);
1375 }
1376 
1377 /// EnterDeclaratorContext - Used when we must lookup names in the context
1378 /// of a declarator's nested name specifier.
1379 ///
1380 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1381   // C++0x [basic.lookup.unqual]p13:
1382   //   A name used in the definition of a static data member of class
1383   //   X (after the qualified-id of the static member) is looked up as
1384   //   if the name was used in a member function of X.
1385   // C++0x [basic.lookup.unqual]p14:
1386   //   If a variable member of a namespace is defined outside of the
1387   //   scope of its namespace then any name used in the definition of
1388   //   the variable member (after the declarator-id) is looked up as
1389   //   if the definition of the variable member occurred in its
1390   //   namespace.
1391   // Both of these imply that we should push a scope whose context
1392   // is the semantic context of the declaration.  We can't use
1393   // PushDeclContext here because that context is not necessarily
1394   // lexically contained in the current context.  Fortunately,
1395   // the containing scope should have the appropriate information.
1396 
1397   assert(!S->getEntity() && "scope already has entity");
1398 
1399 #ifndef NDEBUG
1400   Scope *Ancestor = S->getParent();
1401   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1402   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1403 #endif
1404 
1405   CurContext = DC;
1406   S->setEntity(DC);
1407 
1408   if (S->getParent()->isTemplateParamScope()) {
1409     // Also set the corresponding entities for all immediately-enclosing
1410     // template parameter scopes.
1411     EnterTemplatedContext(S->getParent(), DC);
1412   }
1413 }
1414 
1415 void Sema::ExitDeclaratorContext(Scope *S) {
1416   assert(S->getEntity() == CurContext && "Context imbalance!");
1417 
1418   // Switch back to the lexical context.  The safety of this is
1419   // enforced by an assert in EnterDeclaratorContext.
1420   Scope *Ancestor = S->getParent();
1421   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1422   CurContext = Ancestor->getEntity();
1423 
1424   // We don't need to do anything with the scope, which is going to
1425   // disappear.
1426 }
1427 
1428 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1429   assert(S->isTemplateParamScope() &&
1430          "expected to be initializing a template parameter scope");
1431 
1432   // C++20 [temp.local]p7:
1433   //   In the definition of a member of a class template that appears outside
1434   //   of the class template definition, the name of a member of the class
1435   //   template hides the name of a template-parameter of any enclosing class
1436   //   templates (but not a template-parameter of the member if the member is a
1437   //   class or function template).
1438   // C++20 [temp.local]p9:
1439   //   In the definition of a class template or in the definition of a member
1440   //   of such a template that appears outside of the template definition, for
1441   //   each non-dependent base class (13.8.2.1), if the name of the base class
1442   //   or the name of a member of the base class is the same as the name of a
1443   //   template-parameter, the base class name or member name hides the
1444   //   template-parameter name (6.4.10).
1445   //
1446   // This means that a template parameter scope should be searched immediately
1447   // after searching the DeclContext for which it is a template parameter
1448   // scope. For example, for
1449   //   template<typename T> template<typename U> template<typename V>
1450   //     void N::A<T>::B<U>::f(...)
1451   // we search V then B<U> (and base classes) then U then A<T> (and base
1452   // classes) then T then N then ::.
1453   unsigned ScopeDepth = getTemplateDepth(S);
1454   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1455     DeclContext *SearchDCAfterScope = DC;
1456     for (; DC; DC = DC->getLookupParent()) {
1457       if (const TemplateParameterList *TPL =
1458               cast<Decl>(DC)->getDescribedTemplateParams()) {
1459         unsigned DCDepth = TPL->getDepth() + 1;
1460         if (DCDepth > ScopeDepth)
1461           continue;
1462         if (ScopeDepth == DCDepth)
1463           SearchDCAfterScope = DC = DC->getLookupParent();
1464         break;
1465       }
1466     }
1467     S->setLookupEntity(SearchDCAfterScope);
1468   }
1469 }
1470 
1471 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1472   // We assume that the caller has already called
1473   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1474   FunctionDecl *FD = D->getAsFunction();
1475   if (!FD)
1476     return;
1477 
1478   // Same implementation as PushDeclContext, but enters the context
1479   // from the lexical parent, rather than the top-level class.
1480   assert(CurContext == FD->getLexicalParent() &&
1481     "The next DeclContext should be lexically contained in the current one.");
1482   CurContext = FD;
1483   S->setEntity(CurContext);
1484 
1485   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1486     ParmVarDecl *Param = FD->getParamDecl(P);
1487     // If the parameter has an identifier, then add it to the scope
1488     if (Param->getIdentifier()) {
1489       S->AddDecl(Param);
1490       IdResolver.AddDecl(Param);
1491     }
1492   }
1493 }
1494 
1495 void Sema::ActOnExitFunctionContext() {
1496   // Same implementation as PopDeclContext, but returns to the lexical parent,
1497   // rather than the top-level class.
1498   assert(CurContext && "DeclContext imbalance!");
1499   CurContext = CurContext->getLexicalParent();
1500   assert(CurContext && "Popped translation unit!");
1501 }
1502 
1503 /// Determine whether overloading is allowed for a new function
1504 /// declaration considering prior declarations of the same name.
1505 ///
1506 /// This routine determines whether overloading is possible, not
1507 /// whether a new declaration actually overloads a previous one.
1508 /// It will return true in C++ (where overloads are alway permitted)
1509 /// or, as a C extension, when either the new declaration or a
1510 /// previous one is declared with the 'overloadable' attribute.
1511 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1512                                        ASTContext &Context,
1513                                        const FunctionDecl *New) {
1514   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1515     return true;
1516 
1517   // Multiversion function declarations are not overloads in the
1518   // usual sense of that term, but lookup will report that an
1519   // overload set was found if more than one multiversion function
1520   // declaration is present for the same name. It is therefore
1521   // inadequate to assume that some prior declaration(s) had
1522   // the overloadable attribute; checking is required. Since one
1523   // declaration is permitted to omit the attribute, it is necessary
1524   // to check at least two; hence the 'any_of' check below. Note that
1525   // the overloadable attribute is implicitly added to declarations
1526   // that were required to have it but did not.
1527   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1528     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1529       return ND->hasAttr<OverloadableAttr>();
1530     });
1531   } else if (Previous.getResultKind() == LookupResult::Found)
1532     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1533 
1534   return false;
1535 }
1536 
1537 /// Add this decl to the scope shadowed decl chains.
1538 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1539   // Move up the scope chain until we find the nearest enclosing
1540   // non-transparent context. The declaration will be introduced into this
1541   // scope.
1542   while (S->getEntity() && S->getEntity()->isTransparentContext())
1543     S = S->getParent();
1544 
1545   // Add scoped declarations into their context, so that they can be
1546   // found later. Declarations without a context won't be inserted
1547   // into any context.
1548   if (AddToContext)
1549     CurContext->addDecl(D);
1550 
1551   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1552   // are function-local declarations.
1553   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1554     return;
1555 
1556   // Template instantiations should also not be pushed into scope.
1557   if (isa<FunctionDecl>(D) &&
1558       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1559     return;
1560 
1561   // If this replaces anything in the current scope,
1562   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1563                                IEnd = IdResolver.end();
1564   for (; I != IEnd; ++I) {
1565     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1566       S->RemoveDecl(*I);
1567       IdResolver.RemoveDecl(*I);
1568 
1569       // Should only need to replace one decl.
1570       break;
1571     }
1572   }
1573 
1574   S->AddDecl(D);
1575 
1576   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1577     // Implicitly-generated labels may end up getting generated in an order that
1578     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1579     // the label at the appropriate place in the identifier chain.
1580     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1581       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1582       if (IDC == CurContext) {
1583         if (!S->isDeclScope(*I))
1584           continue;
1585       } else if (IDC->Encloses(CurContext))
1586         break;
1587     }
1588 
1589     IdResolver.InsertDeclAfter(I, D);
1590   } else {
1591     IdResolver.AddDecl(D);
1592   }
1593   warnOnReservedIdentifier(D);
1594 }
1595 
1596 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1597                          bool AllowInlineNamespace) const {
1598   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1599 }
1600 
1601 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1602   DeclContext *TargetDC = DC->getPrimaryContext();
1603   do {
1604     if (DeclContext *ScopeDC = S->getEntity())
1605       if (ScopeDC->getPrimaryContext() == TargetDC)
1606         return S;
1607   } while ((S = S->getParent()));
1608 
1609   return nullptr;
1610 }
1611 
1612 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1613                                             DeclContext*,
1614                                             ASTContext&);
1615 
1616 /// Filters out lookup results that don't fall within the given scope
1617 /// as determined by isDeclInScope.
1618 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1619                                 bool ConsiderLinkage,
1620                                 bool AllowInlineNamespace) {
1621   LookupResult::Filter F = R.makeFilter();
1622   while (F.hasNext()) {
1623     NamedDecl *D = F.next();
1624 
1625     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1626       continue;
1627 
1628     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1629       continue;
1630 
1631     F.erase();
1632   }
1633 
1634   F.done();
1635 }
1636 
1637 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1638 /// have compatible owning modules.
1639 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1640   // [module.interface]p7:
1641   // A declaration is attached to a module as follows:
1642   // - If the declaration is a non-dependent friend declaration that nominates a
1643   // function with a declarator-id that is a qualified-id or template-id or that
1644   // nominates a class other than with an elaborated-type-specifier with neither
1645   // a nested-name-specifier nor a simple-template-id, it is attached to the
1646   // module to which the friend is attached ([basic.link]).
1647   if (New->getFriendObjectKind() &&
1648       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1649     New->setLocalOwningModule(Old->getOwningModule());
1650     makeMergedDefinitionVisible(New);
1651     return false;
1652   }
1653 
1654   Module *NewM = New->getOwningModule();
1655   Module *OldM = Old->getOwningModule();
1656 
1657   if (NewM && NewM->isPrivateModule())
1658     NewM = NewM->Parent;
1659   if (OldM && OldM->isPrivateModule())
1660     OldM = OldM->Parent;
1661 
1662   if (NewM == OldM)
1663     return false;
1664 
1665   if (NewM && OldM) {
1666     // A module implementation unit has visibility of the decls in its
1667     // implicitly imported interface.
1668     if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1669       return false;
1670 
1671     // Partitions are part of the module, but a partition could import another
1672     // module, so verify that the PMIs agree.
1673     if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1674         NewM->getPrimaryModuleInterfaceName() ==
1675             OldM->getPrimaryModuleInterfaceName())
1676       return false;
1677   }
1678 
1679   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1680   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1681   if (NewIsModuleInterface || OldIsModuleInterface) {
1682     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1683     //   if a declaration of D [...] appears in the purview of a module, all
1684     //   other such declarations shall appear in the purview of the same module
1685     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1686       << New
1687       << NewIsModuleInterface
1688       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1689       << OldIsModuleInterface
1690       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1691     Diag(Old->getLocation(), diag::note_previous_declaration);
1692     New->setInvalidDecl();
1693     return true;
1694   }
1695 
1696   return false;
1697 }
1698 
1699 // [module.interface]p6:
1700 // A redeclaration of an entity X is implicitly exported if X was introduced by
1701 // an exported declaration; otherwise it shall not be exported.
1702 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1703   // [module.interface]p1:
1704   // An export-declaration shall inhabit a namespace scope.
1705   //
1706   // So it is meaningless to talk about redeclaration which is not at namespace
1707   // scope.
1708   if (!New->getLexicalDeclContext()
1709            ->getNonTransparentContext()
1710            ->isFileContext() ||
1711       !Old->getLexicalDeclContext()
1712            ->getNonTransparentContext()
1713            ->isFileContext())
1714     return false;
1715 
1716   bool IsNewExported = New->isInExportDeclContext();
1717   bool IsOldExported = Old->isInExportDeclContext();
1718 
1719   // It should be irrevelant if both of them are not exported.
1720   if (!IsNewExported && !IsOldExported)
1721     return false;
1722 
1723   if (IsOldExported)
1724     return false;
1725 
1726   assert(IsNewExported);
1727 
1728   auto Lk = Old->getFormalLinkage();
1729   int S = 0;
1730   if (Lk == Linkage::InternalLinkage)
1731     S = 1;
1732   else if (Lk == Linkage::ModuleLinkage)
1733     S = 2;
1734   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1735   Diag(Old->getLocation(), diag::note_previous_declaration);
1736   return true;
1737 }
1738 
1739 // A wrapper function for checking the semantic restrictions of
1740 // a redeclaration within a module.
1741 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1742   if (CheckRedeclarationModuleOwnership(New, Old))
1743     return true;
1744 
1745   if (CheckRedeclarationExported(New, Old))
1746     return true;
1747 
1748   return false;
1749 }
1750 
1751 // Check the redefinition in C++20 Modules.
1752 //
1753 // [basic.def.odr]p14:
1754 // For any definable item D with definitions in multiple translation units,
1755 // - if D is a non-inline non-templated function or variable, or
1756 // - if the definitions in different translation units do not satisfy the
1757 // following requirements,
1758 //   the program is ill-formed; a diagnostic is required only if the definable
1759 //   item is attached to a named module and a prior definition is reachable at
1760 //   the point where a later definition occurs.
1761 // - Each such definition shall not be attached to a named module
1762 // ([module.unit]).
1763 // - Each such definition shall consist of the same sequence of tokens, ...
1764 // ...
1765 //
1766 // Return true if the redefinition is not allowed. Return false otherwise.
1767 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1768                                      const NamedDecl *Old) const {
1769   assert(getASTContext().isSameEntity(New, Old) &&
1770          "New and Old are not the same definition, we should diagnostic it "
1771          "immediately instead of checking it.");
1772   assert(const_cast<Sema *>(this)->isReachable(New) &&
1773          const_cast<Sema *>(this)->isReachable(Old) &&
1774          "We shouldn't see unreachable definitions here.");
1775 
1776   Module *NewM = New->getOwningModule();
1777   Module *OldM = Old->getOwningModule();
1778 
1779   // We only checks for named modules here. The header like modules is skipped.
1780   // FIXME: This is not right if we import the header like modules in the module
1781   // purview.
1782   //
1783   // For example, assuming "header.h" provides definition for `D`.
1784   // ```C++
1785   // //--- M.cppm
1786   // export module M;
1787   // import "header.h"; // or #include "header.h" but import it by clang modules
1788   // actually.
1789   //
1790   // //--- Use.cpp
1791   // import M;
1792   // import "header.h"; // or uses clang modules.
1793   // ```
1794   //
1795   // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1796   // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1797   // reject it. But the current implementation couldn't detect the case since we
1798   // don't record the information about the importee modules.
1799   //
1800   // But this might not be painful in practice. Since the design of C++20 Named
1801   // Modules suggests us to use headers in global module fragment instead of
1802   // module purview.
1803   if (NewM && NewM->isHeaderLikeModule())
1804     NewM = nullptr;
1805   if (OldM && OldM->isHeaderLikeModule())
1806     OldM = nullptr;
1807 
1808   if (!NewM && !OldM)
1809     return true;
1810 
1811   // [basic.def.odr]p14.3
1812   // Each such definition shall not be attached to a named module
1813   // ([module.unit]).
1814   if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1815     return true;
1816 
1817   // Then New and Old lives in the same TU if their share one same module unit.
1818   if (NewM)
1819     NewM = NewM->getTopLevelModule();
1820   if (OldM)
1821     OldM = OldM->getTopLevelModule();
1822   return OldM == NewM;
1823 }
1824 
1825 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1826   if (D->getDeclContext()->isFileContext())
1827     return false;
1828 
1829   return isa<UsingShadowDecl>(D) ||
1830          isa<UnresolvedUsingTypenameDecl>(D) ||
1831          isa<UnresolvedUsingValueDecl>(D);
1832 }
1833 
1834 /// Removes using shadow declarations not at class scope from the lookup
1835 /// results.
1836 static void RemoveUsingDecls(LookupResult &R) {
1837   LookupResult::Filter F = R.makeFilter();
1838   while (F.hasNext())
1839     if (isUsingDeclNotAtClassScope(F.next()))
1840       F.erase();
1841 
1842   F.done();
1843 }
1844 
1845 /// Check for this common pattern:
1846 /// @code
1847 /// class S {
1848 ///   S(const S&); // DO NOT IMPLEMENT
1849 ///   void operator=(const S&); // DO NOT IMPLEMENT
1850 /// };
1851 /// @endcode
1852 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1853   // FIXME: Should check for private access too but access is set after we get
1854   // the decl here.
1855   if (D->doesThisDeclarationHaveABody())
1856     return false;
1857 
1858   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1859     return CD->isCopyConstructor();
1860   return D->isCopyAssignmentOperator();
1861 }
1862 
1863 // We need this to handle
1864 //
1865 // typedef struct {
1866 //   void *foo() { return 0; }
1867 // } A;
1868 //
1869 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1870 // for example. If 'A', foo will have external linkage. If we have '*A',
1871 // foo will have no linkage. Since we can't know until we get to the end
1872 // of the typedef, this function finds out if D might have non-external linkage.
1873 // Callers should verify at the end of the TU if it D has external linkage or
1874 // not.
1875 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1876   const DeclContext *DC = D->getDeclContext();
1877   while (!DC->isTranslationUnit()) {
1878     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1879       if (!RD->hasNameForLinkage())
1880         return true;
1881     }
1882     DC = DC->getParent();
1883   }
1884 
1885   return !D->isExternallyVisible();
1886 }
1887 
1888 // FIXME: This needs to be refactored; some other isInMainFile users want
1889 // these semantics.
1890 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1891   if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1892     return false;
1893   return S.SourceMgr.isInMainFile(Loc);
1894 }
1895 
1896 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1897   assert(D);
1898 
1899   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1900     return false;
1901 
1902   // Ignore all entities declared within templates, and out-of-line definitions
1903   // of members of class templates.
1904   if (D->getDeclContext()->isDependentContext() ||
1905       D->getLexicalDeclContext()->isDependentContext())
1906     return false;
1907 
1908   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1909     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1910       return false;
1911     // A non-out-of-line declaration of a member specialization was implicitly
1912     // instantiated; it's the out-of-line declaration that we're interested in.
1913     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1914         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1915       return false;
1916 
1917     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1918       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1919         return false;
1920     } else {
1921       // 'static inline' functions are defined in headers; don't warn.
1922       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1923         return false;
1924     }
1925 
1926     if (FD->doesThisDeclarationHaveABody() &&
1927         Context.DeclMustBeEmitted(FD))
1928       return false;
1929   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1930     // Constants and utility variables are defined in headers with internal
1931     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1932     // like "inline".)
1933     if (!isMainFileLoc(*this, VD->getLocation()))
1934       return false;
1935 
1936     if (Context.DeclMustBeEmitted(VD))
1937       return false;
1938 
1939     if (VD->isStaticDataMember() &&
1940         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1941       return false;
1942     if (VD->isStaticDataMember() &&
1943         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1944         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1945       return false;
1946 
1947     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1948       return false;
1949   } else {
1950     return false;
1951   }
1952 
1953   // Only warn for unused decls internal to the translation unit.
1954   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1955   // for inline functions defined in the main source file, for instance.
1956   return mightHaveNonExternalLinkage(D);
1957 }
1958 
1959 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1960   if (!D)
1961     return;
1962 
1963   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1964     const FunctionDecl *First = FD->getFirstDecl();
1965     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1966       return; // First should already be in the vector.
1967   }
1968 
1969   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1970     const VarDecl *First = VD->getFirstDecl();
1971     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1972       return; // First should already be in the vector.
1973   }
1974 
1975   if (ShouldWarnIfUnusedFileScopedDecl(D))
1976     UnusedFileScopedDecls.push_back(D);
1977 }
1978 
1979 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1980   if (D->isInvalidDecl())
1981     return false;
1982 
1983   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1984     // For a decomposition declaration, warn if none of the bindings are
1985     // referenced, instead of if the variable itself is referenced (which
1986     // it is, by the bindings' expressions).
1987     for (auto *BD : DD->bindings())
1988       if (BD->isReferenced())
1989         return false;
1990   } else if (!D->getDeclName()) {
1991     return false;
1992   } else if (D->isReferenced() || D->isUsed()) {
1993     return false;
1994   }
1995 
1996   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1997       D->hasAttr<CleanupAttr>())
1998     return false;
1999 
2000   if (isa<LabelDecl>(D))
2001     return true;
2002 
2003   // Except for labels, we only care about unused decls that are local to
2004   // functions.
2005   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2006   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2007     // For dependent types, the diagnostic is deferred.
2008     WithinFunction =
2009         WithinFunction || (R->isLocalClass() && !R->isDependentType());
2010   if (!WithinFunction)
2011     return false;
2012 
2013   if (isa<TypedefNameDecl>(D))
2014     return true;
2015 
2016   // White-list anything that isn't a local variable.
2017   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2018     return false;
2019 
2020   // Types of valid local variables should be complete, so this should succeed.
2021   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2022 
2023     const Expr *Init = VD->getInit();
2024     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2025       Init = Cleanups->getSubExpr();
2026 
2027     const auto *Ty = VD->getType().getTypePtr();
2028 
2029     // Only look at the outermost level of typedef.
2030     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2031       // Allow anything marked with __attribute__((unused)).
2032       if (TT->getDecl()->hasAttr<UnusedAttr>())
2033         return false;
2034     }
2035 
2036     // Warn for reference variables whose initializtion performs lifetime
2037     // extension.
2038     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2039       if (MTE->getExtendingDecl()) {
2040         Ty = VD->getType().getNonReferenceType().getTypePtr();
2041         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2042       }
2043     }
2044 
2045     // If we failed to complete the type for some reason, or if the type is
2046     // dependent, don't diagnose the variable.
2047     if (Ty->isIncompleteType() || Ty->isDependentType())
2048       return false;
2049 
2050     // Look at the element type to ensure that the warning behaviour is
2051     // consistent for both scalars and arrays.
2052     Ty = Ty->getBaseElementTypeUnsafe();
2053 
2054     if (const TagType *TT = Ty->getAs<TagType>()) {
2055       const TagDecl *Tag = TT->getDecl();
2056       if (Tag->hasAttr<UnusedAttr>())
2057         return false;
2058 
2059       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2060         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2061           return false;
2062 
2063         if (Init) {
2064           const CXXConstructExpr *Construct =
2065             dyn_cast<CXXConstructExpr>(Init);
2066           if (Construct && !Construct->isElidable()) {
2067             CXXConstructorDecl *CD = Construct->getConstructor();
2068             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2069                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2070               return false;
2071           }
2072 
2073           // Suppress the warning if we don't know how this is constructed, and
2074           // it could possibly be non-trivial constructor.
2075           if (Init->isTypeDependent()) {
2076             for (const CXXConstructorDecl *Ctor : RD->ctors())
2077               if (!Ctor->isTrivial())
2078                 return false;
2079           }
2080 
2081           // Suppress the warning if the constructor is unresolved because
2082           // its arguments are dependent.
2083           if (isa<CXXUnresolvedConstructExpr>(Init))
2084             return false;
2085         }
2086       }
2087     }
2088 
2089     // TODO: __attribute__((unused)) templates?
2090   }
2091 
2092   return true;
2093 }
2094 
2095 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2096                                      FixItHint &Hint) {
2097   if (isa<LabelDecl>(D)) {
2098     SourceLocation AfterColon = Lexer::findLocationAfterToken(
2099         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2100         /*SkipTrailingWhitespaceAndNewline=*/false);
2101     if (AfterColon.isInvalid())
2102       return;
2103     Hint = FixItHint::CreateRemoval(
2104         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2105   }
2106 }
2107 
2108 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2109   DiagnoseUnusedNestedTypedefs(
2110       D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2111 }
2112 
2113 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2114                                         DiagReceiverTy DiagReceiver) {
2115   if (D->getTypeForDecl()->isDependentType())
2116     return;
2117 
2118   for (auto *TmpD : D->decls()) {
2119     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2120       DiagnoseUnusedDecl(T, DiagReceiver);
2121     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2122       DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2123   }
2124 }
2125 
2126 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2127   DiagnoseUnusedDecl(
2128       D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2129 }
2130 
2131 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2132 /// unless they are marked attr(unused).
2133 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2134   if (!ShouldDiagnoseUnusedDecl(D))
2135     return;
2136 
2137   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2138     // typedefs can be referenced later on, so the diagnostics are emitted
2139     // at end-of-translation-unit.
2140     UnusedLocalTypedefNameCandidates.insert(TD);
2141     return;
2142   }
2143 
2144   FixItHint Hint;
2145   GenerateFixForUnusedDecl(D, Context, Hint);
2146 
2147   unsigned DiagID;
2148   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2149     DiagID = diag::warn_unused_exception_param;
2150   else if (isa<LabelDecl>(D))
2151     DiagID = diag::warn_unused_label;
2152   else
2153     DiagID = diag::warn_unused_variable;
2154 
2155   SourceLocation DiagLoc = D->getLocation();
2156   DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2157 }
2158 
2159 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2160                                     DiagReceiverTy DiagReceiver) {
2161   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2162   // it's not really unused.
2163   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2164       VD->hasAttr<CleanupAttr>())
2165     return;
2166 
2167   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2168 
2169   if (Ty->isReferenceType() || Ty->isDependentType())
2170     return;
2171 
2172   if (const TagType *TT = Ty->getAs<TagType>()) {
2173     const TagDecl *Tag = TT->getDecl();
2174     if (Tag->hasAttr<UnusedAttr>())
2175       return;
2176     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2177     // mimic gcc's behavior.
2178     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2179       if (!RD->hasAttr<WarnUnusedAttr>())
2180         return;
2181     }
2182   }
2183 
2184   // Don't warn about __block Objective-C pointer variables, as they might
2185   // be assigned in the block but not used elsewhere for the purpose of lifetime
2186   // extension.
2187   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2188     return;
2189 
2190   // Don't warn about Objective-C pointer variables with precise lifetime
2191   // semantics; they can be used to ensure ARC releases the object at a known
2192   // time, which may mean assignment but no other references.
2193   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2194     return;
2195 
2196   auto iter = RefsMinusAssignments.find(VD);
2197   if (iter == RefsMinusAssignments.end())
2198     return;
2199 
2200   assert(iter->getSecond() >= 0 &&
2201          "Found a negative number of references to a VarDecl");
2202   if (iter->getSecond() != 0)
2203     return;
2204   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2205                                          : diag::warn_unused_but_set_variable;
2206   DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2207 }
2208 
2209 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2210                              Sema::DiagReceiverTy DiagReceiver) {
2211   // Verify that we have no forward references left.  If so, there was a goto
2212   // or address of a label taken, but no definition of it.  Label fwd
2213   // definitions are indicated with a null substmt which is also not a resolved
2214   // MS inline assembly label name.
2215   bool Diagnose = false;
2216   if (L->isMSAsmLabel())
2217     Diagnose = !L->isResolvedMSAsmLabel();
2218   else
2219     Diagnose = L->getStmt() == nullptr;
2220   if (Diagnose)
2221     DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2222                                        << L);
2223 }
2224 
2225 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2226   S->applyNRVO();
2227 
2228   if (S->decl_empty()) return;
2229   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2230          "Scope shouldn't contain decls!");
2231 
2232   /// We visit the decls in non-deterministic order, but we want diagnostics
2233   /// emitted in deterministic order. Collect any diagnostic that may be emitted
2234   /// and sort the diagnostics before emitting them, after we visited all decls.
2235   struct LocAndDiag {
2236     SourceLocation Loc;
2237     std::optional<SourceLocation> PreviousDeclLoc;
2238     PartialDiagnostic PD;
2239   };
2240   SmallVector<LocAndDiag, 16> DeclDiags;
2241   auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2242     DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2243   };
2244   auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2245                                       SourceLocation PreviousDeclLoc,
2246                                       PartialDiagnostic PD) {
2247     DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2248   };
2249 
2250   for (auto *TmpD : S->decls()) {
2251     assert(TmpD && "This decl didn't get pushed??");
2252 
2253     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2254     NamedDecl *D = cast<NamedDecl>(TmpD);
2255 
2256     // Diagnose unused variables in this scope.
2257     if (!S->hasUnrecoverableErrorOccurred()) {
2258       DiagnoseUnusedDecl(D, addDiag);
2259       if (const auto *RD = dyn_cast<RecordDecl>(D))
2260         DiagnoseUnusedNestedTypedefs(RD, addDiag);
2261       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2262         DiagnoseUnusedButSetDecl(VD, addDiag);
2263         RefsMinusAssignments.erase(VD);
2264       }
2265     }
2266 
2267     if (!D->getDeclName()) continue;
2268 
2269     // If this was a forward reference to a label, verify it was defined.
2270     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2271       CheckPoppedLabel(LD, *this, addDiag);
2272 
2273     // Remove this name from our lexical scope, and warn on it if we haven't
2274     // already.
2275     IdResolver.RemoveDecl(D);
2276     auto ShadowI = ShadowingDecls.find(D);
2277     if (ShadowI != ShadowingDecls.end()) {
2278       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2279         addDiagWithPrev(D->getLocation(), FD->getLocation(),
2280                         PDiag(diag::warn_ctor_parm_shadows_field)
2281                             << D << FD << FD->getParent());
2282       }
2283       ShadowingDecls.erase(ShadowI);
2284     }
2285   }
2286 
2287   llvm::sort(DeclDiags,
2288              [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2289                // The particular order for diagnostics is not important, as long
2290                // as the order is deterministic. Using the raw location is going
2291                // to generally be in source order unless there are macro
2292                // expansions involved.
2293                return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2294              });
2295   for (const LocAndDiag &D : DeclDiags) {
2296     Diag(D.Loc, D.PD);
2297     if (D.PreviousDeclLoc)
2298       Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2299   }
2300 }
2301 
2302 /// Look for an Objective-C class in the translation unit.
2303 ///
2304 /// \param Id The name of the Objective-C class we're looking for. If
2305 /// typo-correction fixes this name, the Id will be updated
2306 /// to the fixed name.
2307 ///
2308 /// \param IdLoc The location of the name in the translation unit.
2309 ///
2310 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2311 /// if there is no class with the given name.
2312 ///
2313 /// \returns The declaration of the named Objective-C class, or NULL if the
2314 /// class could not be found.
2315 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2316                                               SourceLocation IdLoc,
2317                                               bool DoTypoCorrection) {
2318   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2319   // creation from this context.
2320   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2321 
2322   if (!IDecl && DoTypoCorrection) {
2323     // Perform typo correction at the given location, but only if we
2324     // find an Objective-C class name.
2325     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2326     if (TypoCorrection C =
2327             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2328                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2329       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2330       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2331       Id = IDecl->getIdentifier();
2332     }
2333   }
2334   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2335   // This routine must always return a class definition, if any.
2336   if (Def && Def->getDefinition())
2337       Def = Def->getDefinition();
2338   return Def;
2339 }
2340 
2341 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2342 /// from S, where a non-field would be declared. This routine copes
2343 /// with the difference between C and C++ scoping rules in structs and
2344 /// unions. For example, the following code is well-formed in C but
2345 /// ill-formed in C++:
2346 /// @code
2347 /// struct S6 {
2348 ///   enum { BAR } e;
2349 /// };
2350 ///
2351 /// void test_S6() {
2352 ///   struct S6 a;
2353 ///   a.e = BAR;
2354 /// }
2355 /// @endcode
2356 /// For the declaration of BAR, this routine will return a different
2357 /// scope. The scope S will be the scope of the unnamed enumeration
2358 /// within S6. In C++, this routine will return the scope associated
2359 /// with S6, because the enumeration's scope is a transparent
2360 /// context but structures can contain non-field names. In C, this
2361 /// routine will return the translation unit scope, since the
2362 /// enumeration's scope is a transparent context and structures cannot
2363 /// contain non-field names.
2364 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2365   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2366          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2367          (S->isClassScope() && !getLangOpts().CPlusPlus))
2368     S = S->getParent();
2369   return S;
2370 }
2371 
2372 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2373                                ASTContext::GetBuiltinTypeError Error) {
2374   switch (Error) {
2375   case ASTContext::GE_None:
2376     return "";
2377   case ASTContext::GE_Missing_type:
2378     return BuiltinInfo.getHeaderName(ID);
2379   case ASTContext::GE_Missing_stdio:
2380     return "stdio.h";
2381   case ASTContext::GE_Missing_setjmp:
2382     return "setjmp.h";
2383   case ASTContext::GE_Missing_ucontext:
2384     return "ucontext.h";
2385   }
2386   llvm_unreachable("unhandled error kind");
2387 }
2388 
2389 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2390                                   unsigned ID, SourceLocation Loc) {
2391   DeclContext *Parent = Context.getTranslationUnitDecl();
2392 
2393   if (getLangOpts().CPlusPlus) {
2394     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2395         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2396     CLinkageDecl->setImplicit();
2397     Parent->addDecl(CLinkageDecl);
2398     Parent = CLinkageDecl;
2399   }
2400 
2401   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2402                                            /*TInfo=*/nullptr, SC_Extern,
2403                                            getCurFPFeatures().isFPConstrained(),
2404                                            false, Type->isFunctionProtoType());
2405   New->setImplicit();
2406   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2407 
2408   // Create Decl objects for each parameter, adding them to the
2409   // FunctionDecl.
2410   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2411     SmallVector<ParmVarDecl *, 16> Params;
2412     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2413       ParmVarDecl *parm = ParmVarDecl::Create(
2414           Context, New, SourceLocation(), SourceLocation(), nullptr,
2415           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2416       parm->setScopeInfo(0, i);
2417       Params.push_back(parm);
2418     }
2419     New->setParams(Params);
2420   }
2421 
2422   AddKnownFunctionAttributes(New);
2423   return New;
2424 }
2425 
2426 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2427 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2428 /// if we're creating this built-in in anticipation of redeclaring the
2429 /// built-in.
2430 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2431                                      Scope *S, bool ForRedeclaration,
2432                                      SourceLocation Loc) {
2433   LookupNecessaryTypesForBuiltin(S, ID);
2434 
2435   ASTContext::GetBuiltinTypeError Error;
2436   QualType R = Context.GetBuiltinType(ID, Error);
2437   if (Error) {
2438     if (!ForRedeclaration)
2439       return nullptr;
2440 
2441     // If we have a builtin without an associated type we should not emit a
2442     // warning when we were not able to find a type for it.
2443     if (Error == ASTContext::GE_Missing_type ||
2444         Context.BuiltinInfo.allowTypeMismatch(ID))
2445       return nullptr;
2446 
2447     // If we could not find a type for setjmp it is because the jmp_buf type was
2448     // not defined prior to the setjmp declaration.
2449     if (Error == ASTContext::GE_Missing_setjmp) {
2450       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2451           << Context.BuiltinInfo.getName(ID);
2452       return nullptr;
2453     }
2454 
2455     // Generally, we emit a warning that the declaration requires the
2456     // appropriate header.
2457     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2458         << getHeaderName(Context.BuiltinInfo, ID, Error)
2459         << Context.BuiltinInfo.getName(ID);
2460     return nullptr;
2461   }
2462 
2463   if (!ForRedeclaration &&
2464       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2465        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2466     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2467                            : diag::ext_implicit_lib_function_decl)
2468         << Context.BuiltinInfo.getName(ID) << R;
2469     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2470       Diag(Loc, diag::note_include_header_or_declare)
2471           << Header << Context.BuiltinInfo.getName(ID);
2472   }
2473 
2474   if (R.isNull())
2475     return nullptr;
2476 
2477   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2478   RegisterLocallyScopedExternCDecl(New, S);
2479 
2480   // TUScope is the translation-unit scope to insert this function into.
2481   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2482   // relate Scopes to DeclContexts, and probably eliminate CurContext
2483   // entirely, but we're not there yet.
2484   DeclContext *SavedContext = CurContext;
2485   CurContext = New->getDeclContext();
2486   PushOnScopeChains(New, TUScope);
2487   CurContext = SavedContext;
2488   return New;
2489 }
2490 
2491 /// Typedef declarations don't have linkage, but they still denote the same
2492 /// entity if their types are the same.
2493 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2494 /// isSameEntity.
2495 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2496                                                      TypedefNameDecl *Decl,
2497                                                      LookupResult &Previous) {
2498   // This is only interesting when modules are enabled.
2499   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2500     return;
2501 
2502   // Empty sets are uninteresting.
2503   if (Previous.empty())
2504     return;
2505 
2506   LookupResult::Filter Filter = Previous.makeFilter();
2507   while (Filter.hasNext()) {
2508     NamedDecl *Old = Filter.next();
2509 
2510     // Non-hidden declarations are never ignored.
2511     if (S.isVisible(Old))
2512       continue;
2513 
2514     // Declarations of the same entity are not ignored, even if they have
2515     // different linkages.
2516     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2517       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2518                                 Decl->getUnderlyingType()))
2519         continue;
2520 
2521       // If both declarations give a tag declaration a typedef name for linkage
2522       // purposes, then they declare the same entity.
2523       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2524           Decl->getAnonDeclWithTypedefName())
2525         continue;
2526     }
2527 
2528     Filter.erase();
2529   }
2530 
2531   Filter.done();
2532 }
2533 
2534 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2535   QualType OldType;
2536   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2537     OldType = OldTypedef->getUnderlyingType();
2538   else
2539     OldType = Context.getTypeDeclType(Old);
2540   QualType NewType = New->getUnderlyingType();
2541 
2542   if (NewType->isVariablyModifiedType()) {
2543     // Must not redefine a typedef with a variably-modified type.
2544     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2545     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2546       << Kind << NewType;
2547     if (Old->getLocation().isValid())
2548       notePreviousDefinition(Old, New->getLocation());
2549     New->setInvalidDecl();
2550     return true;
2551   }
2552 
2553   if (OldType != NewType &&
2554       !OldType->isDependentType() &&
2555       !NewType->isDependentType() &&
2556       !Context.hasSameType(OldType, NewType)) {
2557     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2558     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2559       << Kind << NewType << OldType;
2560     if (Old->getLocation().isValid())
2561       notePreviousDefinition(Old, New->getLocation());
2562     New->setInvalidDecl();
2563     return true;
2564   }
2565   return false;
2566 }
2567 
2568 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2569 /// same name and scope as a previous declaration 'Old'.  Figure out
2570 /// how to resolve this situation, merging decls or emitting
2571 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2572 ///
2573 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2574                                 LookupResult &OldDecls) {
2575   // If the new decl is known invalid already, don't bother doing any
2576   // merging checks.
2577   if (New->isInvalidDecl()) return;
2578 
2579   // Allow multiple definitions for ObjC built-in typedefs.
2580   // FIXME: Verify the underlying types are equivalent!
2581   if (getLangOpts().ObjC) {
2582     const IdentifierInfo *TypeID = New->getIdentifier();
2583     switch (TypeID->getLength()) {
2584     default: break;
2585     case 2:
2586       {
2587         if (!TypeID->isStr("id"))
2588           break;
2589         QualType T = New->getUnderlyingType();
2590         if (!T->isPointerType())
2591           break;
2592         if (!T->isVoidPointerType()) {
2593           QualType PT = T->castAs<PointerType>()->getPointeeType();
2594           if (!PT->isStructureType())
2595             break;
2596         }
2597         Context.setObjCIdRedefinitionType(T);
2598         // Install the built-in type for 'id', ignoring the current definition.
2599         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2600         return;
2601       }
2602     case 5:
2603       if (!TypeID->isStr("Class"))
2604         break;
2605       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2606       // Install the built-in type for 'Class', ignoring the current definition.
2607       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2608       return;
2609     case 3:
2610       if (!TypeID->isStr("SEL"))
2611         break;
2612       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2613       // Install the built-in type for 'SEL', ignoring the current definition.
2614       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2615       return;
2616     }
2617     // Fall through - the typedef name was not a builtin type.
2618   }
2619 
2620   // Verify the old decl was also a type.
2621   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2622   if (!Old) {
2623     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2624       << New->getDeclName();
2625 
2626     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2627     if (OldD->getLocation().isValid())
2628       notePreviousDefinition(OldD, New->getLocation());
2629 
2630     return New->setInvalidDecl();
2631   }
2632 
2633   // If the old declaration is invalid, just give up here.
2634   if (Old->isInvalidDecl())
2635     return New->setInvalidDecl();
2636 
2637   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2638     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2639     auto *NewTag = New->getAnonDeclWithTypedefName();
2640     NamedDecl *Hidden = nullptr;
2641     if (OldTag && NewTag &&
2642         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2643         !hasVisibleDefinition(OldTag, &Hidden)) {
2644       // There is a definition of this tag, but it is not visible. Use it
2645       // instead of our tag.
2646       New->setTypeForDecl(OldTD->getTypeForDecl());
2647       if (OldTD->isModed())
2648         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2649                                     OldTD->getUnderlyingType());
2650       else
2651         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2652 
2653       // Make the old tag definition visible.
2654       makeMergedDefinitionVisible(Hidden);
2655 
2656       // If this was an unscoped enumeration, yank all of its enumerators
2657       // out of the scope.
2658       if (isa<EnumDecl>(NewTag)) {
2659         Scope *EnumScope = getNonFieldDeclScope(S);
2660         for (auto *D : NewTag->decls()) {
2661           auto *ED = cast<EnumConstantDecl>(D);
2662           assert(EnumScope->isDeclScope(ED));
2663           EnumScope->RemoveDecl(ED);
2664           IdResolver.RemoveDecl(ED);
2665           ED->getLexicalDeclContext()->removeDecl(ED);
2666         }
2667       }
2668     }
2669   }
2670 
2671   // If the typedef types are not identical, reject them in all languages and
2672   // with any extensions enabled.
2673   if (isIncompatibleTypedef(Old, New))
2674     return;
2675 
2676   // The types match.  Link up the redeclaration chain and merge attributes if
2677   // the old declaration was a typedef.
2678   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2679     New->setPreviousDecl(Typedef);
2680     mergeDeclAttributes(New, Old);
2681   }
2682 
2683   if (getLangOpts().MicrosoftExt)
2684     return;
2685 
2686   if (getLangOpts().CPlusPlus) {
2687     // C++ [dcl.typedef]p2:
2688     //   In a given non-class scope, a typedef specifier can be used to
2689     //   redefine the name of any type declared in that scope to refer
2690     //   to the type to which it already refers.
2691     if (!isa<CXXRecordDecl>(CurContext))
2692       return;
2693 
2694     // C++0x [dcl.typedef]p4:
2695     //   In a given class scope, a typedef specifier can be used to redefine
2696     //   any class-name declared in that scope that is not also a typedef-name
2697     //   to refer to the type to which it already refers.
2698     //
2699     // This wording came in via DR424, which was a correction to the
2700     // wording in DR56, which accidentally banned code like:
2701     //
2702     //   struct S {
2703     //     typedef struct A { } A;
2704     //   };
2705     //
2706     // in the C++03 standard. We implement the C++0x semantics, which
2707     // allow the above but disallow
2708     //
2709     //   struct S {
2710     //     typedef int I;
2711     //     typedef int I;
2712     //   };
2713     //
2714     // since that was the intent of DR56.
2715     if (!isa<TypedefNameDecl>(Old))
2716       return;
2717 
2718     Diag(New->getLocation(), diag::err_redefinition)
2719       << New->getDeclName();
2720     notePreviousDefinition(Old, New->getLocation());
2721     return New->setInvalidDecl();
2722   }
2723 
2724   // Modules always permit redefinition of typedefs, as does C11.
2725   if (getLangOpts().Modules || getLangOpts().C11)
2726     return;
2727 
2728   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2729   // is normally mapped to an error, but can be controlled with
2730   // -Wtypedef-redefinition.  If either the original or the redefinition is
2731   // in a system header, don't emit this for compatibility with GCC.
2732   if (getDiagnostics().getSuppressSystemWarnings() &&
2733       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2734       (Old->isImplicit() ||
2735        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2736        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2737     return;
2738 
2739   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2740     << New->getDeclName();
2741   notePreviousDefinition(Old, New->getLocation());
2742 }
2743 
2744 /// DeclhasAttr - returns true if decl Declaration already has the target
2745 /// attribute.
2746 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2747   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2748   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2749   for (const auto *i : D->attrs())
2750     if (i->getKind() == A->getKind()) {
2751       if (Ann) {
2752         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2753           return true;
2754         continue;
2755       }
2756       // FIXME: Don't hardcode this check
2757       if (OA && isa<OwnershipAttr>(i))
2758         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2759       return true;
2760     }
2761 
2762   return false;
2763 }
2764 
2765 static bool isAttributeTargetADefinition(Decl *D) {
2766   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2767     return VD->isThisDeclarationADefinition();
2768   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2769     return TD->isCompleteDefinition() || TD->isBeingDefined();
2770   return true;
2771 }
2772 
2773 /// Merge alignment attributes from \p Old to \p New, taking into account the
2774 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2775 ///
2776 /// \return \c true if any attributes were added to \p New.
2777 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2778   // Look for alignas attributes on Old, and pick out whichever attribute
2779   // specifies the strictest alignment requirement.
2780   AlignedAttr *OldAlignasAttr = nullptr;
2781   AlignedAttr *OldStrictestAlignAttr = nullptr;
2782   unsigned OldAlign = 0;
2783   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2784     // FIXME: We have no way of representing inherited dependent alignments
2785     // in a case like:
2786     //   template<int A, int B> struct alignas(A) X;
2787     //   template<int A, int B> struct alignas(B) X {};
2788     // For now, we just ignore any alignas attributes which are not on the
2789     // definition in such a case.
2790     if (I->isAlignmentDependent())
2791       return false;
2792 
2793     if (I->isAlignas())
2794       OldAlignasAttr = I;
2795 
2796     unsigned Align = I->getAlignment(S.Context);
2797     if (Align > OldAlign) {
2798       OldAlign = Align;
2799       OldStrictestAlignAttr = I;
2800     }
2801   }
2802 
2803   // Look for alignas attributes on New.
2804   AlignedAttr *NewAlignasAttr = nullptr;
2805   unsigned NewAlign = 0;
2806   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2807     if (I->isAlignmentDependent())
2808       return false;
2809 
2810     if (I->isAlignas())
2811       NewAlignasAttr = I;
2812 
2813     unsigned Align = I->getAlignment(S.Context);
2814     if (Align > NewAlign)
2815       NewAlign = Align;
2816   }
2817 
2818   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2819     // Both declarations have 'alignas' attributes. We require them to match.
2820     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2821     // fall short. (If two declarations both have alignas, they must both match
2822     // every definition, and so must match each other if there is a definition.)
2823 
2824     // If either declaration only contains 'alignas(0)' specifiers, then it
2825     // specifies the natural alignment for the type.
2826     if (OldAlign == 0 || NewAlign == 0) {
2827       QualType Ty;
2828       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2829         Ty = VD->getType();
2830       else
2831         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2832 
2833       if (OldAlign == 0)
2834         OldAlign = S.Context.getTypeAlign(Ty);
2835       if (NewAlign == 0)
2836         NewAlign = S.Context.getTypeAlign(Ty);
2837     }
2838 
2839     if (OldAlign != NewAlign) {
2840       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2841         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2842         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2843       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2844     }
2845   }
2846 
2847   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2848     // C++11 [dcl.align]p6:
2849     //   if any declaration of an entity has an alignment-specifier,
2850     //   every defining declaration of that entity shall specify an
2851     //   equivalent alignment.
2852     // C11 6.7.5/7:
2853     //   If the definition of an object does not have an alignment
2854     //   specifier, any other declaration of that object shall also
2855     //   have no alignment specifier.
2856     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2857       << OldAlignasAttr;
2858     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2859       << OldAlignasAttr;
2860   }
2861 
2862   bool AnyAdded = false;
2863 
2864   // Ensure we have an attribute representing the strictest alignment.
2865   if (OldAlign > NewAlign) {
2866     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2867     Clone->setInherited(true);
2868     New->addAttr(Clone);
2869     AnyAdded = true;
2870   }
2871 
2872   // Ensure we have an alignas attribute if the old declaration had one.
2873   if (OldAlignasAttr && !NewAlignasAttr &&
2874       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2875     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2876     Clone->setInherited(true);
2877     New->addAttr(Clone);
2878     AnyAdded = true;
2879   }
2880 
2881   return AnyAdded;
2882 }
2883 
2884 #define WANT_DECL_MERGE_LOGIC
2885 #include "clang/Sema/AttrParsedAttrImpl.inc"
2886 #undef WANT_DECL_MERGE_LOGIC
2887 
2888 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2889                                const InheritableAttr *Attr,
2890                                Sema::AvailabilityMergeKind AMK) {
2891   // Diagnose any mutual exclusions between the attribute that we want to add
2892   // and attributes that already exist on the declaration.
2893   if (!DiagnoseMutualExclusions(S, D, Attr))
2894     return false;
2895 
2896   // This function copies an attribute Attr from a previous declaration to the
2897   // new declaration D if the new declaration doesn't itself have that attribute
2898   // yet or if that attribute allows duplicates.
2899   // If you're adding a new attribute that requires logic different from
2900   // "use explicit attribute on decl if present, else use attribute from
2901   // previous decl", for example if the attribute needs to be consistent
2902   // between redeclarations, you need to call a custom merge function here.
2903   InheritableAttr *NewAttr = nullptr;
2904   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2905     NewAttr = S.mergeAvailabilityAttr(
2906         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2907         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2908         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2909         AA->getPriority());
2910   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2911     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2912   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2913     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2914   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2915     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2916   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2917     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2918   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2919     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2920   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2921     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2922                                 FA->getFirstArg());
2923   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2924     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2925   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2926     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2927   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2928     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2929                                        IA->getInheritanceModel());
2930   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2931     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2932                                       &S.Context.Idents.get(AA->getSpelling()));
2933   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2934            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2935             isa<CUDAGlobalAttr>(Attr))) {
2936     // CUDA target attributes are part of function signature for
2937     // overloading purposes and must not be merged.
2938     return false;
2939   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2940     NewAttr = S.mergeMinSizeAttr(D, *MA);
2941   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2942     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2943   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2944     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2945   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2946     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2947   else if (isa<AlignedAttr>(Attr))
2948     // AlignedAttrs are handled separately, because we need to handle all
2949     // such attributes on a declaration at the same time.
2950     NewAttr = nullptr;
2951   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2952            (AMK == Sema::AMK_Override ||
2953             AMK == Sema::AMK_ProtocolImplementation ||
2954             AMK == Sema::AMK_OptionalProtocolImplementation))
2955     NewAttr = nullptr;
2956   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2957     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2958   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2959     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2960   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2961     NewAttr = S.mergeImportNameAttr(D, *INA);
2962   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2963     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2964   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2965     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2966   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2967     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2968   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2969     NewAttr =
2970         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2971   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2972     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2973   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2974     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2975 
2976   if (NewAttr) {
2977     NewAttr->setInherited(true);
2978     D->addAttr(NewAttr);
2979     if (isa<MSInheritanceAttr>(NewAttr))
2980       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2981     return true;
2982   }
2983 
2984   return false;
2985 }
2986 
2987 static const NamedDecl *getDefinition(const Decl *D) {
2988   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2989     return TD->getDefinition();
2990   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2991     const VarDecl *Def = VD->getDefinition();
2992     if (Def)
2993       return Def;
2994     return VD->getActingDefinition();
2995   }
2996   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2997     const FunctionDecl *Def = nullptr;
2998     if (FD->isDefined(Def, true))
2999       return Def;
3000   }
3001   return nullptr;
3002 }
3003 
3004 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3005   for (const auto *Attribute : D->attrs())
3006     if (Attribute->getKind() == Kind)
3007       return true;
3008   return false;
3009 }
3010 
3011 /// checkNewAttributesAfterDef - If we already have a definition, check that
3012 /// there are no new attributes in this declaration.
3013 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3014   if (!New->hasAttrs())
3015     return;
3016 
3017   const NamedDecl *Def = getDefinition(Old);
3018   if (!Def || Def == New)
3019     return;
3020 
3021   AttrVec &NewAttributes = New->getAttrs();
3022   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3023     const Attr *NewAttribute = NewAttributes[I];
3024 
3025     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3026       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3027         Sema::SkipBodyInfo SkipBody;
3028         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3029 
3030         // If we're skipping this definition, drop the "alias" attribute.
3031         if (SkipBody.ShouldSkip) {
3032           NewAttributes.erase(NewAttributes.begin() + I);
3033           --E;
3034           continue;
3035         }
3036       } else {
3037         VarDecl *VD = cast<VarDecl>(New);
3038         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3039                                 VarDecl::TentativeDefinition
3040                             ? diag::err_alias_after_tentative
3041                             : diag::err_redefinition;
3042         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3043         if (Diag == diag::err_redefinition)
3044           S.notePreviousDefinition(Def, VD->getLocation());
3045         else
3046           S.Diag(Def->getLocation(), diag::note_previous_definition);
3047         VD->setInvalidDecl();
3048       }
3049       ++I;
3050       continue;
3051     }
3052 
3053     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3054       // Tentative definitions are only interesting for the alias check above.
3055       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3056         ++I;
3057         continue;
3058       }
3059     }
3060 
3061     if (hasAttribute(Def, NewAttribute->getKind())) {
3062       ++I;
3063       continue; // regular attr merging will take care of validating this.
3064     }
3065 
3066     if (isa<C11NoReturnAttr>(NewAttribute)) {
3067       // C's _Noreturn is allowed to be added to a function after it is defined.
3068       ++I;
3069       continue;
3070     } else if (isa<UuidAttr>(NewAttribute)) {
3071       // msvc will allow a subsequent definition to add an uuid to a class
3072       ++I;
3073       continue;
3074     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3075       if (AA->isAlignas()) {
3076         // C++11 [dcl.align]p6:
3077         //   if any declaration of an entity has an alignment-specifier,
3078         //   every defining declaration of that entity shall specify an
3079         //   equivalent alignment.
3080         // C11 6.7.5/7:
3081         //   If the definition of an object does not have an alignment
3082         //   specifier, any other declaration of that object shall also
3083         //   have no alignment specifier.
3084         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3085           << AA;
3086         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3087           << AA;
3088         NewAttributes.erase(NewAttributes.begin() + I);
3089         --E;
3090         continue;
3091       }
3092     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3093       // If there is a C definition followed by a redeclaration with this
3094       // attribute then there are two different definitions. In C++, prefer the
3095       // standard diagnostics.
3096       if (!S.getLangOpts().CPlusPlus) {
3097         S.Diag(NewAttribute->getLocation(),
3098                diag::err_loader_uninitialized_redeclaration);
3099         S.Diag(Def->getLocation(), diag::note_previous_definition);
3100         NewAttributes.erase(NewAttributes.begin() + I);
3101         --E;
3102         continue;
3103       }
3104     } else if (isa<SelectAnyAttr>(NewAttribute) &&
3105                cast<VarDecl>(New)->isInline() &&
3106                !cast<VarDecl>(New)->isInlineSpecified()) {
3107       // Don't warn about applying selectany to implicitly inline variables.
3108       // Older compilers and language modes would require the use of selectany
3109       // to make such variables inline, and it would have no effect if we
3110       // honored it.
3111       ++I;
3112       continue;
3113     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3114       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3115       // declarations after definitions.
3116       ++I;
3117       continue;
3118     }
3119 
3120     S.Diag(NewAttribute->getLocation(),
3121            diag::warn_attribute_precede_definition);
3122     S.Diag(Def->getLocation(), diag::note_previous_definition);
3123     NewAttributes.erase(NewAttributes.begin() + I);
3124     --E;
3125   }
3126 }
3127 
3128 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3129                                      const ConstInitAttr *CIAttr,
3130                                      bool AttrBeforeInit) {
3131   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3132 
3133   // Figure out a good way to write this specifier on the old declaration.
3134   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3135   // enough of the attribute list spelling information to extract that without
3136   // heroics.
3137   std::string SuitableSpelling;
3138   if (S.getLangOpts().CPlusPlus20)
3139     SuitableSpelling = std::string(
3140         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3141   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3142     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3143         InsertLoc, {tok::l_square, tok::l_square,
3144                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3145                     S.PP.getIdentifierInfo("require_constant_initialization"),
3146                     tok::r_square, tok::r_square}));
3147   if (SuitableSpelling.empty())
3148     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3149         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3150                     S.PP.getIdentifierInfo("require_constant_initialization"),
3151                     tok::r_paren, tok::r_paren}));
3152   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3153     SuitableSpelling = "constinit";
3154   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3155     SuitableSpelling = "[[clang::require_constant_initialization]]";
3156   if (SuitableSpelling.empty())
3157     SuitableSpelling = "__attribute__((require_constant_initialization))";
3158   SuitableSpelling += " ";
3159 
3160   if (AttrBeforeInit) {
3161     // extern constinit int a;
3162     // int a = 0; // error (missing 'constinit'), accepted as extension
3163     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3164     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3165         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3166     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3167   } else {
3168     // int a = 0;
3169     // constinit extern int a; // error (missing 'constinit')
3170     S.Diag(CIAttr->getLocation(),
3171            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3172                                  : diag::warn_require_const_init_added_too_late)
3173         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3174     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3175         << CIAttr->isConstinit()
3176         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3177   }
3178 }
3179 
3180 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3181 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3182                                AvailabilityMergeKind AMK) {
3183   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3184     UsedAttr *NewAttr = OldAttr->clone(Context);
3185     NewAttr->setInherited(true);
3186     New->addAttr(NewAttr);
3187   }
3188   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3189     RetainAttr *NewAttr = OldAttr->clone(Context);
3190     NewAttr->setInherited(true);
3191     New->addAttr(NewAttr);
3192   }
3193 
3194   if (!Old->hasAttrs() && !New->hasAttrs())
3195     return;
3196 
3197   // [dcl.constinit]p1:
3198   //   If the [constinit] specifier is applied to any declaration of a
3199   //   variable, it shall be applied to the initializing declaration.
3200   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3201   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3202   if (bool(OldConstInit) != bool(NewConstInit)) {
3203     const auto *OldVD = cast<VarDecl>(Old);
3204     auto *NewVD = cast<VarDecl>(New);
3205 
3206     // Find the initializing declaration. Note that we might not have linked
3207     // the new declaration into the redeclaration chain yet.
3208     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3209     if (!InitDecl &&
3210         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3211       InitDecl = NewVD;
3212 
3213     if (InitDecl == NewVD) {
3214       // This is the initializing declaration. If it would inherit 'constinit',
3215       // that's ill-formed. (Note that we do not apply this to the attribute
3216       // form).
3217       if (OldConstInit && OldConstInit->isConstinit())
3218         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3219                                  /*AttrBeforeInit=*/true);
3220     } else if (NewConstInit) {
3221       // This is the first time we've been told that this declaration should
3222       // have a constant initializer. If we already saw the initializing
3223       // declaration, this is too late.
3224       if (InitDecl && InitDecl != NewVD) {
3225         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3226                                  /*AttrBeforeInit=*/false);
3227         NewVD->dropAttr<ConstInitAttr>();
3228       }
3229     }
3230   }
3231 
3232   // Attributes declared post-definition are currently ignored.
3233   checkNewAttributesAfterDef(*this, New, Old);
3234 
3235   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3236     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3237       if (!OldA->isEquivalent(NewA)) {
3238         // This redeclaration changes __asm__ label.
3239         Diag(New->getLocation(), diag::err_different_asm_label);
3240         Diag(OldA->getLocation(), diag::note_previous_declaration);
3241       }
3242     } else if (Old->isUsed()) {
3243       // This redeclaration adds an __asm__ label to a declaration that has
3244       // already been ODR-used.
3245       Diag(New->getLocation(), diag::err_late_asm_label_name)
3246         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3247     }
3248   }
3249 
3250   // Re-declaration cannot add abi_tag's.
3251   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3252     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3253       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3254         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3255           Diag(NewAbiTagAttr->getLocation(),
3256                diag::err_new_abi_tag_on_redeclaration)
3257               << NewTag;
3258           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3259         }
3260       }
3261     } else {
3262       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3263       Diag(Old->getLocation(), diag::note_previous_declaration);
3264     }
3265   }
3266 
3267   // This redeclaration adds a section attribute.
3268   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3269     if (auto *VD = dyn_cast<VarDecl>(New)) {
3270       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3271         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3272         Diag(Old->getLocation(), diag::note_previous_declaration);
3273       }
3274     }
3275   }
3276 
3277   // Redeclaration adds code-seg attribute.
3278   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3279   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3280       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3281     Diag(New->getLocation(), diag::warn_mismatched_section)
3282          << 0 /*codeseg*/;
3283     Diag(Old->getLocation(), diag::note_previous_declaration);
3284   }
3285 
3286   if (!Old->hasAttrs())
3287     return;
3288 
3289   bool foundAny = New->hasAttrs();
3290 
3291   // Ensure that any moving of objects within the allocated map is done before
3292   // we process them.
3293   if (!foundAny) New->setAttrs(AttrVec());
3294 
3295   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3296     // Ignore deprecated/unavailable/availability attributes if requested.
3297     AvailabilityMergeKind LocalAMK = AMK_None;
3298     if (isa<DeprecatedAttr>(I) ||
3299         isa<UnavailableAttr>(I) ||
3300         isa<AvailabilityAttr>(I)) {
3301       switch (AMK) {
3302       case AMK_None:
3303         continue;
3304 
3305       case AMK_Redeclaration:
3306       case AMK_Override:
3307       case AMK_ProtocolImplementation:
3308       case AMK_OptionalProtocolImplementation:
3309         LocalAMK = AMK;
3310         break;
3311       }
3312     }
3313 
3314     // Already handled.
3315     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3316       continue;
3317 
3318     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3319       foundAny = true;
3320   }
3321 
3322   if (mergeAlignedAttrs(*this, New, Old))
3323     foundAny = true;
3324 
3325   if (!foundAny) New->dropAttrs();
3326 }
3327 
3328 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3329 /// to the new one.
3330 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3331                                      const ParmVarDecl *oldDecl,
3332                                      Sema &S) {
3333   // C++11 [dcl.attr.depend]p2:
3334   //   The first declaration of a function shall specify the
3335   //   carries_dependency attribute for its declarator-id if any declaration
3336   //   of the function specifies the carries_dependency attribute.
3337   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3338   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3339     S.Diag(CDA->getLocation(),
3340            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3341     // Find the first declaration of the parameter.
3342     // FIXME: Should we build redeclaration chains for function parameters?
3343     const FunctionDecl *FirstFD =
3344       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3345     const ParmVarDecl *FirstVD =
3346       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3347     S.Diag(FirstVD->getLocation(),
3348            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3349   }
3350 
3351   if (!oldDecl->hasAttrs())
3352     return;
3353 
3354   bool foundAny = newDecl->hasAttrs();
3355 
3356   // Ensure that any moving of objects within the allocated map is
3357   // done before we process them.
3358   if (!foundAny) newDecl->setAttrs(AttrVec());
3359 
3360   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3361     if (!DeclHasAttr(newDecl, I)) {
3362       InheritableAttr *newAttr =
3363         cast<InheritableParamAttr>(I->clone(S.Context));
3364       newAttr->setInherited(true);
3365       newDecl->addAttr(newAttr);
3366       foundAny = true;
3367     }
3368   }
3369 
3370   if (!foundAny) newDecl->dropAttrs();
3371 }
3372 
3373 static bool EquivalentArrayTypes(QualType Old, QualType New,
3374                                  const ASTContext &Ctx) {
3375 
3376   auto NoSizeInfo = [&Ctx](QualType Ty) {
3377     if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3378       return true;
3379     if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3380       return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3381     return false;
3382   };
3383 
3384   // `type[]` is equivalent to `type *` and `type[*]`.
3385   if (NoSizeInfo(Old) && NoSizeInfo(New))
3386     return true;
3387 
3388   // Don't try to compare VLA sizes, unless one of them has the star modifier.
3389   if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3390     const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3391     const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3392     if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3393         (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3394       return false;
3395     return true;
3396   }
3397 
3398   // Only compare size, ignore Size modifiers and CVR.
3399   if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3400     return Ctx.getAsConstantArrayType(Old)->getSize() ==
3401            Ctx.getAsConstantArrayType(New)->getSize();
3402   }
3403 
3404   // Don't try to compare dependent sized array
3405   if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3406     return true;
3407   }
3408 
3409   return Old == New;
3410 }
3411 
3412 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3413                                 const ParmVarDecl *OldParam,
3414                                 Sema &S) {
3415   if (auto Oldnullability = OldParam->getType()->getNullability()) {
3416     if (auto Newnullability = NewParam->getType()->getNullability()) {
3417       if (*Oldnullability != *Newnullability) {
3418         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3419           << DiagNullabilityKind(
3420                *Newnullability,
3421                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3422                 != 0))
3423           << DiagNullabilityKind(
3424                *Oldnullability,
3425                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3426                 != 0));
3427         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3428       }
3429     } else {
3430       QualType NewT = NewParam->getType();
3431       NewT = S.Context.getAttributedType(
3432                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3433                          NewT, NewT);
3434       NewParam->setType(NewT);
3435     }
3436   }
3437   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3438   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3439   if (OldParamDT && NewParamDT &&
3440       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3441     QualType OldParamOT = OldParamDT->getOriginalType();
3442     QualType NewParamOT = NewParamDT->getOriginalType();
3443     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3444       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3445           << NewParam << NewParamOT;
3446       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3447           << OldParamOT;
3448     }
3449   }
3450 }
3451 
3452 namespace {
3453 
3454 /// Used in MergeFunctionDecl to keep track of function parameters in
3455 /// C.
3456 struct GNUCompatibleParamWarning {
3457   ParmVarDecl *OldParm;
3458   ParmVarDecl *NewParm;
3459   QualType PromotedType;
3460 };
3461 
3462 } // end anonymous namespace
3463 
3464 // Determine whether the previous declaration was a definition, implicit
3465 // declaration, or a declaration.
3466 template <typename T>
3467 static std::pair<diag::kind, SourceLocation>
3468 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3469   diag::kind PrevDiag;
3470   SourceLocation OldLocation = Old->getLocation();
3471   if (Old->isThisDeclarationADefinition())
3472     PrevDiag = diag::note_previous_definition;
3473   else if (Old->isImplicit()) {
3474     PrevDiag = diag::note_previous_implicit_declaration;
3475     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3476       if (FD->getBuiltinID())
3477         PrevDiag = diag::note_previous_builtin_declaration;
3478     }
3479     if (OldLocation.isInvalid())
3480       OldLocation = New->getLocation();
3481   } else
3482     PrevDiag = diag::note_previous_declaration;
3483   return std::make_pair(PrevDiag, OldLocation);
3484 }
3485 
3486 /// canRedefineFunction - checks if a function can be redefined. Currently,
3487 /// only extern inline functions can be redefined, and even then only in
3488 /// GNU89 mode.
3489 static bool canRedefineFunction(const FunctionDecl *FD,
3490                                 const LangOptions& LangOpts) {
3491   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3492           !LangOpts.CPlusPlus &&
3493           FD->isInlineSpecified() &&
3494           FD->getStorageClass() == SC_Extern);
3495 }
3496 
3497 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3498   const AttributedType *AT = T->getAs<AttributedType>();
3499   while (AT && !AT->isCallingConv())
3500     AT = AT->getModifiedType()->getAs<AttributedType>();
3501   return AT;
3502 }
3503 
3504 template <typename T>
3505 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3506   const DeclContext *DC = Old->getDeclContext();
3507   if (DC->isRecord())
3508     return false;
3509 
3510   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3511   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3512     return true;
3513   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3514     return true;
3515   return false;
3516 }
3517 
3518 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3519 static bool isExternC(VarTemplateDecl *) { return false; }
3520 static bool isExternC(FunctionTemplateDecl *) { return false; }
3521 
3522 /// Check whether a redeclaration of an entity introduced by a
3523 /// using-declaration is valid, given that we know it's not an overload
3524 /// (nor a hidden tag declaration).
3525 template<typename ExpectedDecl>
3526 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3527                                    ExpectedDecl *New) {
3528   // C++11 [basic.scope.declarative]p4:
3529   //   Given a set of declarations in a single declarative region, each of
3530   //   which specifies the same unqualified name,
3531   //   -- they shall all refer to the same entity, or all refer to functions
3532   //      and function templates; or
3533   //   -- exactly one declaration shall declare a class name or enumeration
3534   //      name that is not a typedef name and the other declarations shall all
3535   //      refer to the same variable or enumerator, or all refer to functions
3536   //      and function templates; in this case the class name or enumeration
3537   //      name is hidden (3.3.10).
3538 
3539   // C++11 [namespace.udecl]p14:
3540   //   If a function declaration in namespace scope or block scope has the
3541   //   same name and the same parameter-type-list as a function introduced
3542   //   by a using-declaration, and the declarations do not declare the same
3543   //   function, the program is ill-formed.
3544 
3545   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3546   if (Old &&
3547       !Old->getDeclContext()->getRedeclContext()->Equals(
3548           New->getDeclContext()->getRedeclContext()) &&
3549       !(isExternC(Old) && isExternC(New)))
3550     Old = nullptr;
3551 
3552   if (!Old) {
3553     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3554     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3555     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3556     return true;
3557   }
3558   return false;
3559 }
3560 
3561 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3562                                             const FunctionDecl *B) {
3563   assert(A->getNumParams() == B->getNumParams());
3564 
3565   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3566     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3567     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3568     if (AttrA == AttrB)
3569       return true;
3570     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3571            AttrA->isDynamic() == AttrB->isDynamic();
3572   };
3573 
3574   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3575 }
3576 
3577 /// If necessary, adjust the semantic declaration context for a qualified
3578 /// declaration to name the correct inline namespace within the qualifier.
3579 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3580                                                DeclaratorDecl *OldD) {
3581   // The only case where we need to update the DeclContext is when
3582   // redeclaration lookup for a qualified name finds a declaration
3583   // in an inline namespace within the context named by the qualifier:
3584   //
3585   //   inline namespace N { int f(); }
3586   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3587   //
3588   // For unqualified declarations, the semantic context *can* change
3589   // along the redeclaration chain (for local extern declarations,
3590   // extern "C" declarations, and friend declarations in particular).
3591   if (!NewD->getQualifier())
3592     return;
3593 
3594   // NewD is probably already in the right context.
3595   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3596   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3597   if (NamedDC->Equals(SemaDC))
3598     return;
3599 
3600   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3601           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3602          "unexpected context for redeclaration");
3603 
3604   auto *LexDC = NewD->getLexicalDeclContext();
3605   auto FixSemaDC = [=](NamedDecl *D) {
3606     if (!D)
3607       return;
3608     D->setDeclContext(SemaDC);
3609     D->setLexicalDeclContext(LexDC);
3610   };
3611 
3612   FixSemaDC(NewD);
3613   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3614     FixSemaDC(FD->getDescribedFunctionTemplate());
3615   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3616     FixSemaDC(VD->getDescribedVarTemplate());
3617 }
3618 
3619 /// MergeFunctionDecl - We just parsed a function 'New' from
3620 /// declarator D which has the same name and scope as a previous
3621 /// declaration 'Old'.  Figure out how to resolve this situation,
3622 /// merging decls or emitting diagnostics as appropriate.
3623 ///
3624 /// In C++, New and Old must be declarations that are not
3625 /// overloaded. Use IsOverload to determine whether New and Old are
3626 /// overloaded, and to select the Old declaration that New should be
3627 /// merged with.
3628 ///
3629 /// Returns true if there was an error, false otherwise.
3630 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3631                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3632   // Verify the old decl was also a function.
3633   FunctionDecl *Old = OldD->getAsFunction();
3634   if (!Old) {
3635     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3636       if (New->getFriendObjectKind()) {
3637         Diag(New->getLocation(), diag::err_using_decl_friend);
3638         Diag(Shadow->getTargetDecl()->getLocation(),
3639              diag::note_using_decl_target);
3640         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3641             << 0;
3642         return true;
3643       }
3644 
3645       // Check whether the two declarations might declare the same function or
3646       // function template.
3647       if (FunctionTemplateDecl *NewTemplate =
3648               New->getDescribedFunctionTemplate()) {
3649         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3650                                                          NewTemplate))
3651           return true;
3652         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3653                          ->getAsFunction();
3654       } else {
3655         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3656           return true;
3657         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3658       }
3659     } else {
3660       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3661         << New->getDeclName();
3662       notePreviousDefinition(OldD, New->getLocation());
3663       return true;
3664     }
3665   }
3666 
3667   // If the old declaration was found in an inline namespace and the new
3668   // declaration was qualified, update the DeclContext to match.
3669   adjustDeclContextForDeclaratorDecl(New, Old);
3670 
3671   // If the old declaration is invalid, just give up here.
3672   if (Old->isInvalidDecl())
3673     return true;
3674 
3675   // Disallow redeclaration of some builtins.
3676   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3677     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3678     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3679         << Old << Old->getType();
3680     return true;
3681   }
3682 
3683   diag::kind PrevDiag;
3684   SourceLocation OldLocation;
3685   std::tie(PrevDiag, OldLocation) =
3686       getNoteDiagForInvalidRedeclaration(Old, New);
3687 
3688   // Don't complain about this if we're in GNU89 mode and the old function
3689   // is an extern inline function.
3690   // Don't complain about specializations. They are not supposed to have
3691   // storage classes.
3692   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3693       New->getStorageClass() == SC_Static &&
3694       Old->hasExternalFormalLinkage() &&
3695       !New->getTemplateSpecializationInfo() &&
3696       !canRedefineFunction(Old, getLangOpts())) {
3697     if (getLangOpts().MicrosoftExt) {
3698       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3699       Diag(OldLocation, PrevDiag) << Old << Old->getType();
3700     } else {
3701       Diag(New->getLocation(), diag::err_static_non_static) << New;
3702       Diag(OldLocation, PrevDiag) << Old << Old->getType();
3703       return true;
3704     }
3705   }
3706 
3707   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3708     if (!Old->hasAttr<InternalLinkageAttr>()) {
3709       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3710           << ILA;
3711       Diag(Old->getLocation(), diag::note_previous_declaration);
3712       New->dropAttr<InternalLinkageAttr>();
3713     }
3714 
3715   if (auto *EA = New->getAttr<ErrorAttr>()) {
3716     if (!Old->hasAttr<ErrorAttr>()) {
3717       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3718       Diag(Old->getLocation(), diag::note_previous_declaration);
3719       New->dropAttr<ErrorAttr>();
3720     }
3721   }
3722 
3723   if (CheckRedeclarationInModule(New, Old))
3724     return true;
3725 
3726   if (!getLangOpts().CPlusPlus) {
3727     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3728     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3729       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3730         << New << OldOvl;
3731 
3732       // Try our best to find a decl that actually has the overloadable
3733       // attribute for the note. In most cases (e.g. programs with only one
3734       // broken declaration/definition), this won't matter.
3735       //
3736       // FIXME: We could do this if we juggled some extra state in
3737       // OverloadableAttr, rather than just removing it.
3738       const Decl *DiagOld = Old;
3739       if (OldOvl) {
3740         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3741           const auto *A = D->getAttr<OverloadableAttr>();
3742           return A && !A->isImplicit();
3743         });
3744         // If we've implicitly added *all* of the overloadable attrs to this
3745         // chain, emitting a "previous redecl" note is pointless.
3746         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3747       }
3748 
3749       if (DiagOld)
3750         Diag(DiagOld->getLocation(),
3751              diag::note_attribute_overloadable_prev_overload)
3752           << OldOvl;
3753 
3754       if (OldOvl)
3755         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3756       else
3757         New->dropAttr<OverloadableAttr>();
3758     }
3759   }
3760 
3761   // If a function is first declared with a calling convention, but is later
3762   // declared or defined without one, all following decls assume the calling
3763   // convention of the first.
3764   //
3765   // It's OK if a function is first declared without a calling convention,
3766   // but is later declared or defined with the default calling convention.
3767   //
3768   // To test if either decl has an explicit calling convention, we look for
3769   // AttributedType sugar nodes on the type as written.  If they are missing or
3770   // were canonicalized away, we assume the calling convention was implicit.
3771   //
3772   // Note also that we DO NOT return at this point, because we still have
3773   // other tests to run.
3774   QualType OldQType = Context.getCanonicalType(Old->getType());
3775   QualType NewQType = Context.getCanonicalType(New->getType());
3776   const FunctionType *OldType = cast<FunctionType>(OldQType);
3777   const FunctionType *NewType = cast<FunctionType>(NewQType);
3778   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3779   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3780   bool RequiresAdjustment = false;
3781 
3782   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3783     FunctionDecl *First = Old->getFirstDecl();
3784     const FunctionType *FT =
3785         First->getType().getCanonicalType()->castAs<FunctionType>();
3786     FunctionType::ExtInfo FI = FT->getExtInfo();
3787     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3788     if (!NewCCExplicit) {
3789       // Inherit the CC from the previous declaration if it was specified
3790       // there but not here.
3791       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3792       RequiresAdjustment = true;
3793     } else if (Old->getBuiltinID()) {
3794       // Builtin attribute isn't propagated to the new one yet at this point,
3795       // so we check if the old one is a builtin.
3796 
3797       // Calling Conventions on a Builtin aren't really useful and setting a
3798       // default calling convention and cdecl'ing some builtin redeclarations is
3799       // common, so warn and ignore the calling convention on the redeclaration.
3800       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3801           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3802           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3803       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3804       RequiresAdjustment = true;
3805     } else {
3806       // Calling conventions aren't compatible, so complain.
3807       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3808       Diag(New->getLocation(), diag::err_cconv_change)
3809         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3810         << !FirstCCExplicit
3811         << (!FirstCCExplicit ? "" :
3812             FunctionType::getNameForCallConv(FI.getCC()));
3813 
3814       // Put the note on the first decl, since it is the one that matters.
3815       Diag(First->getLocation(), diag::note_previous_declaration);
3816       return true;
3817     }
3818   }
3819 
3820   // FIXME: diagnose the other way around?
3821   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3822     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3823     RequiresAdjustment = true;
3824   }
3825 
3826   // Merge regparm attribute.
3827   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3828       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3829     if (NewTypeInfo.getHasRegParm()) {
3830       Diag(New->getLocation(), diag::err_regparm_mismatch)
3831         << NewType->getRegParmType()
3832         << OldType->getRegParmType();
3833       Diag(OldLocation, diag::note_previous_declaration);
3834       return true;
3835     }
3836 
3837     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3838     RequiresAdjustment = true;
3839   }
3840 
3841   // Merge ns_returns_retained attribute.
3842   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3843     if (NewTypeInfo.getProducesResult()) {
3844       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3845           << "'ns_returns_retained'";
3846       Diag(OldLocation, diag::note_previous_declaration);
3847       return true;
3848     }
3849 
3850     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3851     RequiresAdjustment = true;
3852   }
3853 
3854   if (OldTypeInfo.getNoCallerSavedRegs() !=
3855       NewTypeInfo.getNoCallerSavedRegs()) {
3856     if (NewTypeInfo.getNoCallerSavedRegs()) {
3857       AnyX86NoCallerSavedRegistersAttr *Attr =
3858         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3859       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3860       Diag(OldLocation, diag::note_previous_declaration);
3861       return true;
3862     }
3863 
3864     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3865     RequiresAdjustment = true;
3866   }
3867 
3868   if (RequiresAdjustment) {
3869     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3870     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3871     New->setType(QualType(AdjustedType, 0));
3872     NewQType = Context.getCanonicalType(New->getType());
3873   }
3874 
3875   // If this redeclaration makes the function inline, we may need to add it to
3876   // UndefinedButUsed.
3877   if (!Old->isInlined() && New->isInlined() &&
3878       !New->hasAttr<GNUInlineAttr>() &&
3879       !getLangOpts().GNUInline &&
3880       Old->isUsed(false) &&
3881       !Old->isDefined() && !New->isThisDeclarationADefinition())
3882     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3883                                            SourceLocation()));
3884 
3885   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3886   // about it.
3887   if (New->hasAttr<GNUInlineAttr>() &&
3888       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3889     UndefinedButUsed.erase(Old->getCanonicalDecl());
3890   }
3891 
3892   // If pass_object_size params don't match up perfectly, this isn't a valid
3893   // redeclaration.
3894   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3895       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3896     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3897         << New->getDeclName();
3898     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3899     return true;
3900   }
3901 
3902   if (getLangOpts().CPlusPlus) {
3903     // C++1z [over.load]p2
3904     //   Certain function declarations cannot be overloaded:
3905     //     -- Function declarations that differ only in the return type,
3906     //        the exception specification, or both cannot be overloaded.
3907 
3908     // Check the exception specifications match. This may recompute the type of
3909     // both Old and New if it resolved exception specifications, so grab the
3910     // types again after this. Because this updates the type, we do this before
3911     // any of the other checks below, which may update the "de facto" NewQType
3912     // but do not necessarily update the type of New.
3913     if (CheckEquivalentExceptionSpec(Old, New))
3914       return true;
3915     OldQType = Context.getCanonicalType(Old->getType());
3916     NewQType = Context.getCanonicalType(New->getType());
3917 
3918     // Go back to the type source info to compare the declared return types,
3919     // per C++1y [dcl.type.auto]p13:
3920     //   Redeclarations or specializations of a function or function template
3921     //   with a declared return type that uses a placeholder type shall also
3922     //   use that placeholder, not a deduced type.
3923     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3924     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3925     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3926         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3927                                        OldDeclaredReturnType)) {
3928       QualType ResQT;
3929       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3930           OldDeclaredReturnType->isObjCObjectPointerType())
3931         // FIXME: This does the wrong thing for a deduced return type.
3932         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3933       if (ResQT.isNull()) {
3934         if (New->isCXXClassMember() && New->isOutOfLine())
3935           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3936               << New << New->getReturnTypeSourceRange();
3937         else
3938           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3939               << New->getReturnTypeSourceRange();
3940         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3941                                     << Old->getReturnTypeSourceRange();
3942         return true;
3943       }
3944       else
3945         NewQType = ResQT;
3946     }
3947 
3948     QualType OldReturnType = OldType->getReturnType();
3949     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3950     if (OldReturnType != NewReturnType) {
3951       // If this function has a deduced return type and has already been
3952       // defined, copy the deduced value from the old declaration.
3953       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3954       if (OldAT && OldAT->isDeduced()) {
3955         QualType DT = OldAT->getDeducedType();
3956         if (DT.isNull()) {
3957           New->setType(SubstAutoTypeDependent(New->getType()));
3958           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3959         } else {
3960           New->setType(SubstAutoType(New->getType(), DT));
3961           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3962         }
3963       }
3964     }
3965 
3966     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3967     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3968     if (OldMethod && NewMethod) {
3969       // Preserve triviality.
3970       NewMethod->setTrivial(OldMethod->isTrivial());
3971 
3972       // MSVC allows explicit template specialization at class scope:
3973       // 2 CXXMethodDecls referring to the same function will be injected.
3974       // We don't want a redeclaration error.
3975       bool IsClassScopeExplicitSpecialization =
3976                               OldMethod->isFunctionTemplateSpecialization() &&
3977                               NewMethod->isFunctionTemplateSpecialization();
3978       bool isFriend = NewMethod->getFriendObjectKind();
3979 
3980       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3981           !IsClassScopeExplicitSpecialization) {
3982         //    -- Member function declarations with the same name and the
3983         //       same parameter types cannot be overloaded if any of them
3984         //       is a static member function declaration.
3985         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3986           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3987           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3988           return true;
3989         }
3990 
3991         // C++ [class.mem]p1:
3992         //   [...] A member shall not be declared twice in the
3993         //   member-specification, except that a nested class or member
3994         //   class template can be declared and then later defined.
3995         if (!inTemplateInstantiation()) {
3996           unsigned NewDiag;
3997           if (isa<CXXConstructorDecl>(OldMethod))
3998             NewDiag = diag::err_constructor_redeclared;
3999           else if (isa<CXXDestructorDecl>(NewMethod))
4000             NewDiag = diag::err_destructor_redeclared;
4001           else if (isa<CXXConversionDecl>(NewMethod))
4002             NewDiag = diag::err_conv_function_redeclared;
4003           else
4004             NewDiag = diag::err_member_redeclared;
4005 
4006           Diag(New->getLocation(), NewDiag);
4007         } else {
4008           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4009             << New << New->getType();
4010         }
4011         Diag(OldLocation, PrevDiag) << Old << Old->getType();
4012         return true;
4013 
4014       // Complain if this is an explicit declaration of a special
4015       // member that was initially declared implicitly.
4016       //
4017       // As an exception, it's okay to befriend such methods in order
4018       // to permit the implicit constructor/destructor/operator calls.
4019       } else if (OldMethod->isImplicit()) {
4020         if (isFriend) {
4021           NewMethod->setImplicit();
4022         } else {
4023           Diag(NewMethod->getLocation(),
4024                diag::err_definition_of_implicitly_declared_member)
4025             << New << getSpecialMember(OldMethod);
4026           return true;
4027         }
4028       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4029         Diag(NewMethod->getLocation(),
4030              diag::err_definition_of_explicitly_defaulted_member)
4031           << getSpecialMember(OldMethod);
4032         return true;
4033       }
4034     }
4035 
4036     // C++11 [dcl.attr.noreturn]p1:
4037     //   The first declaration of a function shall specify the noreturn
4038     //   attribute if any declaration of that function specifies the noreturn
4039     //   attribute.
4040     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4041       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4042         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4043             << NRA;
4044         Diag(Old->getLocation(), diag::note_previous_declaration);
4045       }
4046 
4047     // C++11 [dcl.attr.depend]p2:
4048     //   The first declaration of a function shall specify the
4049     //   carries_dependency attribute for its declarator-id if any declaration
4050     //   of the function specifies the carries_dependency attribute.
4051     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4052     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4053       Diag(CDA->getLocation(),
4054            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4055       Diag(Old->getFirstDecl()->getLocation(),
4056            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4057     }
4058 
4059     // (C++98 8.3.5p3):
4060     //   All declarations for a function shall agree exactly in both the
4061     //   return type and the parameter-type-list.
4062     // We also want to respect all the extended bits except noreturn.
4063 
4064     // noreturn should now match unless the old type info didn't have it.
4065     QualType OldQTypeForComparison = OldQType;
4066     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4067       auto *OldType = OldQType->castAs<FunctionProtoType>();
4068       const FunctionType *OldTypeForComparison
4069         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4070       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4071       assert(OldQTypeForComparison.isCanonical());
4072     }
4073 
4074     if (haveIncompatibleLanguageLinkages(Old, New)) {
4075       // As a special case, retain the language linkage from previous
4076       // declarations of a friend function as an extension.
4077       //
4078       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4079       // and is useful because there's otherwise no way to specify language
4080       // linkage within class scope.
4081       //
4082       // Check cautiously as the friend object kind isn't yet complete.
4083       if (New->getFriendObjectKind() != Decl::FOK_None) {
4084         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4085         Diag(OldLocation, PrevDiag);
4086       } else {
4087         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4088         Diag(OldLocation, PrevDiag);
4089         return true;
4090       }
4091     }
4092 
4093     // If the function types are compatible, merge the declarations. Ignore the
4094     // exception specifier because it was already checked above in
4095     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4096     // about incompatible types under -fms-compatibility.
4097     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4098                                                          NewQType))
4099       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4100 
4101     // If the types are imprecise (due to dependent constructs in friends or
4102     // local extern declarations), it's OK if they differ. We'll check again
4103     // during instantiation.
4104     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4105       return false;
4106 
4107     // Fall through for conflicting redeclarations and redefinitions.
4108   }
4109 
4110   // C: Function types need to be compatible, not identical. This handles
4111   // duplicate function decls like "void f(int); void f(enum X);" properly.
4112   if (!getLangOpts().CPlusPlus) {
4113     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4114     // type is specified by a function definition that contains a (possibly
4115     // empty) identifier list, both shall agree in the number of parameters
4116     // and the type of each parameter shall be compatible with the type that
4117     // results from the application of default argument promotions to the
4118     // type of the corresponding identifier. ...
4119     // This cannot be handled by ASTContext::typesAreCompatible() because that
4120     // doesn't know whether the function type is for a definition or not when
4121     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4122     // we need to cover here is that the number of arguments agree as the
4123     // default argument promotion rules were already checked by
4124     // ASTContext::typesAreCompatible().
4125     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4126         Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4127       if (Old->hasInheritedPrototype())
4128         Old = Old->getCanonicalDecl();
4129       Diag(New->getLocation(), diag::err_conflicting_types) << New;
4130       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4131       return true;
4132     }
4133 
4134     // If we are merging two functions where only one of them has a prototype,
4135     // we may have enough information to decide to issue a diagnostic that the
4136     // function without a protoype will change behavior in C2x. This handles
4137     // cases like:
4138     //   void i(); void i(int j);
4139     //   void i(int j); void i();
4140     //   void i(); void i(int j) {}
4141     // See ActOnFinishFunctionBody() for other cases of the behavior change
4142     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4143     // type without a prototype.
4144     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4145         !New->isImplicit() && !Old->isImplicit()) {
4146       const FunctionDecl *WithProto, *WithoutProto;
4147       if (New->hasWrittenPrototype()) {
4148         WithProto = New;
4149         WithoutProto = Old;
4150       } else {
4151         WithProto = Old;
4152         WithoutProto = New;
4153       }
4154 
4155       if (WithProto->getNumParams() != 0) {
4156         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4157           // The one without the prototype will be changing behavior in C2x, so
4158           // warn about that one so long as it's a user-visible declaration.
4159           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4160           if (WithoutProto == New)
4161             IsWithoutProtoADef = NewDeclIsDefn;
4162           else
4163             IsWithProtoADef = NewDeclIsDefn;
4164           Diag(WithoutProto->getLocation(),
4165                diag::warn_non_prototype_changes_behavior)
4166               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4167               << (WithoutProto == Old) << IsWithProtoADef;
4168 
4169           // The reason the one without the prototype will be changing behavior
4170           // is because of the one with the prototype, so note that so long as
4171           // it's a user-visible declaration. There is one exception to this:
4172           // when the new declaration is a definition without a prototype, the
4173           // old declaration with a prototype is not the cause of the issue,
4174           // and that does not need to be noted because the one with a
4175           // prototype will not change behavior in C2x.
4176           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4177               !IsWithoutProtoADef)
4178             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4179         }
4180       }
4181     }
4182 
4183     if (Context.typesAreCompatible(OldQType, NewQType)) {
4184       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4185       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4186       const FunctionProtoType *OldProto = nullptr;
4187       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4188           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4189         // The old declaration provided a function prototype, but the
4190         // new declaration does not. Merge in the prototype.
4191         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4192         NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4193                                            OldProto->getParamTypes(),
4194                                            OldProto->getExtProtoInfo());
4195         New->setType(NewQType);
4196         New->setHasInheritedPrototype();
4197 
4198         // Synthesize parameters with the same types.
4199         SmallVector<ParmVarDecl *, 16> Params;
4200         for (const auto &ParamType : OldProto->param_types()) {
4201           ParmVarDecl *Param = ParmVarDecl::Create(
4202               Context, New, SourceLocation(), SourceLocation(), nullptr,
4203               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4204           Param->setScopeInfo(0, Params.size());
4205           Param->setImplicit();
4206           Params.push_back(Param);
4207         }
4208 
4209         New->setParams(Params);
4210       }
4211 
4212       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4213     }
4214   }
4215 
4216   // Check if the function types are compatible when pointer size address
4217   // spaces are ignored.
4218   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4219     return false;
4220 
4221   // GNU C permits a K&R definition to follow a prototype declaration
4222   // if the declared types of the parameters in the K&R definition
4223   // match the types in the prototype declaration, even when the
4224   // promoted types of the parameters from the K&R definition differ
4225   // from the types in the prototype. GCC then keeps the types from
4226   // the prototype.
4227   //
4228   // If a variadic prototype is followed by a non-variadic K&R definition,
4229   // the K&R definition becomes variadic.  This is sort of an edge case, but
4230   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4231   // C99 6.9.1p8.
4232   if (!getLangOpts().CPlusPlus &&
4233       Old->hasPrototype() && !New->hasPrototype() &&
4234       New->getType()->getAs<FunctionProtoType>() &&
4235       Old->getNumParams() == New->getNumParams()) {
4236     SmallVector<QualType, 16> ArgTypes;
4237     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4238     const FunctionProtoType *OldProto
4239       = Old->getType()->getAs<FunctionProtoType>();
4240     const FunctionProtoType *NewProto
4241       = New->getType()->getAs<FunctionProtoType>();
4242 
4243     // Determine whether this is the GNU C extension.
4244     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4245                                                NewProto->getReturnType());
4246     bool LooseCompatible = !MergedReturn.isNull();
4247     for (unsigned Idx = 0, End = Old->getNumParams();
4248          LooseCompatible && Idx != End; ++Idx) {
4249       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4250       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4251       if (Context.typesAreCompatible(OldParm->getType(),
4252                                      NewProto->getParamType(Idx))) {
4253         ArgTypes.push_back(NewParm->getType());
4254       } else if (Context.typesAreCompatible(OldParm->getType(),
4255                                             NewParm->getType(),
4256                                             /*CompareUnqualified=*/true)) {
4257         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4258                                            NewProto->getParamType(Idx) };
4259         Warnings.push_back(Warn);
4260         ArgTypes.push_back(NewParm->getType());
4261       } else
4262         LooseCompatible = false;
4263     }
4264 
4265     if (LooseCompatible) {
4266       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4267         Diag(Warnings[Warn].NewParm->getLocation(),
4268              diag::ext_param_promoted_not_compatible_with_prototype)
4269           << Warnings[Warn].PromotedType
4270           << Warnings[Warn].OldParm->getType();
4271         if (Warnings[Warn].OldParm->getLocation().isValid())
4272           Diag(Warnings[Warn].OldParm->getLocation(),
4273                diag::note_previous_declaration);
4274       }
4275 
4276       if (MergeTypeWithOld)
4277         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4278                                              OldProto->getExtProtoInfo()));
4279       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4280     }
4281 
4282     // Fall through to diagnose conflicting types.
4283   }
4284 
4285   // A function that has already been declared has been redeclared or
4286   // defined with a different type; show an appropriate diagnostic.
4287 
4288   // If the previous declaration was an implicitly-generated builtin
4289   // declaration, then at the very least we should use a specialized note.
4290   unsigned BuiltinID;
4291   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4292     // If it's actually a library-defined builtin function like 'malloc'
4293     // or 'printf', just warn about the incompatible redeclaration.
4294     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4295       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4296       Diag(OldLocation, diag::note_previous_builtin_declaration)
4297         << Old << Old->getType();
4298       return false;
4299     }
4300 
4301     PrevDiag = diag::note_previous_builtin_declaration;
4302   }
4303 
4304   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4305   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4306   return true;
4307 }
4308 
4309 /// Completes the merge of two function declarations that are
4310 /// known to be compatible.
4311 ///
4312 /// This routine handles the merging of attributes and other
4313 /// properties of function declarations from the old declaration to
4314 /// the new declaration, once we know that New is in fact a
4315 /// redeclaration of Old.
4316 ///
4317 /// \returns false
4318 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4319                                         Scope *S, bool MergeTypeWithOld) {
4320   // Merge the attributes
4321   mergeDeclAttributes(New, Old);
4322 
4323   // Merge "pure" flag.
4324   if (Old->isPure())
4325     New->setPure();
4326 
4327   // Merge "used" flag.
4328   if (Old->getMostRecentDecl()->isUsed(false))
4329     New->setIsUsed();
4330 
4331   // Merge attributes from the parameters.  These can mismatch with K&R
4332   // declarations.
4333   if (New->getNumParams() == Old->getNumParams())
4334       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4335         ParmVarDecl *NewParam = New->getParamDecl(i);
4336         ParmVarDecl *OldParam = Old->getParamDecl(i);
4337         mergeParamDeclAttributes(NewParam, OldParam, *this);
4338         mergeParamDeclTypes(NewParam, OldParam, *this);
4339       }
4340 
4341   if (getLangOpts().CPlusPlus)
4342     return MergeCXXFunctionDecl(New, Old, S);
4343 
4344   // Merge the function types so the we get the composite types for the return
4345   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4346   // was visible.
4347   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4348   if (!Merged.isNull() && MergeTypeWithOld)
4349     New->setType(Merged);
4350 
4351   return false;
4352 }
4353 
4354 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4355                                 ObjCMethodDecl *oldMethod) {
4356   // Merge the attributes, including deprecated/unavailable
4357   AvailabilityMergeKind MergeKind =
4358       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4359           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4360                                      : AMK_ProtocolImplementation)
4361           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4362                                                            : AMK_Override;
4363 
4364   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4365 
4366   // Merge attributes from the parameters.
4367   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4368                                        oe = oldMethod->param_end();
4369   for (ObjCMethodDecl::param_iterator
4370          ni = newMethod->param_begin(), ne = newMethod->param_end();
4371        ni != ne && oi != oe; ++ni, ++oi)
4372     mergeParamDeclAttributes(*ni, *oi, *this);
4373 
4374   CheckObjCMethodOverride(newMethod, oldMethod);
4375 }
4376 
4377 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4378   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4379 
4380   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4381          ? diag::err_redefinition_different_type
4382          : diag::err_redeclaration_different_type)
4383     << New->getDeclName() << New->getType() << Old->getType();
4384 
4385   diag::kind PrevDiag;
4386   SourceLocation OldLocation;
4387   std::tie(PrevDiag, OldLocation)
4388     = getNoteDiagForInvalidRedeclaration(Old, New);
4389   S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4390   New->setInvalidDecl();
4391 }
4392 
4393 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4394 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4395 /// emitting diagnostics as appropriate.
4396 ///
4397 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4398 /// to here in AddInitializerToDecl. We can't check them before the initializer
4399 /// is attached.
4400 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4401                              bool MergeTypeWithOld) {
4402   if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4403     return;
4404 
4405   QualType MergedT;
4406   if (getLangOpts().CPlusPlus) {
4407     if (New->getType()->isUndeducedType()) {
4408       // We don't know what the new type is until the initializer is attached.
4409       return;
4410     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4411       // These could still be something that needs exception specs checked.
4412       return MergeVarDeclExceptionSpecs(New, Old);
4413     }
4414     // C++ [basic.link]p10:
4415     //   [...] the types specified by all declarations referring to a given
4416     //   object or function shall be identical, except that declarations for an
4417     //   array object can specify array types that differ by the presence or
4418     //   absence of a major array bound (8.3.4).
4419     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4420       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4421       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4422 
4423       // We are merging a variable declaration New into Old. If it has an array
4424       // bound, and that bound differs from Old's bound, we should diagnose the
4425       // mismatch.
4426       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4427         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4428              PrevVD = PrevVD->getPreviousDecl()) {
4429           QualType PrevVDTy = PrevVD->getType();
4430           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4431             continue;
4432 
4433           if (!Context.hasSameType(New->getType(), PrevVDTy))
4434             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4435         }
4436       }
4437 
4438       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4439         if (Context.hasSameType(OldArray->getElementType(),
4440                                 NewArray->getElementType()))
4441           MergedT = New->getType();
4442       }
4443       // FIXME: Check visibility. New is hidden but has a complete type. If New
4444       // has no array bound, it should not inherit one from Old, if Old is not
4445       // visible.
4446       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4447         if (Context.hasSameType(OldArray->getElementType(),
4448                                 NewArray->getElementType()))
4449           MergedT = Old->getType();
4450       }
4451     }
4452     else if (New->getType()->isObjCObjectPointerType() &&
4453                Old->getType()->isObjCObjectPointerType()) {
4454       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4455                                               Old->getType());
4456     }
4457   } else {
4458     // C 6.2.7p2:
4459     //   All declarations that refer to the same object or function shall have
4460     //   compatible type.
4461     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4462   }
4463   if (MergedT.isNull()) {
4464     // It's OK if we couldn't merge types if either type is dependent, for a
4465     // block-scope variable. In other cases (static data members of class
4466     // templates, variable templates, ...), we require the types to be
4467     // equivalent.
4468     // FIXME: The C++ standard doesn't say anything about this.
4469     if ((New->getType()->isDependentType() ||
4470          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4471       // If the old type was dependent, we can't merge with it, so the new type
4472       // becomes dependent for now. We'll reproduce the original type when we
4473       // instantiate the TypeSourceInfo for the variable.
4474       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4475         New->setType(Context.DependentTy);
4476       return;
4477     }
4478     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4479   }
4480 
4481   // Don't actually update the type on the new declaration if the old
4482   // declaration was an extern declaration in a different scope.
4483   if (MergeTypeWithOld)
4484     New->setType(MergedT);
4485 }
4486 
4487 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4488                                   LookupResult &Previous) {
4489   // C11 6.2.7p4:
4490   //   For an identifier with internal or external linkage declared
4491   //   in a scope in which a prior declaration of that identifier is
4492   //   visible, if the prior declaration specifies internal or
4493   //   external linkage, the type of the identifier at the later
4494   //   declaration becomes the composite type.
4495   //
4496   // If the variable isn't visible, we do not merge with its type.
4497   if (Previous.isShadowed())
4498     return false;
4499 
4500   if (S.getLangOpts().CPlusPlus) {
4501     // C++11 [dcl.array]p3:
4502     //   If there is a preceding declaration of the entity in the same
4503     //   scope in which the bound was specified, an omitted array bound
4504     //   is taken to be the same as in that earlier declaration.
4505     return NewVD->isPreviousDeclInSameBlockScope() ||
4506            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4507             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4508   } else {
4509     // If the old declaration was function-local, don't merge with its
4510     // type unless we're in the same function.
4511     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4512            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4513   }
4514 }
4515 
4516 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4517 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4518 /// situation, merging decls or emitting diagnostics as appropriate.
4519 ///
4520 /// Tentative definition rules (C99 6.9.2p2) are checked by
4521 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4522 /// definitions here, since the initializer hasn't been attached.
4523 ///
4524 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4525   // If the new decl is already invalid, don't do any other checking.
4526   if (New->isInvalidDecl())
4527     return;
4528 
4529   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4530     return;
4531 
4532   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4533 
4534   // Verify the old decl was also a variable or variable template.
4535   VarDecl *Old = nullptr;
4536   VarTemplateDecl *OldTemplate = nullptr;
4537   if (Previous.isSingleResult()) {
4538     if (NewTemplate) {
4539       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4540       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4541 
4542       if (auto *Shadow =
4543               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4544         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4545           return New->setInvalidDecl();
4546     } else {
4547       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4548 
4549       if (auto *Shadow =
4550               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4551         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4552           return New->setInvalidDecl();
4553     }
4554   }
4555   if (!Old) {
4556     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4557         << New->getDeclName();
4558     notePreviousDefinition(Previous.getRepresentativeDecl(),
4559                            New->getLocation());
4560     return New->setInvalidDecl();
4561   }
4562 
4563   // If the old declaration was found in an inline namespace and the new
4564   // declaration was qualified, update the DeclContext to match.
4565   adjustDeclContextForDeclaratorDecl(New, Old);
4566 
4567   // Ensure the template parameters are compatible.
4568   if (NewTemplate &&
4569       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4570                                       OldTemplate->getTemplateParameters(),
4571                                       /*Complain=*/true, TPL_TemplateMatch))
4572     return New->setInvalidDecl();
4573 
4574   // C++ [class.mem]p1:
4575   //   A member shall not be declared twice in the member-specification [...]
4576   //
4577   // Here, we need only consider static data members.
4578   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4579     Diag(New->getLocation(), diag::err_duplicate_member)
4580       << New->getIdentifier();
4581     Diag(Old->getLocation(), diag::note_previous_declaration);
4582     New->setInvalidDecl();
4583   }
4584 
4585   mergeDeclAttributes(New, Old);
4586   // Warn if an already-declared variable is made a weak_import in a subsequent
4587   // declaration
4588   if (New->hasAttr<WeakImportAttr>() &&
4589       Old->getStorageClass() == SC_None &&
4590       !Old->hasAttr<WeakImportAttr>()) {
4591     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4592     Diag(Old->getLocation(), diag::note_previous_declaration);
4593     // Remove weak_import attribute on new declaration.
4594     New->dropAttr<WeakImportAttr>();
4595   }
4596 
4597   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4598     if (!Old->hasAttr<InternalLinkageAttr>()) {
4599       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4600           << ILA;
4601       Diag(Old->getLocation(), diag::note_previous_declaration);
4602       New->dropAttr<InternalLinkageAttr>();
4603     }
4604 
4605   // Merge the types.
4606   VarDecl *MostRecent = Old->getMostRecentDecl();
4607   if (MostRecent != Old) {
4608     MergeVarDeclTypes(New, MostRecent,
4609                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4610     if (New->isInvalidDecl())
4611       return;
4612   }
4613 
4614   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4615   if (New->isInvalidDecl())
4616     return;
4617 
4618   diag::kind PrevDiag;
4619   SourceLocation OldLocation;
4620   std::tie(PrevDiag, OldLocation) =
4621       getNoteDiagForInvalidRedeclaration(Old, New);
4622 
4623   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4624   if (New->getStorageClass() == SC_Static &&
4625       !New->isStaticDataMember() &&
4626       Old->hasExternalFormalLinkage()) {
4627     if (getLangOpts().MicrosoftExt) {
4628       Diag(New->getLocation(), diag::ext_static_non_static)
4629           << New->getDeclName();
4630       Diag(OldLocation, PrevDiag);
4631     } else {
4632       Diag(New->getLocation(), diag::err_static_non_static)
4633           << New->getDeclName();
4634       Diag(OldLocation, PrevDiag);
4635       return New->setInvalidDecl();
4636     }
4637   }
4638   // C99 6.2.2p4:
4639   //   For an identifier declared with the storage-class specifier
4640   //   extern in a scope in which a prior declaration of that
4641   //   identifier is visible,23) if the prior declaration specifies
4642   //   internal or external linkage, the linkage of the identifier at
4643   //   the later declaration is the same as the linkage specified at
4644   //   the prior declaration. If no prior declaration is visible, or
4645   //   if the prior declaration specifies no linkage, then the
4646   //   identifier has external linkage.
4647   if (New->hasExternalStorage() && Old->hasLinkage())
4648     /* Okay */;
4649   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4650            !New->isStaticDataMember() &&
4651            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4652     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4653     Diag(OldLocation, PrevDiag);
4654     return New->setInvalidDecl();
4655   }
4656 
4657   // Check if extern is followed by non-extern and vice-versa.
4658   if (New->hasExternalStorage() &&
4659       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4660     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4661     Diag(OldLocation, PrevDiag);
4662     return New->setInvalidDecl();
4663   }
4664   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4665       !New->hasExternalStorage()) {
4666     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4667     Diag(OldLocation, PrevDiag);
4668     return New->setInvalidDecl();
4669   }
4670 
4671   if (CheckRedeclarationInModule(New, Old))
4672     return;
4673 
4674   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4675 
4676   // FIXME: The test for external storage here seems wrong? We still
4677   // need to check for mismatches.
4678   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4679       // Don't complain about out-of-line definitions of static members.
4680       !(Old->getLexicalDeclContext()->isRecord() &&
4681         !New->getLexicalDeclContext()->isRecord())) {
4682     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4683     Diag(OldLocation, PrevDiag);
4684     return New->setInvalidDecl();
4685   }
4686 
4687   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4688     if (VarDecl *Def = Old->getDefinition()) {
4689       // C++1z [dcl.fcn.spec]p4:
4690       //   If the definition of a variable appears in a translation unit before
4691       //   its first declaration as inline, the program is ill-formed.
4692       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4693       Diag(Def->getLocation(), diag::note_previous_definition);
4694     }
4695   }
4696 
4697   // If this redeclaration makes the variable inline, we may need to add it to
4698   // UndefinedButUsed.
4699   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4700       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4701     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4702                                            SourceLocation()));
4703 
4704   if (New->getTLSKind() != Old->getTLSKind()) {
4705     if (!Old->getTLSKind()) {
4706       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4707       Diag(OldLocation, PrevDiag);
4708     } else if (!New->getTLSKind()) {
4709       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4710       Diag(OldLocation, PrevDiag);
4711     } else {
4712       // Do not allow redeclaration to change the variable between requiring
4713       // static and dynamic initialization.
4714       // FIXME: GCC allows this, but uses the TLS keyword on the first
4715       // declaration to determine the kind. Do we need to be compatible here?
4716       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4717         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4718       Diag(OldLocation, PrevDiag);
4719     }
4720   }
4721 
4722   // C++ doesn't have tentative definitions, so go right ahead and check here.
4723   if (getLangOpts().CPlusPlus) {
4724     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4725         Old->getCanonicalDecl()->isConstexpr()) {
4726       // This definition won't be a definition any more once it's been merged.
4727       Diag(New->getLocation(),
4728            diag::warn_deprecated_redundant_constexpr_static_def);
4729     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4730       VarDecl *Def = Old->getDefinition();
4731       if (Def && checkVarDeclRedefinition(Def, New))
4732         return;
4733     }
4734   }
4735 
4736   if (haveIncompatibleLanguageLinkages(Old, New)) {
4737     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4738     Diag(OldLocation, PrevDiag);
4739     New->setInvalidDecl();
4740     return;
4741   }
4742 
4743   // Merge "used" flag.
4744   if (Old->getMostRecentDecl()->isUsed(false))
4745     New->setIsUsed();
4746 
4747   // Keep a chain of previous declarations.
4748   New->setPreviousDecl(Old);
4749   if (NewTemplate)
4750     NewTemplate->setPreviousDecl(OldTemplate);
4751 
4752   // Inherit access appropriately.
4753   New->setAccess(Old->getAccess());
4754   if (NewTemplate)
4755     NewTemplate->setAccess(New->getAccess());
4756 
4757   if (Old->isInline())
4758     New->setImplicitlyInline();
4759 }
4760 
4761 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4762   SourceManager &SrcMgr = getSourceManager();
4763   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4764   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4765   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4766   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4767   auto &HSI = PP.getHeaderSearchInfo();
4768   StringRef HdrFilename =
4769       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4770 
4771   auto noteFromModuleOrInclude = [&](Module *Mod,
4772                                      SourceLocation IncLoc) -> bool {
4773     // Redefinition errors with modules are common with non modular mapped
4774     // headers, example: a non-modular header H in module A that also gets
4775     // included directly in a TU. Pointing twice to the same header/definition
4776     // is confusing, try to get better diagnostics when modules is on.
4777     if (IncLoc.isValid()) {
4778       if (Mod) {
4779         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4780             << HdrFilename.str() << Mod->getFullModuleName();
4781         if (!Mod->DefinitionLoc.isInvalid())
4782           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4783               << Mod->getFullModuleName();
4784       } else {
4785         Diag(IncLoc, diag::note_redefinition_include_same_file)
4786             << HdrFilename.str();
4787       }
4788       return true;
4789     }
4790 
4791     return false;
4792   };
4793 
4794   // Is it the same file and same offset? Provide more information on why
4795   // this leads to a redefinition error.
4796   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4797     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4798     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4799     bool EmittedDiag =
4800         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4801     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4802 
4803     // If the header has no guards, emit a note suggesting one.
4804     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4805       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4806 
4807     if (EmittedDiag)
4808       return;
4809   }
4810 
4811   // Redefinition coming from different files or couldn't do better above.
4812   if (Old->getLocation().isValid())
4813     Diag(Old->getLocation(), diag::note_previous_definition);
4814 }
4815 
4816 /// We've just determined that \p Old and \p New both appear to be definitions
4817 /// of the same variable. Either diagnose or fix the problem.
4818 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4819   if (!hasVisibleDefinition(Old) &&
4820       (New->getFormalLinkage() == InternalLinkage ||
4821        New->isInline() ||
4822        isa<VarTemplateSpecializationDecl>(New) ||
4823        New->getDescribedVarTemplate() ||
4824        New->getNumTemplateParameterLists() ||
4825        New->getDeclContext()->isDependentContext())) {
4826     // The previous definition is hidden, and multiple definitions are
4827     // permitted (in separate TUs). Demote this to a declaration.
4828     New->demoteThisDefinitionToDeclaration();
4829 
4830     // Make the canonical definition visible.
4831     if (auto *OldTD = Old->getDescribedVarTemplate())
4832       makeMergedDefinitionVisible(OldTD);
4833     makeMergedDefinitionVisible(Old);
4834     return false;
4835   } else {
4836     Diag(New->getLocation(), diag::err_redefinition) << New;
4837     notePreviousDefinition(Old, New->getLocation());
4838     New->setInvalidDecl();
4839     return true;
4840   }
4841 }
4842 
4843 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4844 /// no declarator (e.g. "struct foo;") is parsed.
4845 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4846                                        DeclSpec &DS,
4847                                        const ParsedAttributesView &DeclAttrs,
4848                                        RecordDecl *&AnonRecord) {
4849   return ParsedFreeStandingDeclSpec(
4850       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4851 }
4852 
4853 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4854 // disambiguate entities defined in different scopes.
4855 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4856 // compatibility.
4857 // We will pick our mangling number depending on which version of MSVC is being
4858 // targeted.
4859 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4860   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4861              ? S->getMSCurManglingNumber()
4862              : S->getMSLastManglingNumber();
4863 }
4864 
4865 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4866   if (!Context.getLangOpts().CPlusPlus)
4867     return;
4868 
4869   if (isa<CXXRecordDecl>(Tag->getParent())) {
4870     // If this tag is the direct child of a class, number it if
4871     // it is anonymous.
4872     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4873       return;
4874     MangleNumberingContext &MCtx =
4875         Context.getManglingNumberContext(Tag->getParent());
4876     Context.setManglingNumber(
4877         Tag, MCtx.getManglingNumber(
4878                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4879     return;
4880   }
4881 
4882   // If this tag isn't a direct child of a class, number it if it is local.
4883   MangleNumberingContext *MCtx;
4884   Decl *ManglingContextDecl;
4885   std::tie(MCtx, ManglingContextDecl) =
4886       getCurrentMangleNumberContext(Tag->getDeclContext());
4887   if (MCtx) {
4888     Context.setManglingNumber(
4889         Tag, MCtx->getManglingNumber(
4890                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4891   }
4892 }
4893 
4894 namespace {
4895 struct NonCLikeKind {
4896   enum {
4897     None,
4898     BaseClass,
4899     DefaultMemberInit,
4900     Lambda,
4901     Friend,
4902     OtherMember,
4903     Invalid,
4904   } Kind = None;
4905   SourceRange Range;
4906 
4907   explicit operator bool() { return Kind != None; }
4908 };
4909 }
4910 
4911 /// Determine whether a class is C-like, according to the rules of C++
4912 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4913 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4914   if (RD->isInvalidDecl())
4915     return {NonCLikeKind::Invalid, {}};
4916 
4917   // C++ [dcl.typedef]p9: [P1766R1]
4918   //   An unnamed class with a typedef name for linkage purposes shall not
4919   //
4920   //    -- have any base classes
4921   if (RD->getNumBases())
4922     return {NonCLikeKind::BaseClass,
4923             SourceRange(RD->bases_begin()->getBeginLoc(),
4924                         RD->bases_end()[-1].getEndLoc())};
4925   bool Invalid = false;
4926   for (Decl *D : RD->decls()) {
4927     // Don't complain about things we already diagnosed.
4928     if (D->isInvalidDecl()) {
4929       Invalid = true;
4930       continue;
4931     }
4932 
4933     //  -- have any [...] default member initializers
4934     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4935       if (FD->hasInClassInitializer()) {
4936         auto *Init = FD->getInClassInitializer();
4937         return {NonCLikeKind::DefaultMemberInit,
4938                 Init ? Init->getSourceRange() : D->getSourceRange()};
4939       }
4940       continue;
4941     }
4942 
4943     // FIXME: We don't allow friend declarations. This violates the wording of
4944     // P1766, but not the intent.
4945     if (isa<FriendDecl>(D))
4946       return {NonCLikeKind::Friend, D->getSourceRange()};
4947 
4948     //  -- declare any members other than non-static data members, member
4949     //     enumerations, or member classes,
4950     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4951         isa<EnumDecl>(D))
4952       continue;
4953     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4954     if (!MemberRD) {
4955       if (D->isImplicit())
4956         continue;
4957       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4958     }
4959 
4960     //  -- contain a lambda-expression,
4961     if (MemberRD->isLambda())
4962       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4963 
4964     //  and all member classes shall also satisfy these requirements
4965     //  (recursively).
4966     if (MemberRD->isThisDeclarationADefinition()) {
4967       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4968         return Kind;
4969     }
4970   }
4971 
4972   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4973 }
4974 
4975 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4976                                         TypedefNameDecl *NewTD) {
4977   if (TagFromDeclSpec->isInvalidDecl())
4978     return;
4979 
4980   // Do nothing if the tag already has a name for linkage purposes.
4981   if (TagFromDeclSpec->hasNameForLinkage())
4982     return;
4983 
4984   // A well-formed anonymous tag must always be a TUK_Definition.
4985   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4986 
4987   // The type must match the tag exactly;  no qualifiers allowed.
4988   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4989                            Context.getTagDeclType(TagFromDeclSpec))) {
4990     if (getLangOpts().CPlusPlus)
4991       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4992     return;
4993   }
4994 
4995   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4996   //   An unnamed class with a typedef name for linkage purposes shall [be
4997   //   C-like].
4998   //
4999   // FIXME: Also diagnose if we've already computed the linkage. That ideally
5000   // shouldn't happen, but there are constructs that the language rule doesn't
5001   // disallow for which we can't reasonably avoid computing linkage early.
5002   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5003   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5004                              : NonCLikeKind();
5005   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5006   if (NonCLike || ChangesLinkage) {
5007     if (NonCLike.Kind == NonCLikeKind::Invalid)
5008       return;
5009 
5010     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5011     if (ChangesLinkage) {
5012       // If the linkage changes, we can't accept this as an extension.
5013       if (NonCLike.Kind == NonCLikeKind::None)
5014         DiagID = diag::err_typedef_changes_linkage;
5015       else
5016         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5017     }
5018 
5019     SourceLocation FixitLoc =
5020         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5021     llvm::SmallString<40> TextToInsert;
5022     TextToInsert += ' ';
5023     TextToInsert += NewTD->getIdentifier()->getName();
5024 
5025     Diag(FixitLoc, DiagID)
5026       << isa<TypeAliasDecl>(NewTD)
5027       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5028     if (NonCLike.Kind != NonCLikeKind::None) {
5029       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5030         << NonCLike.Kind - 1 << NonCLike.Range;
5031     }
5032     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5033       << NewTD << isa<TypeAliasDecl>(NewTD);
5034 
5035     if (ChangesLinkage)
5036       return;
5037   }
5038 
5039   // Otherwise, set this as the anon-decl typedef for the tag.
5040   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5041 }
5042 
5043 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5044   DeclSpec::TST T = DS.getTypeSpecType();
5045   switch (T) {
5046   case DeclSpec::TST_class:
5047     return 0;
5048   case DeclSpec::TST_struct:
5049     return 1;
5050   case DeclSpec::TST_interface:
5051     return 2;
5052   case DeclSpec::TST_union:
5053     return 3;
5054   case DeclSpec::TST_enum:
5055     if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5056       if (ED->isScopedUsingClassTag())
5057         return 5;
5058       if (ED->isScoped())
5059         return 6;
5060     }
5061     return 4;
5062   default:
5063     llvm_unreachable("unexpected type specifier");
5064   }
5065 }
5066 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5067 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5068 /// parameters to cope with template friend declarations.
5069 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5070                                        DeclSpec &DS,
5071                                        const ParsedAttributesView &DeclAttrs,
5072                                        MultiTemplateParamsArg TemplateParams,
5073                                        bool IsExplicitInstantiation,
5074                                        RecordDecl *&AnonRecord) {
5075   Decl *TagD = nullptr;
5076   TagDecl *Tag = nullptr;
5077   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5078       DS.getTypeSpecType() == DeclSpec::TST_struct ||
5079       DS.getTypeSpecType() == DeclSpec::TST_interface ||
5080       DS.getTypeSpecType() == DeclSpec::TST_union ||
5081       DS.getTypeSpecType() == DeclSpec::TST_enum) {
5082     TagD = DS.getRepAsDecl();
5083 
5084     if (!TagD) // We probably had an error
5085       return nullptr;
5086 
5087     // Note that the above type specs guarantee that the
5088     // type rep is a Decl, whereas in many of the others
5089     // it's a Type.
5090     if (isa<TagDecl>(TagD))
5091       Tag = cast<TagDecl>(TagD);
5092     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5093       Tag = CTD->getTemplatedDecl();
5094   }
5095 
5096   if (Tag) {
5097     handleTagNumbering(Tag, S);
5098     Tag->setFreeStanding();
5099     if (Tag->isInvalidDecl())
5100       return Tag;
5101   }
5102 
5103   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5104     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5105     // or incomplete types shall not be restrict-qualified."
5106     if (TypeQuals & DeclSpec::TQ_restrict)
5107       Diag(DS.getRestrictSpecLoc(),
5108            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5109            << DS.getSourceRange();
5110   }
5111 
5112   if (DS.isInlineSpecified())
5113     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5114         << getLangOpts().CPlusPlus17;
5115 
5116   if (DS.hasConstexprSpecifier()) {
5117     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5118     // and definitions of functions and variables.
5119     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5120     // the declaration of a function or function template
5121     if (Tag)
5122       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5123           << GetDiagnosticTypeSpecifierID(DS)
5124           << static_cast<int>(DS.getConstexprSpecifier());
5125     else
5126       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5127           << static_cast<int>(DS.getConstexprSpecifier());
5128     // Don't emit warnings after this error.
5129     return TagD;
5130   }
5131 
5132   DiagnoseFunctionSpecifiers(DS);
5133 
5134   if (DS.isFriendSpecified()) {
5135     // If we're dealing with a decl but not a TagDecl, assume that
5136     // whatever routines created it handled the friendship aspect.
5137     if (TagD && !Tag)
5138       return nullptr;
5139     return ActOnFriendTypeDecl(S, DS, TemplateParams);
5140   }
5141 
5142   const CXXScopeSpec &SS = DS.getTypeSpecScope();
5143   bool IsExplicitSpecialization =
5144     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5145   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5146       !IsExplicitInstantiation && !IsExplicitSpecialization &&
5147       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5148     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5149     // nested-name-specifier unless it is an explicit instantiation
5150     // or an explicit specialization.
5151     //
5152     // FIXME: We allow class template partial specializations here too, per the
5153     // obvious intent of DR1819.
5154     //
5155     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5156     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5157         << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5158     return nullptr;
5159   }
5160 
5161   // Track whether this decl-specifier declares anything.
5162   bool DeclaresAnything = true;
5163 
5164   // Handle anonymous struct definitions.
5165   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5166     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5167         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5168       if (getLangOpts().CPlusPlus ||
5169           Record->getDeclContext()->isRecord()) {
5170         // If CurContext is a DeclContext that can contain statements,
5171         // RecursiveASTVisitor won't visit the decls that
5172         // BuildAnonymousStructOrUnion() will put into CurContext.
5173         // Also store them here so that they can be part of the
5174         // DeclStmt that gets created in this case.
5175         // FIXME: Also return the IndirectFieldDecls created by
5176         // BuildAnonymousStructOr union, for the same reason?
5177         if (CurContext->isFunctionOrMethod())
5178           AnonRecord = Record;
5179         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5180                                            Context.getPrintingPolicy());
5181       }
5182 
5183       DeclaresAnything = false;
5184     }
5185   }
5186 
5187   // C11 6.7.2.1p2:
5188   //   A struct-declaration that does not declare an anonymous structure or
5189   //   anonymous union shall contain a struct-declarator-list.
5190   //
5191   // This rule also existed in C89 and C99; the grammar for struct-declaration
5192   // did not permit a struct-declaration without a struct-declarator-list.
5193   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5194       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5195     // Check for Microsoft C extension: anonymous struct/union member.
5196     // Handle 2 kinds of anonymous struct/union:
5197     //   struct STRUCT;
5198     //   union UNION;
5199     // and
5200     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5201     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5202     if ((Tag && Tag->getDeclName()) ||
5203         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5204       RecordDecl *Record = nullptr;
5205       if (Tag)
5206         Record = dyn_cast<RecordDecl>(Tag);
5207       else if (const RecordType *RT =
5208                    DS.getRepAsType().get()->getAsStructureType())
5209         Record = RT->getDecl();
5210       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5211         Record = UT->getDecl();
5212 
5213       if (Record && getLangOpts().MicrosoftExt) {
5214         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5215             << Record->isUnion() << DS.getSourceRange();
5216         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5217       }
5218 
5219       DeclaresAnything = false;
5220     }
5221   }
5222 
5223   // Skip all the checks below if we have a type error.
5224   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5225       (TagD && TagD->isInvalidDecl()))
5226     return TagD;
5227 
5228   if (getLangOpts().CPlusPlus &&
5229       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5230     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5231       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5232           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5233         DeclaresAnything = false;
5234 
5235   if (!DS.isMissingDeclaratorOk()) {
5236     // Customize diagnostic for a typedef missing a name.
5237     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5238       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5239           << DS.getSourceRange();
5240     else
5241       DeclaresAnything = false;
5242   }
5243 
5244   if (DS.isModulePrivateSpecified() &&
5245       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5246     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5247       << Tag->getTagKind()
5248       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5249 
5250   ActOnDocumentableDecl(TagD);
5251 
5252   // C 6.7/2:
5253   //   A declaration [...] shall declare at least a declarator [...], a tag,
5254   //   or the members of an enumeration.
5255   // C++ [dcl.dcl]p3:
5256   //   [If there are no declarators], and except for the declaration of an
5257   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5258   //   names into the program, or shall redeclare a name introduced by a
5259   //   previous declaration.
5260   if (!DeclaresAnything) {
5261     // In C, we allow this as a (popular) extension / bug. Don't bother
5262     // producing further diagnostics for redundant qualifiers after this.
5263     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5264                                ? diag::err_no_declarators
5265                                : diag::ext_no_declarators)
5266         << DS.getSourceRange();
5267     return TagD;
5268   }
5269 
5270   // C++ [dcl.stc]p1:
5271   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5272   //   init-declarator-list of the declaration shall not be empty.
5273   // C++ [dcl.fct.spec]p1:
5274   //   If a cv-qualifier appears in a decl-specifier-seq, the
5275   //   init-declarator-list of the declaration shall not be empty.
5276   //
5277   // Spurious qualifiers here appear to be valid in C.
5278   unsigned DiagID = diag::warn_standalone_specifier;
5279   if (getLangOpts().CPlusPlus)
5280     DiagID = diag::ext_standalone_specifier;
5281 
5282   // Note that a linkage-specification sets a storage class, but
5283   // 'extern "C" struct foo;' is actually valid and not theoretically
5284   // useless.
5285   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5286     if (SCS == DeclSpec::SCS_mutable)
5287       // Since mutable is not a viable storage class specifier in C, there is
5288       // no reason to treat it as an extension. Instead, diagnose as an error.
5289       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5290     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5291       Diag(DS.getStorageClassSpecLoc(), DiagID)
5292         << DeclSpec::getSpecifierName(SCS);
5293   }
5294 
5295   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5296     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5297       << DeclSpec::getSpecifierName(TSCS);
5298   if (DS.getTypeQualifiers()) {
5299     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5300       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5301     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5302       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5303     // Restrict is covered above.
5304     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5305       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5306     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5307       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5308   }
5309 
5310   // Warn about ignored type attributes, for example:
5311   // __attribute__((aligned)) struct A;
5312   // Attributes should be placed after tag to apply to type declaration.
5313   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5314     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5315     if (TypeSpecType == DeclSpec::TST_class ||
5316         TypeSpecType == DeclSpec::TST_struct ||
5317         TypeSpecType == DeclSpec::TST_interface ||
5318         TypeSpecType == DeclSpec::TST_union ||
5319         TypeSpecType == DeclSpec::TST_enum) {
5320       for (const ParsedAttr &AL : DS.getAttributes())
5321         Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5322                               ? diag::err_declspec_keyword_has_no_effect
5323                               : diag::warn_declspec_attribute_ignored)
5324             << AL << GetDiagnosticTypeSpecifierID(DS);
5325       for (const ParsedAttr &AL : DeclAttrs)
5326         Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5327                               ? diag::err_declspec_keyword_has_no_effect
5328                               : diag::warn_declspec_attribute_ignored)
5329             << AL << GetDiagnosticTypeSpecifierID(DS);
5330     }
5331   }
5332 
5333   return TagD;
5334 }
5335 
5336 /// We are trying to inject an anonymous member into the given scope;
5337 /// check if there's an existing declaration that can't be overloaded.
5338 ///
5339 /// \return true if this is a forbidden redeclaration
5340 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5341                                          Scope *S,
5342                                          DeclContext *Owner,
5343                                          DeclarationName Name,
5344                                          SourceLocation NameLoc,
5345                                          bool IsUnion) {
5346   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5347                  Sema::ForVisibleRedeclaration);
5348   if (!SemaRef.LookupName(R, S)) return false;
5349 
5350   // Pick a representative declaration.
5351   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5352   assert(PrevDecl && "Expected a non-null Decl");
5353 
5354   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5355     return false;
5356 
5357   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5358     << IsUnion << Name;
5359   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5360 
5361   return true;
5362 }
5363 
5364 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5365 /// anonymous struct or union AnonRecord into the owning context Owner
5366 /// and scope S. This routine will be invoked just after we realize
5367 /// that an unnamed union or struct is actually an anonymous union or
5368 /// struct, e.g.,
5369 ///
5370 /// @code
5371 /// union {
5372 ///   int i;
5373 ///   float f;
5374 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5375 ///    // f into the surrounding scope.x
5376 /// @endcode
5377 ///
5378 /// This routine is recursive, injecting the names of nested anonymous
5379 /// structs/unions into the owning context and scope as well.
5380 static bool
5381 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5382                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5383                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5384   bool Invalid = false;
5385 
5386   // Look every FieldDecl and IndirectFieldDecl with a name.
5387   for (auto *D : AnonRecord->decls()) {
5388     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5389         cast<NamedDecl>(D)->getDeclName()) {
5390       ValueDecl *VD = cast<ValueDecl>(D);
5391       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5392                                        VD->getLocation(),
5393                                        AnonRecord->isUnion())) {
5394         // C++ [class.union]p2:
5395         //   The names of the members of an anonymous union shall be
5396         //   distinct from the names of any other entity in the
5397         //   scope in which the anonymous union is declared.
5398         Invalid = true;
5399       } else {
5400         // C++ [class.union]p2:
5401         //   For the purpose of name lookup, after the anonymous union
5402         //   definition, the members of the anonymous union are
5403         //   considered to have been defined in the scope in which the
5404         //   anonymous union is declared.
5405         unsigned OldChainingSize = Chaining.size();
5406         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5407           Chaining.append(IF->chain_begin(), IF->chain_end());
5408         else
5409           Chaining.push_back(VD);
5410 
5411         assert(Chaining.size() >= 2);
5412         NamedDecl **NamedChain =
5413           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5414         for (unsigned i = 0; i < Chaining.size(); i++)
5415           NamedChain[i] = Chaining[i];
5416 
5417         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5418             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5419             VD->getType(), {NamedChain, Chaining.size()});
5420 
5421         for (const auto *Attr : VD->attrs())
5422           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5423 
5424         IndirectField->setAccess(AS);
5425         IndirectField->setImplicit();
5426         SemaRef.PushOnScopeChains(IndirectField, S);
5427 
5428         // That includes picking up the appropriate access specifier.
5429         if (AS != AS_none) IndirectField->setAccess(AS);
5430 
5431         Chaining.resize(OldChainingSize);
5432       }
5433     }
5434   }
5435 
5436   return Invalid;
5437 }
5438 
5439 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5440 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5441 /// illegal input values are mapped to SC_None.
5442 static StorageClass
5443 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5444   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5445   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5446          "Parser allowed 'typedef' as storage class VarDecl.");
5447   switch (StorageClassSpec) {
5448   case DeclSpec::SCS_unspecified:    return SC_None;
5449   case DeclSpec::SCS_extern:
5450     if (DS.isExternInLinkageSpec())
5451       return SC_None;
5452     return SC_Extern;
5453   case DeclSpec::SCS_static:         return SC_Static;
5454   case DeclSpec::SCS_auto:           return SC_Auto;
5455   case DeclSpec::SCS_register:       return SC_Register;
5456   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5457     // Illegal SCSs map to None: error reporting is up to the caller.
5458   case DeclSpec::SCS_mutable:        // Fall through.
5459   case DeclSpec::SCS_typedef:        return SC_None;
5460   }
5461   llvm_unreachable("unknown storage class specifier");
5462 }
5463 
5464 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5465   assert(Record->hasInClassInitializer());
5466 
5467   for (const auto *I : Record->decls()) {
5468     const auto *FD = dyn_cast<FieldDecl>(I);
5469     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5470       FD = IFD->getAnonField();
5471     if (FD && FD->hasInClassInitializer())
5472       return FD->getLocation();
5473   }
5474 
5475   llvm_unreachable("couldn't find in-class initializer");
5476 }
5477 
5478 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5479                                       SourceLocation DefaultInitLoc) {
5480   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5481     return;
5482 
5483   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5484   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5485 }
5486 
5487 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5488                                       CXXRecordDecl *AnonUnion) {
5489   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5490     return;
5491 
5492   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5493 }
5494 
5495 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5496 /// anonymous structure or union. Anonymous unions are a C++ feature
5497 /// (C++ [class.union]) and a C11 feature; anonymous structures
5498 /// are a C11 feature and GNU C++ extension.
5499 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5500                                         AccessSpecifier AS,
5501                                         RecordDecl *Record,
5502                                         const PrintingPolicy &Policy) {
5503   DeclContext *Owner = Record->getDeclContext();
5504 
5505   // Diagnose whether this anonymous struct/union is an extension.
5506   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5507     Diag(Record->getLocation(), diag::ext_anonymous_union);
5508   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5509     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5510   else if (!Record->isUnion() && !getLangOpts().C11)
5511     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5512 
5513   // C and C++ require different kinds of checks for anonymous
5514   // structs/unions.
5515   bool Invalid = false;
5516   if (getLangOpts().CPlusPlus) {
5517     const char *PrevSpec = nullptr;
5518     if (Record->isUnion()) {
5519       // C++ [class.union]p6:
5520       // C++17 [class.union.anon]p2:
5521       //   Anonymous unions declared in a named namespace or in the
5522       //   global namespace shall be declared static.
5523       unsigned DiagID;
5524       DeclContext *OwnerScope = Owner->getRedeclContext();
5525       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5526           (OwnerScope->isTranslationUnit() ||
5527            (OwnerScope->isNamespace() &&
5528             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5529         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5530           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5531 
5532         // Recover by adding 'static'.
5533         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5534                                PrevSpec, DiagID, Policy);
5535       }
5536       // C++ [class.union]p6:
5537       //   A storage class is not allowed in a declaration of an
5538       //   anonymous union in a class scope.
5539       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5540                isa<RecordDecl>(Owner)) {
5541         Diag(DS.getStorageClassSpecLoc(),
5542              diag::err_anonymous_union_with_storage_spec)
5543           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5544 
5545         // Recover by removing the storage specifier.
5546         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5547                                SourceLocation(),
5548                                PrevSpec, DiagID, Context.getPrintingPolicy());
5549       }
5550     }
5551 
5552     // Ignore const/volatile/restrict qualifiers.
5553     if (DS.getTypeQualifiers()) {
5554       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5555         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5556           << Record->isUnion() << "const"
5557           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5558       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5559         Diag(DS.getVolatileSpecLoc(),
5560              diag::ext_anonymous_struct_union_qualified)
5561           << Record->isUnion() << "volatile"
5562           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5563       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5564         Diag(DS.getRestrictSpecLoc(),
5565              diag::ext_anonymous_struct_union_qualified)
5566           << Record->isUnion() << "restrict"
5567           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5568       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5569         Diag(DS.getAtomicSpecLoc(),
5570              diag::ext_anonymous_struct_union_qualified)
5571           << Record->isUnion() << "_Atomic"
5572           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5573       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5574         Diag(DS.getUnalignedSpecLoc(),
5575              diag::ext_anonymous_struct_union_qualified)
5576           << Record->isUnion() << "__unaligned"
5577           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5578 
5579       DS.ClearTypeQualifiers();
5580     }
5581 
5582     // C++ [class.union]p2:
5583     //   The member-specification of an anonymous union shall only
5584     //   define non-static data members. [Note: nested types and
5585     //   functions cannot be declared within an anonymous union. ]
5586     for (auto *Mem : Record->decls()) {
5587       // Ignore invalid declarations; we already diagnosed them.
5588       if (Mem->isInvalidDecl())
5589         continue;
5590 
5591       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5592         // C++ [class.union]p3:
5593         //   An anonymous union shall not have private or protected
5594         //   members (clause 11).
5595         assert(FD->getAccess() != AS_none);
5596         if (FD->getAccess() != AS_public) {
5597           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5598             << Record->isUnion() << (FD->getAccess() == AS_protected);
5599           Invalid = true;
5600         }
5601 
5602         // C++ [class.union]p1
5603         //   An object of a class with a non-trivial constructor, a non-trivial
5604         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5605         //   assignment operator cannot be a member of a union, nor can an
5606         //   array of such objects.
5607         if (CheckNontrivialField(FD))
5608           Invalid = true;
5609       } else if (Mem->isImplicit()) {
5610         // Any implicit members are fine.
5611       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5612         // This is a type that showed up in an
5613         // elaborated-type-specifier inside the anonymous struct or
5614         // union, but which actually declares a type outside of the
5615         // anonymous struct or union. It's okay.
5616       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5617         if (!MemRecord->isAnonymousStructOrUnion() &&
5618             MemRecord->getDeclName()) {
5619           // Visual C++ allows type definition in anonymous struct or union.
5620           if (getLangOpts().MicrosoftExt)
5621             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5622               << Record->isUnion();
5623           else {
5624             // This is a nested type declaration.
5625             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5626               << Record->isUnion();
5627             Invalid = true;
5628           }
5629         } else {
5630           // This is an anonymous type definition within another anonymous type.
5631           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5632           // not part of standard C++.
5633           Diag(MemRecord->getLocation(),
5634                diag::ext_anonymous_record_with_anonymous_type)
5635             << Record->isUnion();
5636         }
5637       } else if (isa<AccessSpecDecl>(Mem)) {
5638         // Any access specifier is fine.
5639       } else if (isa<StaticAssertDecl>(Mem)) {
5640         // In C++1z, static_assert declarations are also fine.
5641       } else {
5642         // We have something that isn't a non-static data
5643         // member. Complain about it.
5644         unsigned DK = diag::err_anonymous_record_bad_member;
5645         if (isa<TypeDecl>(Mem))
5646           DK = diag::err_anonymous_record_with_type;
5647         else if (isa<FunctionDecl>(Mem))
5648           DK = diag::err_anonymous_record_with_function;
5649         else if (isa<VarDecl>(Mem))
5650           DK = diag::err_anonymous_record_with_static;
5651 
5652         // Visual C++ allows type definition in anonymous struct or union.
5653         if (getLangOpts().MicrosoftExt &&
5654             DK == diag::err_anonymous_record_with_type)
5655           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5656             << Record->isUnion();
5657         else {
5658           Diag(Mem->getLocation(), DK) << Record->isUnion();
5659           Invalid = true;
5660         }
5661       }
5662     }
5663 
5664     // C++11 [class.union]p8 (DR1460):
5665     //   At most one variant member of a union may have a
5666     //   brace-or-equal-initializer.
5667     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5668         Owner->isRecord())
5669       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5670                                 cast<CXXRecordDecl>(Record));
5671   }
5672 
5673   if (!Record->isUnion() && !Owner->isRecord()) {
5674     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5675       << getLangOpts().CPlusPlus;
5676     Invalid = true;
5677   }
5678 
5679   // C++ [dcl.dcl]p3:
5680   //   [If there are no declarators], and except for the declaration of an
5681   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5682   //   names into the program
5683   // C++ [class.mem]p2:
5684   //   each such member-declaration shall either declare at least one member
5685   //   name of the class or declare at least one unnamed bit-field
5686   //
5687   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5688   if (getLangOpts().CPlusPlus && Record->field_empty())
5689     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5690 
5691   // Mock up a declarator.
5692   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5693   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5694   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5695 
5696   // Create a declaration for this anonymous struct/union.
5697   NamedDecl *Anon = nullptr;
5698   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5699     Anon = FieldDecl::Create(
5700         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5701         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5702         /*BitWidth=*/nullptr, /*Mutable=*/false,
5703         /*InitStyle=*/ICIS_NoInit);
5704     Anon->setAccess(AS);
5705     ProcessDeclAttributes(S, Anon, Dc);
5706 
5707     if (getLangOpts().CPlusPlus)
5708       FieldCollector->Add(cast<FieldDecl>(Anon));
5709   } else {
5710     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5711     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5712     if (SCSpec == DeclSpec::SCS_mutable) {
5713       // mutable can only appear on non-static class members, so it's always
5714       // an error here
5715       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5716       Invalid = true;
5717       SC = SC_None;
5718     }
5719 
5720     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5721                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5722                            Context.getTypeDeclType(Record), TInfo, SC);
5723     ProcessDeclAttributes(S, Anon, Dc);
5724 
5725     // Default-initialize the implicit variable. This initialization will be
5726     // trivial in almost all cases, except if a union member has an in-class
5727     // initializer:
5728     //   union { int n = 0; };
5729     ActOnUninitializedDecl(Anon);
5730   }
5731   Anon->setImplicit();
5732 
5733   // Mark this as an anonymous struct/union type.
5734   Record->setAnonymousStructOrUnion(true);
5735 
5736   // Add the anonymous struct/union object to the current
5737   // context. We'll be referencing this object when we refer to one of
5738   // its members.
5739   Owner->addDecl(Anon);
5740 
5741   // Inject the members of the anonymous struct/union into the owning
5742   // context and into the identifier resolver chain for name lookup
5743   // purposes.
5744   SmallVector<NamedDecl*, 2> Chain;
5745   Chain.push_back(Anon);
5746 
5747   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5748     Invalid = true;
5749 
5750   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5751     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5752       MangleNumberingContext *MCtx;
5753       Decl *ManglingContextDecl;
5754       std::tie(MCtx, ManglingContextDecl) =
5755           getCurrentMangleNumberContext(NewVD->getDeclContext());
5756       if (MCtx) {
5757         Context.setManglingNumber(
5758             NewVD, MCtx->getManglingNumber(
5759                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5760         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5761       }
5762     }
5763   }
5764 
5765   if (Invalid)
5766     Anon->setInvalidDecl();
5767 
5768   return Anon;
5769 }
5770 
5771 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5772 /// Microsoft C anonymous structure.
5773 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5774 /// Example:
5775 ///
5776 /// struct A { int a; };
5777 /// struct B { struct A; int b; };
5778 ///
5779 /// void foo() {
5780 ///   B var;
5781 ///   var.a = 3;
5782 /// }
5783 ///
5784 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5785                                            RecordDecl *Record) {
5786   assert(Record && "expected a record!");
5787 
5788   // Mock up a declarator.
5789   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5790   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5791   assert(TInfo && "couldn't build declarator info for anonymous struct");
5792 
5793   auto *ParentDecl = cast<RecordDecl>(CurContext);
5794   QualType RecTy = Context.getTypeDeclType(Record);
5795 
5796   // Create a declaration for this anonymous struct.
5797   NamedDecl *Anon =
5798       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5799                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5800                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5801                         /*InitStyle=*/ICIS_NoInit);
5802   Anon->setImplicit();
5803 
5804   // Add the anonymous struct object to the current context.
5805   CurContext->addDecl(Anon);
5806 
5807   // Inject the members of the anonymous struct into the current
5808   // context and into the identifier resolver chain for name lookup
5809   // purposes.
5810   SmallVector<NamedDecl*, 2> Chain;
5811   Chain.push_back(Anon);
5812 
5813   RecordDecl *RecordDef = Record->getDefinition();
5814   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5815                                diag::err_field_incomplete_or_sizeless) ||
5816       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5817                                           AS_none, Chain)) {
5818     Anon->setInvalidDecl();
5819     ParentDecl->setInvalidDecl();
5820   }
5821 
5822   return Anon;
5823 }
5824 
5825 /// GetNameForDeclarator - Determine the full declaration name for the
5826 /// given Declarator.
5827 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5828   return GetNameFromUnqualifiedId(D.getName());
5829 }
5830 
5831 /// Retrieves the declaration name from a parsed unqualified-id.
5832 DeclarationNameInfo
5833 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5834   DeclarationNameInfo NameInfo;
5835   NameInfo.setLoc(Name.StartLocation);
5836 
5837   switch (Name.getKind()) {
5838 
5839   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5840   case UnqualifiedIdKind::IK_Identifier:
5841     NameInfo.setName(Name.Identifier);
5842     return NameInfo;
5843 
5844   case UnqualifiedIdKind::IK_DeductionGuideName: {
5845     // C++ [temp.deduct.guide]p3:
5846     //   The simple-template-id shall name a class template specialization.
5847     //   The template-name shall be the same identifier as the template-name
5848     //   of the simple-template-id.
5849     // These together intend to imply that the template-name shall name a
5850     // class template.
5851     // FIXME: template<typename T> struct X {};
5852     //        template<typename T> using Y = X<T>;
5853     //        Y(int) -> Y<int>;
5854     //   satisfies these rules but does not name a class template.
5855     TemplateName TN = Name.TemplateName.get().get();
5856     auto *Template = TN.getAsTemplateDecl();
5857     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5858       Diag(Name.StartLocation,
5859            diag::err_deduction_guide_name_not_class_template)
5860         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5861       if (Template)
5862         Diag(Template->getLocation(), diag::note_template_decl_here);
5863       return DeclarationNameInfo();
5864     }
5865 
5866     NameInfo.setName(
5867         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5868     return NameInfo;
5869   }
5870 
5871   case UnqualifiedIdKind::IK_OperatorFunctionId:
5872     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5873                                            Name.OperatorFunctionId.Operator));
5874     NameInfo.setCXXOperatorNameRange(SourceRange(
5875         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5876     return NameInfo;
5877 
5878   case UnqualifiedIdKind::IK_LiteralOperatorId:
5879     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5880                                                            Name.Identifier));
5881     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5882     return NameInfo;
5883 
5884   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5885     TypeSourceInfo *TInfo;
5886     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5887     if (Ty.isNull())
5888       return DeclarationNameInfo();
5889     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5890                                                Context.getCanonicalType(Ty)));
5891     NameInfo.setNamedTypeInfo(TInfo);
5892     return NameInfo;
5893   }
5894 
5895   case UnqualifiedIdKind::IK_ConstructorName: {
5896     TypeSourceInfo *TInfo;
5897     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5898     if (Ty.isNull())
5899       return DeclarationNameInfo();
5900     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5901                                               Context.getCanonicalType(Ty)));
5902     NameInfo.setNamedTypeInfo(TInfo);
5903     return NameInfo;
5904   }
5905 
5906   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5907     // In well-formed code, we can only have a constructor
5908     // template-id that refers to the current context, so go there
5909     // to find the actual type being constructed.
5910     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5911     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5912       return DeclarationNameInfo();
5913 
5914     // Determine the type of the class being constructed.
5915     QualType CurClassType = Context.getTypeDeclType(CurClass);
5916 
5917     // FIXME: Check two things: that the template-id names the same type as
5918     // CurClassType, and that the template-id does not occur when the name
5919     // was qualified.
5920 
5921     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5922                                     Context.getCanonicalType(CurClassType)));
5923     // FIXME: should we retrieve TypeSourceInfo?
5924     NameInfo.setNamedTypeInfo(nullptr);
5925     return NameInfo;
5926   }
5927 
5928   case UnqualifiedIdKind::IK_DestructorName: {
5929     TypeSourceInfo *TInfo;
5930     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5931     if (Ty.isNull())
5932       return DeclarationNameInfo();
5933     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5934                                               Context.getCanonicalType(Ty)));
5935     NameInfo.setNamedTypeInfo(TInfo);
5936     return NameInfo;
5937   }
5938 
5939   case UnqualifiedIdKind::IK_TemplateId: {
5940     TemplateName TName = Name.TemplateId->Template.get();
5941     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5942     return Context.getNameForTemplate(TName, TNameLoc);
5943   }
5944 
5945   } // switch (Name.getKind())
5946 
5947   llvm_unreachable("Unknown name kind");
5948 }
5949 
5950 static QualType getCoreType(QualType Ty) {
5951   do {
5952     if (Ty->isPointerType() || Ty->isReferenceType())
5953       Ty = Ty->getPointeeType();
5954     else if (Ty->isArrayType())
5955       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5956     else
5957       return Ty.withoutLocalFastQualifiers();
5958   } while (true);
5959 }
5960 
5961 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5962 /// and Definition have "nearly" matching parameters. This heuristic is
5963 /// used to improve diagnostics in the case where an out-of-line function
5964 /// definition doesn't match any declaration within the class or namespace.
5965 /// Also sets Params to the list of indices to the parameters that differ
5966 /// between the declaration and the definition. If hasSimilarParameters
5967 /// returns true and Params is empty, then all of the parameters match.
5968 static bool hasSimilarParameters(ASTContext &Context,
5969                                      FunctionDecl *Declaration,
5970                                      FunctionDecl *Definition,
5971                                      SmallVectorImpl<unsigned> &Params) {
5972   Params.clear();
5973   if (Declaration->param_size() != Definition->param_size())
5974     return false;
5975   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5976     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5977     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5978 
5979     // The parameter types are identical
5980     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5981       continue;
5982 
5983     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5984     QualType DefParamBaseTy = getCoreType(DefParamTy);
5985     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5986     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5987 
5988     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5989         (DeclTyName && DeclTyName == DefTyName))
5990       Params.push_back(Idx);
5991     else  // The two parameters aren't even close
5992       return false;
5993   }
5994 
5995   return true;
5996 }
5997 
5998 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5999 /// declarator needs to be rebuilt in the current instantiation.
6000 /// Any bits of declarator which appear before the name are valid for
6001 /// consideration here.  That's specifically the type in the decl spec
6002 /// and the base type in any member-pointer chunks.
6003 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6004                                                     DeclarationName Name) {
6005   // The types we specifically need to rebuild are:
6006   //   - typenames, typeofs, and decltypes
6007   //   - types which will become injected class names
6008   // Of course, we also need to rebuild any type referencing such a
6009   // type.  It's safest to just say "dependent", but we call out a
6010   // few cases here.
6011 
6012   DeclSpec &DS = D.getMutableDeclSpec();
6013   switch (DS.getTypeSpecType()) {
6014   case DeclSpec::TST_typename:
6015   case DeclSpec::TST_typeofType:
6016   case DeclSpec::TST_typeof_unqualType:
6017 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6018 #include "clang/Basic/TransformTypeTraits.def"
6019   case DeclSpec::TST_atomic: {
6020     // Grab the type from the parser.
6021     TypeSourceInfo *TSI = nullptr;
6022     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6023     if (T.isNull() || !T->isInstantiationDependentType()) break;
6024 
6025     // Make sure there's a type source info.  This isn't really much
6026     // of a waste; most dependent types should have type source info
6027     // attached already.
6028     if (!TSI)
6029       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6030 
6031     // Rebuild the type in the current instantiation.
6032     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6033     if (!TSI) return true;
6034 
6035     // Store the new type back in the decl spec.
6036     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6037     DS.UpdateTypeRep(LocType);
6038     break;
6039   }
6040 
6041   case DeclSpec::TST_decltype:
6042   case DeclSpec::TST_typeof_unqualExpr:
6043   case DeclSpec::TST_typeofExpr: {
6044     Expr *E = DS.getRepAsExpr();
6045     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6046     if (Result.isInvalid()) return true;
6047     DS.UpdateExprRep(Result.get());
6048     break;
6049   }
6050 
6051   default:
6052     // Nothing to do for these decl specs.
6053     break;
6054   }
6055 
6056   // It doesn't matter what order we do this in.
6057   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6058     DeclaratorChunk &Chunk = D.getTypeObject(I);
6059 
6060     // The only type information in the declarator which can come
6061     // before the declaration name is the base type of a member
6062     // pointer.
6063     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6064       continue;
6065 
6066     // Rebuild the scope specifier in-place.
6067     CXXScopeSpec &SS = Chunk.Mem.Scope();
6068     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6069       return true;
6070   }
6071 
6072   return false;
6073 }
6074 
6075 /// Returns true if the declaration is declared in a system header or from a
6076 /// system macro.
6077 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6078   return SM.isInSystemHeader(D->getLocation()) ||
6079          SM.isInSystemMacro(D->getLocation());
6080 }
6081 
6082 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6083   // Avoid warning twice on the same identifier, and don't warn on redeclaration
6084   // of system decl.
6085   if (D->getPreviousDecl() || D->isImplicit())
6086     return;
6087   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6088   if (Status != ReservedIdentifierStatus::NotReserved &&
6089       !isFromSystemHeader(Context.getSourceManager(), D)) {
6090     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6091         << D << static_cast<int>(Status);
6092   }
6093 }
6094 
6095 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6096   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6097 
6098   // Check if we are in an `omp begin/end declare variant` scope. Handle this
6099   // declaration only if the `bind_to_declaration` extension is set.
6100   SmallVector<FunctionDecl *, 4> Bases;
6101   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6102     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6103               implementation_extension_bind_to_declaration))
6104     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6105         S, D, MultiTemplateParamsArg(), Bases);
6106 
6107   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6108 
6109   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6110       Dcl && Dcl->getDeclContext()->isFileContext())
6111     Dcl->setTopLevelDeclInObjCContainer();
6112 
6113   if (!Bases.empty())
6114     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6115 
6116   return Dcl;
6117 }
6118 
6119 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6120 ///   If T is the name of a class, then each of the following shall have a
6121 ///   name different from T:
6122 ///     - every static data member of class T;
6123 ///     - every member function of class T
6124 ///     - every member of class T that is itself a type;
6125 /// \returns true if the declaration name violates these rules.
6126 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6127                                    DeclarationNameInfo NameInfo) {
6128   DeclarationName Name = NameInfo.getName();
6129 
6130   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6131   while (Record && Record->isAnonymousStructOrUnion())
6132     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6133   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6134     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6135     return true;
6136   }
6137 
6138   return false;
6139 }
6140 
6141 /// Diagnose a declaration whose declarator-id has the given
6142 /// nested-name-specifier.
6143 ///
6144 /// \param SS The nested-name-specifier of the declarator-id.
6145 ///
6146 /// \param DC The declaration context to which the nested-name-specifier
6147 /// resolves.
6148 ///
6149 /// \param Name The name of the entity being declared.
6150 ///
6151 /// \param Loc The location of the name of the entity being declared.
6152 ///
6153 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6154 /// we're declaring an explicit / partial specialization / instantiation.
6155 ///
6156 /// \returns true if we cannot safely recover from this error, false otherwise.
6157 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6158                                         DeclarationName Name,
6159                                         SourceLocation Loc, bool IsTemplateId) {
6160   DeclContext *Cur = CurContext;
6161   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6162     Cur = Cur->getParent();
6163 
6164   // If the user provided a superfluous scope specifier that refers back to the
6165   // class in which the entity is already declared, diagnose and ignore it.
6166   //
6167   // class X {
6168   //   void X::f();
6169   // };
6170   //
6171   // Note, it was once ill-formed to give redundant qualification in all
6172   // contexts, but that rule was removed by DR482.
6173   if (Cur->Equals(DC)) {
6174     if (Cur->isRecord()) {
6175       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6176                                       : diag::err_member_extra_qualification)
6177         << Name << FixItHint::CreateRemoval(SS.getRange());
6178       SS.clear();
6179     } else {
6180       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6181     }
6182     return false;
6183   }
6184 
6185   // Check whether the qualifying scope encloses the scope of the original
6186   // declaration. For a template-id, we perform the checks in
6187   // CheckTemplateSpecializationScope.
6188   if (!Cur->Encloses(DC) && !IsTemplateId) {
6189     if (Cur->isRecord())
6190       Diag(Loc, diag::err_member_qualification)
6191         << Name << SS.getRange();
6192     else if (isa<TranslationUnitDecl>(DC))
6193       Diag(Loc, diag::err_invalid_declarator_global_scope)
6194         << Name << SS.getRange();
6195     else if (isa<FunctionDecl>(Cur))
6196       Diag(Loc, diag::err_invalid_declarator_in_function)
6197         << Name << SS.getRange();
6198     else if (isa<BlockDecl>(Cur))
6199       Diag(Loc, diag::err_invalid_declarator_in_block)
6200         << Name << SS.getRange();
6201     else if (isa<ExportDecl>(Cur)) {
6202       if (!isa<NamespaceDecl>(DC))
6203         Diag(Loc, diag::err_export_non_namespace_scope_name)
6204             << Name << SS.getRange();
6205       else
6206         // The cases that DC is not NamespaceDecl should be handled in
6207         // CheckRedeclarationExported.
6208         return false;
6209     } else
6210       Diag(Loc, diag::err_invalid_declarator_scope)
6211       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6212 
6213     return true;
6214   }
6215 
6216   if (Cur->isRecord()) {
6217     // Cannot qualify members within a class.
6218     Diag(Loc, diag::err_member_qualification)
6219       << Name << SS.getRange();
6220     SS.clear();
6221 
6222     // C++ constructors and destructors with incorrect scopes can break
6223     // our AST invariants by having the wrong underlying types. If
6224     // that's the case, then drop this declaration entirely.
6225     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6226          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6227         !Context.hasSameType(Name.getCXXNameType(),
6228                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6229       return true;
6230 
6231     return false;
6232   }
6233 
6234   // C++11 [dcl.meaning]p1:
6235   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6236   //   not begin with a decltype-specifer"
6237   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6238   while (SpecLoc.getPrefix())
6239     SpecLoc = SpecLoc.getPrefix();
6240   if (isa_and_nonnull<DecltypeType>(
6241           SpecLoc.getNestedNameSpecifier()->getAsType()))
6242     Diag(Loc, diag::err_decltype_in_declarator)
6243       << SpecLoc.getTypeLoc().getSourceRange();
6244 
6245   return false;
6246 }
6247 
6248 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6249                                   MultiTemplateParamsArg TemplateParamLists) {
6250   // TODO: consider using NameInfo for diagnostic.
6251   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6252   DeclarationName Name = NameInfo.getName();
6253 
6254   // All of these full declarators require an identifier.  If it doesn't have
6255   // one, the ParsedFreeStandingDeclSpec action should be used.
6256   if (D.isDecompositionDeclarator()) {
6257     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6258   } else if (!Name) {
6259     if (!D.isInvalidType())  // Reject this if we think it is valid.
6260       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6261           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6262     return nullptr;
6263   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6264     return nullptr;
6265 
6266   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6267   // we find one that is.
6268   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6269          (S->getFlags() & Scope::TemplateParamScope) != 0)
6270     S = S->getParent();
6271 
6272   DeclContext *DC = CurContext;
6273   if (D.getCXXScopeSpec().isInvalid())
6274     D.setInvalidType();
6275   else if (D.getCXXScopeSpec().isSet()) {
6276     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6277                                         UPPC_DeclarationQualifier))
6278       return nullptr;
6279 
6280     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6281     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6282     if (!DC || isa<EnumDecl>(DC)) {
6283       // If we could not compute the declaration context, it's because the
6284       // declaration context is dependent but does not refer to a class,
6285       // class template, or class template partial specialization. Complain
6286       // and return early, to avoid the coming semantic disaster.
6287       Diag(D.getIdentifierLoc(),
6288            diag::err_template_qualified_declarator_no_match)
6289         << D.getCXXScopeSpec().getScopeRep()
6290         << D.getCXXScopeSpec().getRange();
6291       return nullptr;
6292     }
6293     bool IsDependentContext = DC->isDependentContext();
6294 
6295     if (!IsDependentContext &&
6296         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6297       return nullptr;
6298 
6299     // If a class is incomplete, do not parse entities inside it.
6300     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6301       Diag(D.getIdentifierLoc(),
6302            diag::err_member_def_undefined_record)
6303         << Name << DC << D.getCXXScopeSpec().getRange();
6304       return nullptr;
6305     }
6306     if (!D.getDeclSpec().isFriendSpecified()) {
6307       if (diagnoseQualifiedDeclaration(
6308               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6309               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6310         if (DC->isRecord())
6311           return nullptr;
6312 
6313         D.setInvalidType();
6314       }
6315     }
6316 
6317     // Check whether we need to rebuild the type of the given
6318     // declaration in the current instantiation.
6319     if (EnteringContext && IsDependentContext &&
6320         TemplateParamLists.size() != 0) {
6321       ContextRAII SavedContext(*this, DC);
6322       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6323         D.setInvalidType();
6324     }
6325   }
6326 
6327   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6328   QualType R = TInfo->getType();
6329 
6330   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6331                                       UPPC_DeclarationType))
6332     D.setInvalidType();
6333 
6334   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6335                         forRedeclarationInCurContext());
6336 
6337   // See if this is a redefinition of a variable in the same scope.
6338   if (!D.getCXXScopeSpec().isSet()) {
6339     bool IsLinkageLookup = false;
6340     bool CreateBuiltins = false;
6341 
6342     // If the declaration we're planning to build will be a function
6343     // or object with linkage, then look for another declaration with
6344     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6345     //
6346     // If the declaration we're planning to build will be declared with
6347     // external linkage in the translation unit, create any builtin with
6348     // the same name.
6349     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6350       /* Do nothing*/;
6351     else if (CurContext->isFunctionOrMethod() &&
6352              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6353               R->isFunctionType())) {
6354       IsLinkageLookup = true;
6355       CreateBuiltins =
6356           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6357     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6358                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6359       CreateBuiltins = true;
6360 
6361     if (IsLinkageLookup) {
6362       Previous.clear(LookupRedeclarationWithLinkage);
6363       Previous.setRedeclarationKind(ForExternalRedeclaration);
6364     }
6365 
6366     LookupName(Previous, S, CreateBuiltins);
6367   } else { // Something like "int foo::x;"
6368     LookupQualifiedName(Previous, DC);
6369 
6370     // C++ [dcl.meaning]p1:
6371     //   When the declarator-id is qualified, the declaration shall refer to a
6372     //  previously declared member of the class or namespace to which the
6373     //  qualifier refers (or, in the case of a namespace, of an element of the
6374     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6375     //  thereof; [...]
6376     //
6377     // Note that we already checked the context above, and that we do not have
6378     // enough information to make sure that Previous contains the declaration
6379     // we want to match. For example, given:
6380     //
6381     //   class X {
6382     //     void f();
6383     //     void f(float);
6384     //   };
6385     //
6386     //   void X::f(int) { } // ill-formed
6387     //
6388     // In this case, Previous will point to the overload set
6389     // containing the two f's declared in X, but neither of them
6390     // matches.
6391 
6392     RemoveUsingDecls(Previous);
6393   }
6394 
6395   if (Previous.isSingleResult() &&
6396       Previous.getFoundDecl()->isTemplateParameter()) {
6397     // Maybe we will complain about the shadowed template parameter.
6398     if (!D.isInvalidType())
6399       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6400                                       Previous.getFoundDecl());
6401 
6402     // Just pretend that we didn't see the previous declaration.
6403     Previous.clear();
6404   }
6405 
6406   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6407     // Forget that the previous declaration is the injected-class-name.
6408     Previous.clear();
6409 
6410   // In C++, the previous declaration we find might be a tag type
6411   // (class or enum). In this case, the new declaration will hide the
6412   // tag type. Note that this applies to functions, function templates, and
6413   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6414   if (Previous.isSingleTagDecl() &&
6415       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6416       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6417     Previous.clear();
6418 
6419   // Check that there are no default arguments other than in the parameters
6420   // of a function declaration (C++ only).
6421   if (getLangOpts().CPlusPlus)
6422     CheckExtraCXXDefaultArguments(D);
6423 
6424   NamedDecl *New;
6425 
6426   bool AddToScope = true;
6427   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6428     if (TemplateParamLists.size()) {
6429       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6430       return nullptr;
6431     }
6432 
6433     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6434   } else if (R->isFunctionType()) {
6435     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6436                                   TemplateParamLists,
6437                                   AddToScope);
6438   } else {
6439     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6440                                   AddToScope);
6441   }
6442 
6443   if (!New)
6444     return nullptr;
6445 
6446   // If this has an identifier and is not a function template specialization,
6447   // add it to the scope stack.
6448   if (New->getDeclName() && AddToScope)
6449     PushOnScopeChains(New, S);
6450 
6451   if (isInOpenMPDeclareTargetContext())
6452     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6453 
6454   return New;
6455 }
6456 
6457 /// Helper method to turn variable array types into constant array
6458 /// types in certain situations which would otherwise be errors (for
6459 /// GCC compatibility).
6460 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6461                                                     ASTContext &Context,
6462                                                     bool &SizeIsNegative,
6463                                                     llvm::APSInt &Oversized) {
6464   // This method tries to turn a variable array into a constant
6465   // array even when the size isn't an ICE.  This is necessary
6466   // for compatibility with code that depends on gcc's buggy
6467   // constant expression folding, like struct {char x[(int)(char*)2];}
6468   SizeIsNegative = false;
6469   Oversized = 0;
6470 
6471   if (T->isDependentType())
6472     return QualType();
6473 
6474   QualifierCollector Qs;
6475   const Type *Ty = Qs.strip(T);
6476 
6477   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6478     QualType Pointee = PTy->getPointeeType();
6479     QualType FixedType =
6480         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6481                                             Oversized);
6482     if (FixedType.isNull()) return FixedType;
6483     FixedType = Context.getPointerType(FixedType);
6484     return Qs.apply(Context, FixedType);
6485   }
6486   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6487     QualType Inner = PTy->getInnerType();
6488     QualType FixedType =
6489         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6490                                             Oversized);
6491     if (FixedType.isNull()) return FixedType;
6492     FixedType = Context.getParenType(FixedType);
6493     return Qs.apply(Context, FixedType);
6494   }
6495 
6496   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6497   if (!VLATy)
6498     return QualType();
6499 
6500   QualType ElemTy = VLATy->getElementType();
6501   if (ElemTy->isVariablyModifiedType()) {
6502     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6503                                                  SizeIsNegative, Oversized);
6504     if (ElemTy.isNull())
6505       return QualType();
6506   }
6507 
6508   Expr::EvalResult Result;
6509   if (!VLATy->getSizeExpr() ||
6510       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6511     return QualType();
6512 
6513   llvm::APSInt Res = Result.Val.getInt();
6514 
6515   // Check whether the array size is negative.
6516   if (Res.isSigned() && Res.isNegative()) {
6517     SizeIsNegative = true;
6518     return QualType();
6519   }
6520 
6521   // Check whether the array is too large to be addressed.
6522   unsigned ActiveSizeBits =
6523       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6524        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6525           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6526           : Res.getActiveBits();
6527   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6528     Oversized = Res;
6529     return QualType();
6530   }
6531 
6532   QualType FoldedArrayType = Context.getConstantArrayType(
6533       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6534   return Qs.apply(Context, FoldedArrayType);
6535 }
6536 
6537 static void
6538 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6539   SrcTL = SrcTL.getUnqualifiedLoc();
6540   DstTL = DstTL.getUnqualifiedLoc();
6541   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6542     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6543     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6544                                       DstPTL.getPointeeLoc());
6545     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6546     return;
6547   }
6548   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6549     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6550     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6551                                       DstPTL.getInnerLoc());
6552     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6553     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6554     return;
6555   }
6556   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6557   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6558   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6559   TypeLoc DstElemTL = DstATL.getElementLoc();
6560   if (VariableArrayTypeLoc SrcElemATL =
6561           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6562     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6563     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6564   } else {
6565     DstElemTL.initializeFullCopy(SrcElemTL);
6566   }
6567   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6568   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6569   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6570 }
6571 
6572 /// Helper method to turn variable array types into constant array
6573 /// types in certain situations which would otherwise be errors (for
6574 /// GCC compatibility).
6575 static TypeSourceInfo*
6576 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6577                                               ASTContext &Context,
6578                                               bool &SizeIsNegative,
6579                                               llvm::APSInt &Oversized) {
6580   QualType FixedTy
6581     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6582                                           SizeIsNegative, Oversized);
6583   if (FixedTy.isNull())
6584     return nullptr;
6585   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6586   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6587                                     FixedTInfo->getTypeLoc());
6588   return FixedTInfo;
6589 }
6590 
6591 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6592 /// true if we were successful.
6593 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6594                                            QualType &T, SourceLocation Loc,
6595                                            unsigned FailedFoldDiagID) {
6596   bool SizeIsNegative;
6597   llvm::APSInt Oversized;
6598   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6599       TInfo, Context, SizeIsNegative, Oversized);
6600   if (FixedTInfo) {
6601     Diag(Loc, diag::ext_vla_folded_to_constant);
6602     TInfo = FixedTInfo;
6603     T = FixedTInfo->getType();
6604     return true;
6605   }
6606 
6607   if (SizeIsNegative)
6608     Diag(Loc, diag::err_typecheck_negative_array_size);
6609   else if (Oversized.getBoolValue())
6610     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6611   else if (FailedFoldDiagID)
6612     Diag(Loc, FailedFoldDiagID);
6613   return false;
6614 }
6615 
6616 /// Register the given locally-scoped extern "C" declaration so
6617 /// that it can be found later for redeclarations. We include any extern "C"
6618 /// declaration that is not visible in the translation unit here, not just
6619 /// function-scope declarations.
6620 void
6621 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6622   if (!getLangOpts().CPlusPlus &&
6623       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6624     // Don't need to track declarations in the TU in C.
6625     return;
6626 
6627   // Note that we have a locally-scoped external with this name.
6628   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6629 }
6630 
6631 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6632   // FIXME: We can have multiple results via __attribute__((overloadable)).
6633   auto Result = Context.getExternCContextDecl()->lookup(Name);
6634   return Result.empty() ? nullptr : *Result.begin();
6635 }
6636 
6637 /// Diagnose function specifiers on a declaration of an identifier that
6638 /// does not identify a function.
6639 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6640   // FIXME: We should probably indicate the identifier in question to avoid
6641   // confusion for constructs like "virtual int a(), b;"
6642   if (DS.isVirtualSpecified())
6643     Diag(DS.getVirtualSpecLoc(),
6644          diag::err_virtual_non_function);
6645 
6646   if (DS.hasExplicitSpecifier())
6647     Diag(DS.getExplicitSpecLoc(),
6648          diag::err_explicit_non_function);
6649 
6650   if (DS.isNoreturnSpecified())
6651     Diag(DS.getNoreturnSpecLoc(),
6652          diag::err_noreturn_non_function);
6653 }
6654 
6655 NamedDecl*
6656 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6657                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6658   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6659   if (D.getCXXScopeSpec().isSet()) {
6660     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6661       << D.getCXXScopeSpec().getRange();
6662     D.setInvalidType();
6663     // Pretend we didn't see the scope specifier.
6664     DC = CurContext;
6665     Previous.clear();
6666   }
6667 
6668   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6669 
6670   if (D.getDeclSpec().isInlineSpecified())
6671     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6672         << getLangOpts().CPlusPlus17;
6673   if (D.getDeclSpec().hasConstexprSpecifier())
6674     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6675         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6676 
6677   if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6678     if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6679       Diag(D.getName().StartLocation,
6680            diag::err_deduction_guide_invalid_specifier)
6681           << "typedef";
6682     else
6683       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6684           << D.getName().getSourceRange();
6685     return nullptr;
6686   }
6687 
6688   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6689   if (!NewTD) return nullptr;
6690 
6691   // Handle attributes prior to checking for duplicates in MergeVarDecl
6692   ProcessDeclAttributes(S, NewTD, D);
6693 
6694   CheckTypedefForVariablyModifiedType(S, NewTD);
6695 
6696   bool Redeclaration = D.isRedeclaration();
6697   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6698   D.setRedeclaration(Redeclaration);
6699   return ND;
6700 }
6701 
6702 void
6703 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6704   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6705   // then it shall have block scope.
6706   // Note that variably modified types must be fixed before merging the decl so
6707   // that redeclarations will match.
6708   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6709   QualType T = TInfo->getType();
6710   if (T->isVariablyModifiedType()) {
6711     setFunctionHasBranchProtectedScope();
6712 
6713     if (S->getFnParent() == nullptr) {
6714       bool SizeIsNegative;
6715       llvm::APSInt Oversized;
6716       TypeSourceInfo *FixedTInfo =
6717         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6718                                                       SizeIsNegative,
6719                                                       Oversized);
6720       if (FixedTInfo) {
6721         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6722         NewTD->setTypeSourceInfo(FixedTInfo);
6723       } else {
6724         if (SizeIsNegative)
6725           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6726         else if (T->isVariableArrayType())
6727           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6728         else if (Oversized.getBoolValue())
6729           Diag(NewTD->getLocation(), diag::err_array_too_large)
6730             << toString(Oversized, 10);
6731         else
6732           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6733         NewTD->setInvalidDecl();
6734       }
6735     }
6736   }
6737 }
6738 
6739 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6740 /// declares a typedef-name, either using the 'typedef' type specifier or via
6741 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6742 NamedDecl*
6743 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6744                            LookupResult &Previous, bool &Redeclaration) {
6745 
6746   // Find the shadowed declaration before filtering for scope.
6747   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6748 
6749   // Merge the decl with the existing one if appropriate. If the decl is
6750   // in an outer scope, it isn't the same thing.
6751   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6752                        /*AllowInlineNamespace*/false);
6753   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6754   if (!Previous.empty()) {
6755     Redeclaration = true;
6756     MergeTypedefNameDecl(S, NewTD, Previous);
6757   } else {
6758     inferGslPointerAttribute(NewTD);
6759   }
6760 
6761   if (ShadowedDecl && !Redeclaration)
6762     CheckShadow(NewTD, ShadowedDecl, Previous);
6763 
6764   // If this is the C FILE type, notify the AST context.
6765   if (IdentifierInfo *II = NewTD->getIdentifier())
6766     if (!NewTD->isInvalidDecl() &&
6767         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6768       switch (II->getInterestingIdentifierID()) {
6769       case tok::InterestingIdentifierKind::FILE:
6770         Context.setFILEDecl(NewTD);
6771         break;
6772       case tok::InterestingIdentifierKind::jmp_buf:
6773         Context.setjmp_bufDecl(NewTD);
6774         break;
6775       case tok::InterestingIdentifierKind::sigjmp_buf:
6776         Context.setsigjmp_bufDecl(NewTD);
6777         break;
6778       case tok::InterestingIdentifierKind::ucontext_t:
6779         Context.setucontext_tDecl(NewTD);
6780         break;
6781       case tok::InterestingIdentifierKind::float_t:
6782       case tok::InterestingIdentifierKind::double_t:
6783         NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6784         break;
6785       default:
6786         break;
6787       }
6788     }
6789 
6790   return NewTD;
6791 }
6792 
6793 /// Determines whether the given declaration is an out-of-scope
6794 /// previous declaration.
6795 ///
6796 /// This routine should be invoked when name lookup has found a
6797 /// previous declaration (PrevDecl) that is not in the scope where a
6798 /// new declaration by the same name is being introduced. If the new
6799 /// declaration occurs in a local scope, previous declarations with
6800 /// linkage may still be considered previous declarations (C99
6801 /// 6.2.2p4-5, C++ [basic.link]p6).
6802 ///
6803 /// \param PrevDecl the previous declaration found by name
6804 /// lookup
6805 ///
6806 /// \param DC the context in which the new declaration is being
6807 /// declared.
6808 ///
6809 /// \returns true if PrevDecl is an out-of-scope previous declaration
6810 /// for a new delcaration with the same name.
6811 static bool
6812 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6813                                 ASTContext &Context) {
6814   if (!PrevDecl)
6815     return false;
6816 
6817   if (!PrevDecl->hasLinkage())
6818     return false;
6819 
6820   if (Context.getLangOpts().CPlusPlus) {
6821     // C++ [basic.link]p6:
6822     //   If there is a visible declaration of an entity with linkage
6823     //   having the same name and type, ignoring entities declared
6824     //   outside the innermost enclosing namespace scope, the block
6825     //   scope declaration declares that same entity and receives the
6826     //   linkage of the previous declaration.
6827     DeclContext *OuterContext = DC->getRedeclContext();
6828     if (!OuterContext->isFunctionOrMethod())
6829       // This rule only applies to block-scope declarations.
6830       return false;
6831 
6832     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6833     if (PrevOuterContext->isRecord())
6834       // We found a member function: ignore it.
6835       return false;
6836 
6837     // Find the innermost enclosing namespace for the new and
6838     // previous declarations.
6839     OuterContext = OuterContext->getEnclosingNamespaceContext();
6840     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6841 
6842     // The previous declaration is in a different namespace, so it
6843     // isn't the same function.
6844     if (!OuterContext->Equals(PrevOuterContext))
6845       return false;
6846   }
6847 
6848   return true;
6849 }
6850 
6851 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6852   CXXScopeSpec &SS = D.getCXXScopeSpec();
6853   if (!SS.isSet()) return;
6854   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6855 }
6856 
6857 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6858   QualType type = decl->getType();
6859   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6860   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6861     // Various kinds of declaration aren't allowed to be __autoreleasing.
6862     unsigned kind = -1U;
6863     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6864       if (var->hasAttr<BlocksAttr>())
6865         kind = 0; // __block
6866       else if (!var->hasLocalStorage())
6867         kind = 1; // global
6868     } else if (isa<ObjCIvarDecl>(decl)) {
6869       kind = 3; // ivar
6870     } else if (isa<FieldDecl>(decl)) {
6871       kind = 2; // field
6872     }
6873 
6874     if (kind != -1U) {
6875       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6876         << kind;
6877     }
6878   } else if (lifetime == Qualifiers::OCL_None) {
6879     // Try to infer lifetime.
6880     if (!type->isObjCLifetimeType())
6881       return false;
6882 
6883     lifetime = type->getObjCARCImplicitLifetime();
6884     type = Context.getLifetimeQualifiedType(type, lifetime);
6885     decl->setType(type);
6886   }
6887 
6888   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6889     // Thread-local variables cannot have lifetime.
6890     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6891         var->getTLSKind()) {
6892       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6893         << var->getType();
6894       return true;
6895     }
6896   }
6897 
6898   return false;
6899 }
6900 
6901 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6902   if (Decl->getType().hasAddressSpace())
6903     return;
6904   if (Decl->getType()->isDependentType())
6905     return;
6906   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6907     QualType Type = Var->getType();
6908     if (Type->isSamplerT() || Type->isVoidType())
6909       return;
6910     LangAS ImplAS = LangAS::opencl_private;
6911     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6912     // __opencl_c_program_scope_global_variables feature, the address space
6913     // for a variable at program scope or a static or extern variable inside
6914     // a function are inferred to be __global.
6915     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6916         Var->hasGlobalStorage())
6917       ImplAS = LangAS::opencl_global;
6918     // If the original type from a decayed type is an array type and that array
6919     // type has no address space yet, deduce it now.
6920     if (auto DT = dyn_cast<DecayedType>(Type)) {
6921       auto OrigTy = DT->getOriginalType();
6922       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6923         // Add the address space to the original array type and then propagate
6924         // that to the element type through `getAsArrayType`.
6925         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6926         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6927         // Re-generate the decayed type.
6928         Type = Context.getDecayedType(OrigTy);
6929       }
6930     }
6931     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6932     // Apply any qualifiers (including address space) from the array type to
6933     // the element type. This implements C99 6.7.3p8: "If the specification of
6934     // an array type includes any type qualifiers, the element type is so
6935     // qualified, not the array type."
6936     if (Type->isArrayType())
6937       Type = QualType(Context.getAsArrayType(Type), 0);
6938     Decl->setType(Type);
6939   }
6940 }
6941 
6942 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6943   // Ensure that an auto decl is deduced otherwise the checks below might cache
6944   // the wrong linkage.
6945   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6946 
6947   // 'weak' only applies to declarations with external linkage.
6948   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6949     if (!ND.isExternallyVisible()) {
6950       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6951       ND.dropAttr<WeakAttr>();
6952     }
6953   }
6954   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6955     if (ND.isExternallyVisible()) {
6956       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6957       ND.dropAttr<WeakRefAttr>();
6958       ND.dropAttr<AliasAttr>();
6959     }
6960   }
6961 
6962   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6963     if (VD->hasInit()) {
6964       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6965         assert(VD->isThisDeclarationADefinition() &&
6966                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6967         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6968         VD->dropAttr<AliasAttr>();
6969       }
6970     }
6971   }
6972 
6973   // 'selectany' only applies to externally visible variable declarations.
6974   // It does not apply to functions.
6975   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6976     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6977       S.Diag(Attr->getLocation(),
6978              diag::err_attribute_selectany_non_extern_data);
6979       ND.dropAttr<SelectAnyAttr>();
6980     }
6981   }
6982 
6983   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6984     auto *VD = dyn_cast<VarDecl>(&ND);
6985     bool IsAnonymousNS = false;
6986     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6987     if (VD) {
6988       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6989       while (NS && !IsAnonymousNS) {
6990         IsAnonymousNS = NS->isAnonymousNamespace();
6991         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6992       }
6993     }
6994     // dll attributes require external linkage. Static locals may have external
6995     // linkage but still cannot be explicitly imported or exported.
6996     // In Microsoft mode, a variable defined in anonymous namespace must have
6997     // external linkage in order to be exported.
6998     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6999     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7000         (!AnonNSInMicrosoftMode &&
7001          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7002       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7003         << &ND << Attr;
7004       ND.setInvalidDecl();
7005     }
7006   }
7007 
7008   // Check the attributes on the function type, if any.
7009   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7010     // Don't declare this variable in the second operand of the for-statement;
7011     // GCC miscompiles that by ending its lifetime before evaluating the
7012     // third operand. See gcc.gnu.org/PR86769.
7013     AttributedTypeLoc ATL;
7014     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7015          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7016          TL = ATL.getModifiedLoc()) {
7017       // The [[lifetimebound]] attribute can be applied to the implicit object
7018       // parameter of a non-static member function (other than a ctor or dtor)
7019       // by applying it to the function type.
7020       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7021         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7022         if (!MD || MD->isStatic()) {
7023           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7024               << !MD << A->getRange();
7025         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7026           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7027               << isa<CXXDestructorDecl>(MD) << A->getRange();
7028         }
7029       }
7030     }
7031   }
7032 }
7033 
7034 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7035                                            NamedDecl *NewDecl,
7036                                            bool IsSpecialization,
7037                                            bool IsDefinition) {
7038   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7039     return;
7040 
7041   bool IsTemplate = false;
7042   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7043     OldDecl = OldTD->getTemplatedDecl();
7044     IsTemplate = true;
7045     if (!IsSpecialization)
7046       IsDefinition = false;
7047   }
7048   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7049     NewDecl = NewTD->getTemplatedDecl();
7050     IsTemplate = true;
7051   }
7052 
7053   if (!OldDecl || !NewDecl)
7054     return;
7055 
7056   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7057   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7058   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7059   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7060 
7061   // dllimport and dllexport are inheritable attributes so we have to exclude
7062   // inherited attribute instances.
7063   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7064                     (NewExportAttr && !NewExportAttr->isInherited());
7065 
7066   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7067   // the only exception being explicit specializations.
7068   // Implicitly generated declarations are also excluded for now because there
7069   // is no other way to switch these to use dllimport or dllexport.
7070   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7071 
7072   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7073     // Allow with a warning for free functions and global variables.
7074     bool JustWarn = false;
7075     if (!OldDecl->isCXXClassMember()) {
7076       auto *VD = dyn_cast<VarDecl>(OldDecl);
7077       if (VD && !VD->getDescribedVarTemplate())
7078         JustWarn = true;
7079       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7080       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7081         JustWarn = true;
7082     }
7083 
7084     // We cannot change a declaration that's been used because IR has already
7085     // been emitted. Dllimported functions will still work though (modulo
7086     // address equality) as they can use the thunk.
7087     if (OldDecl->isUsed())
7088       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7089         JustWarn = false;
7090 
7091     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7092                                : diag::err_attribute_dll_redeclaration;
7093     S.Diag(NewDecl->getLocation(), DiagID)
7094         << NewDecl
7095         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7096     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7097     if (!JustWarn) {
7098       NewDecl->setInvalidDecl();
7099       return;
7100     }
7101   }
7102 
7103   // A redeclaration is not allowed to drop a dllimport attribute, the only
7104   // exceptions being inline function definitions (except for function
7105   // templates), local extern declarations, qualified friend declarations or
7106   // special MSVC extension: in the last case, the declaration is treated as if
7107   // it were marked dllexport.
7108   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7109   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7110   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7111     // Ignore static data because out-of-line definitions are diagnosed
7112     // separately.
7113     IsStaticDataMember = VD->isStaticDataMember();
7114     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7115                    VarDecl::DeclarationOnly;
7116   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7117     IsInline = FD->isInlined();
7118     IsQualifiedFriend = FD->getQualifier() &&
7119                         FD->getFriendObjectKind() == Decl::FOK_Declared;
7120   }
7121 
7122   if (OldImportAttr && !HasNewAttr &&
7123       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7124       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7125     if (IsMicrosoftABI && IsDefinition) {
7126       if (IsSpecialization) {
7127         S.Diag(
7128             NewDecl->getLocation(),
7129             diag::err_attribute_dllimport_function_specialization_definition);
7130         S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7131         NewDecl->dropAttr<DLLImportAttr>();
7132       } else {
7133         S.Diag(NewDecl->getLocation(),
7134                diag::warn_redeclaration_without_import_attribute)
7135             << NewDecl;
7136         S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7137         NewDecl->dropAttr<DLLImportAttr>();
7138         NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7139             S.Context, NewImportAttr->getRange()));
7140       }
7141     } else if (IsMicrosoftABI && IsSpecialization) {
7142       assert(!IsDefinition);
7143       // MSVC allows this. Keep the inherited attribute.
7144     } else {
7145       S.Diag(NewDecl->getLocation(),
7146              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7147           << NewDecl << OldImportAttr;
7148       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7149       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7150       OldDecl->dropAttr<DLLImportAttr>();
7151       NewDecl->dropAttr<DLLImportAttr>();
7152     }
7153   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7154     // In MinGW, seeing a function declared inline drops the dllimport
7155     // attribute.
7156     OldDecl->dropAttr<DLLImportAttr>();
7157     NewDecl->dropAttr<DLLImportAttr>();
7158     S.Diag(NewDecl->getLocation(),
7159            diag::warn_dllimport_dropped_from_inline_function)
7160         << NewDecl << OldImportAttr;
7161   }
7162 
7163   // A specialization of a class template member function is processed here
7164   // since it's a redeclaration. If the parent class is dllexport, the
7165   // specialization inherits that attribute. This doesn't happen automatically
7166   // since the parent class isn't instantiated until later.
7167   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7168     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7169         !NewImportAttr && !NewExportAttr) {
7170       if (const DLLExportAttr *ParentExportAttr =
7171               MD->getParent()->getAttr<DLLExportAttr>()) {
7172         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7173         NewAttr->setInherited(true);
7174         NewDecl->addAttr(NewAttr);
7175       }
7176     }
7177   }
7178 }
7179 
7180 /// Given that we are within the definition of the given function,
7181 /// will that definition behave like C99's 'inline', where the
7182 /// definition is discarded except for optimization purposes?
7183 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7184   // Try to avoid calling GetGVALinkageForFunction.
7185 
7186   // All cases of this require the 'inline' keyword.
7187   if (!FD->isInlined()) return false;
7188 
7189   // This is only possible in C++ with the gnu_inline attribute.
7190   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7191     return false;
7192 
7193   // Okay, go ahead and call the relatively-more-expensive function.
7194   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7195 }
7196 
7197 /// Determine whether a variable is extern "C" prior to attaching
7198 /// an initializer. We can't just call isExternC() here, because that
7199 /// will also compute and cache whether the declaration is externally
7200 /// visible, which might change when we attach the initializer.
7201 ///
7202 /// This can only be used if the declaration is known to not be a
7203 /// redeclaration of an internal linkage declaration.
7204 ///
7205 /// For instance:
7206 ///
7207 ///   auto x = []{};
7208 ///
7209 /// Attaching the initializer here makes this declaration not externally
7210 /// visible, because its type has internal linkage.
7211 ///
7212 /// FIXME: This is a hack.
7213 template<typename T>
7214 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7215   if (S.getLangOpts().CPlusPlus) {
7216     // In C++, the overloadable attribute negates the effects of extern "C".
7217     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7218       return false;
7219 
7220     // So do CUDA's host/device attributes.
7221     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7222                                  D->template hasAttr<CUDAHostAttr>()))
7223       return false;
7224   }
7225   return D->isExternC();
7226 }
7227 
7228 static bool shouldConsiderLinkage(const VarDecl *VD) {
7229   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7230   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7231       isa<OMPDeclareMapperDecl>(DC))
7232     return VD->hasExternalStorage();
7233   if (DC->isFileContext())
7234     return true;
7235   if (DC->isRecord())
7236     return false;
7237   if (DC->getDeclKind() == Decl::HLSLBuffer)
7238     return false;
7239 
7240   if (isa<RequiresExprBodyDecl>(DC))
7241     return false;
7242   llvm_unreachable("Unexpected context");
7243 }
7244 
7245 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7246   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7247   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7248       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7249     return true;
7250   if (DC->isRecord())
7251     return false;
7252   llvm_unreachable("Unexpected context");
7253 }
7254 
7255 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7256                           ParsedAttr::Kind Kind) {
7257   // Check decl attributes on the DeclSpec.
7258   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7259     return true;
7260 
7261   // Walk the declarator structure, checking decl attributes that were in a type
7262   // position to the decl itself.
7263   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7264     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7265       return true;
7266   }
7267 
7268   // Finally, check attributes on the decl itself.
7269   return PD.getAttributes().hasAttribute(Kind) ||
7270          PD.getDeclarationAttributes().hasAttribute(Kind);
7271 }
7272 
7273 /// Adjust the \c DeclContext for a function or variable that might be a
7274 /// function-local external declaration.
7275 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7276   if (!DC->isFunctionOrMethod())
7277     return false;
7278 
7279   // If this is a local extern function or variable declared within a function
7280   // template, don't add it into the enclosing namespace scope until it is
7281   // instantiated; it might have a dependent type right now.
7282   if (DC->isDependentContext())
7283     return true;
7284 
7285   // C++11 [basic.link]p7:
7286   //   When a block scope declaration of an entity with linkage is not found to
7287   //   refer to some other declaration, then that entity is a member of the
7288   //   innermost enclosing namespace.
7289   //
7290   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7291   // semantically-enclosing namespace, not a lexically-enclosing one.
7292   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7293     DC = DC->getParent();
7294   return true;
7295 }
7296 
7297 /// Returns true if given declaration has external C language linkage.
7298 static bool isDeclExternC(const Decl *D) {
7299   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7300     return FD->isExternC();
7301   if (const auto *VD = dyn_cast<VarDecl>(D))
7302     return VD->isExternC();
7303 
7304   llvm_unreachable("Unknown type of decl!");
7305 }
7306 
7307 /// Returns true if there hasn't been any invalid type diagnosed.
7308 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7309   DeclContext *DC = NewVD->getDeclContext();
7310   QualType R = NewVD->getType();
7311 
7312   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7313   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7314   // argument.
7315   if (R->isImageType() || R->isPipeType()) {
7316     Se.Diag(NewVD->getLocation(),
7317             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7318         << R;
7319     NewVD->setInvalidDecl();
7320     return false;
7321   }
7322 
7323   // OpenCL v1.2 s6.9.r:
7324   // The event type cannot be used to declare a program scope variable.
7325   // OpenCL v2.0 s6.9.q:
7326   // The clk_event_t and reserve_id_t types cannot be declared in program
7327   // scope.
7328   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7329     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7330       Se.Diag(NewVD->getLocation(),
7331               diag::err_invalid_type_for_program_scope_var)
7332           << R;
7333       NewVD->setInvalidDecl();
7334       return false;
7335     }
7336   }
7337 
7338   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7339   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7340                                                Se.getLangOpts())) {
7341     QualType NR = R.getCanonicalType();
7342     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7343            NR->isReferenceType()) {
7344       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7345           NR->isFunctionReferenceType()) {
7346         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7347             << NR->isReferenceType();
7348         NewVD->setInvalidDecl();
7349         return false;
7350       }
7351       NR = NR->getPointeeType();
7352     }
7353   }
7354 
7355   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7356                                                Se.getLangOpts())) {
7357     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7358     // half array type (unless the cl_khr_fp16 extension is enabled).
7359     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7360       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7361       NewVD->setInvalidDecl();
7362       return false;
7363     }
7364   }
7365 
7366   // OpenCL v1.2 s6.9.r:
7367   // The event type cannot be used with the __local, __constant and __global
7368   // address space qualifiers.
7369   if (R->isEventT()) {
7370     if (R.getAddressSpace() != LangAS::opencl_private) {
7371       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7372       NewVD->setInvalidDecl();
7373       return false;
7374     }
7375   }
7376 
7377   if (R->isSamplerT()) {
7378     // OpenCL v1.2 s6.9.b p4:
7379     // The sampler type cannot be used with the __local and __global address
7380     // space qualifiers.
7381     if (R.getAddressSpace() == LangAS::opencl_local ||
7382         R.getAddressSpace() == LangAS::opencl_global) {
7383       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7384       NewVD->setInvalidDecl();
7385     }
7386 
7387     // OpenCL v1.2 s6.12.14.1:
7388     // A global sampler must be declared with either the constant address
7389     // space qualifier or with the const qualifier.
7390     if (DC->isTranslationUnit() &&
7391         !(R.getAddressSpace() == LangAS::opencl_constant ||
7392           R.isConstQualified())) {
7393       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7394       NewVD->setInvalidDecl();
7395     }
7396     if (NewVD->isInvalidDecl())
7397       return false;
7398   }
7399 
7400   return true;
7401 }
7402 
7403 template <typename AttrTy>
7404 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7405   const TypedefNameDecl *TND = TT->getDecl();
7406   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7407     AttrTy *Clone = Attribute->clone(S.Context);
7408     Clone->setInherited(true);
7409     D->addAttr(Clone);
7410   }
7411 }
7412 
7413 // This function emits warning and a corresponding note based on the
7414 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7415 // declarations of an annotated type must be const qualified.
7416 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7417   QualType VarType = VD->getType().getCanonicalType();
7418 
7419   // Ignore local declarations (for now) and those with const qualification.
7420   // TODO: Local variables should not be allowed if their type declaration has
7421   // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7422   if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7423     return;
7424 
7425   if (VarType->isArrayType()) {
7426     // Retrieve element type for array declarations.
7427     VarType = S.getASTContext().getBaseElementType(VarType);
7428   }
7429 
7430   const RecordDecl *RD = VarType->getAsRecordDecl();
7431 
7432   // Check if the record declaration is present and if it has any attributes.
7433   if (RD == nullptr)
7434     return;
7435 
7436   if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7437     S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7438     S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7439     return;
7440   }
7441 }
7442 
7443 NamedDecl *Sema::ActOnVariableDeclarator(
7444     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7445     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7446     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7447   QualType R = TInfo->getType();
7448   DeclarationName Name = GetNameForDeclarator(D).getName();
7449 
7450   IdentifierInfo *II = Name.getAsIdentifierInfo();
7451 
7452   if (D.isDecompositionDeclarator()) {
7453     // Take the name of the first declarator as our name for diagnostic
7454     // purposes.
7455     auto &Decomp = D.getDecompositionDeclarator();
7456     if (!Decomp.bindings().empty()) {
7457       II = Decomp.bindings()[0].Name;
7458       Name = II;
7459     }
7460   } else if (!II) {
7461     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7462     return nullptr;
7463   }
7464 
7465 
7466   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7467   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7468 
7469   // dllimport globals without explicit storage class are treated as extern. We
7470   // have to change the storage class this early to get the right DeclContext.
7471   if (SC == SC_None && !DC->isRecord() &&
7472       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7473       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7474     SC = SC_Extern;
7475 
7476   DeclContext *OriginalDC = DC;
7477   bool IsLocalExternDecl = SC == SC_Extern &&
7478                            adjustContextForLocalExternDecl(DC);
7479 
7480   if (SCSpec == DeclSpec::SCS_mutable) {
7481     // mutable can only appear on non-static class members, so it's always
7482     // an error here
7483     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7484     D.setInvalidType();
7485     SC = SC_None;
7486   }
7487 
7488   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7489       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7490                               D.getDeclSpec().getStorageClassSpecLoc())) {
7491     // In C++11, the 'register' storage class specifier is deprecated.
7492     // Suppress the warning in system macros, it's used in macros in some
7493     // popular C system headers, such as in glibc's htonl() macro.
7494     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7495          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7496                                    : diag::warn_deprecated_register)
7497       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7498   }
7499 
7500   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7501 
7502   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7503     // C99 6.9p2: The storage-class specifiers auto and register shall not
7504     // appear in the declaration specifiers in an external declaration.
7505     // Global Register+Asm is a GNU extension we support.
7506     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7507       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7508       D.setInvalidType();
7509     }
7510   }
7511 
7512   // If this variable has a VLA type and an initializer, try to
7513   // fold to a constant-sized type. This is otherwise invalid.
7514   if (D.hasInitializer() && R->isVariableArrayType())
7515     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7516                                     /*DiagID=*/0);
7517 
7518   bool IsMemberSpecialization = false;
7519   bool IsVariableTemplateSpecialization = false;
7520   bool IsPartialSpecialization = false;
7521   bool IsVariableTemplate = false;
7522   VarDecl *NewVD = nullptr;
7523   VarTemplateDecl *NewTemplate = nullptr;
7524   TemplateParameterList *TemplateParams = nullptr;
7525   if (!getLangOpts().CPlusPlus) {
7526     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7527                             II, R, TInfo, SC);
7528 
7529     if (R->getContainedDeducedType())
7530       ParsingInitForAutoVars.insert(NewVD);
7531 
7532     if (D.isInvalidType())
7533       NewVD->setInvalidDecl();
7534 
7535     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7536         NewVD->hasLocalStorage())
7537       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7538                             NTCUC_AutoVar, NTCUK_Destruct);
7539   } else {
7540     bool Invalid = false;
7541 
7542     if (DC->isRecord() && !CurContext->isRecord()) {
7543       // This is an out-of-line definition of a static data member.
7544       switch (SC) {
7545       case SC_None:
7546         break;
7547       case SC_Static:
7548         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7549              diag::err_static_out_of_line)
7550           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7551         break;
7552       case SC_Auto:
7553       case SC_Register:
7554       case SC_Extern:
7555         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7556         // to names of variables declared in a block or to function parameters.
7557         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7558         // of class members
7559 
7560         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7561              diag::err_storage_class_for_static_member)
7562           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7563         break;
7564       case SC_PrivateExtern:
7565         llvm_unreachable("C storage class in c++!");
7566       }
7567     }
7568 
7569     if (SC == SC_Static && CurContext->isRecord()) {
7570       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7571         // Walk up the enclosing DeclContexts to check for any that are
7572         // incompatible with static data members.
7573         const DeclContext *FunctionOrMethod = nullptr;
7574         const CXXRecordDecl *AnonStruct = nullptr;
7575         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7576           if (Ctxt->isFunctionOrMethod()) {
7577             FunctionOrMethod = Ctxt;
7578             break;
7579           }
7580           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7581           if (ParentDecl && !ParentDecl->getDeclName()) {
7582             AnonStruct = ParentDecl;
7583             break;
7584           }
7585         }
7586         if (FunctionOrMethod) {
7587           // C++ [class.static.data]p5: A local class shall not have static data
7588           // members.
7589           Diag(D.getIdentifierLoc(),
7590                diag::err_static_data_member_not_allowed_in_local_class)
7591             << Name << RD->getDeclName() << RD->getTagKind();
7592         } else if (AnonStruct) {
7593           // C++ [class.static.data]p4: Unnamed classes and classes contained
7594           // directly or indirectly within unnamed classes shall not contain
7595           // static data members.
7596           Diag(D.getIdentifierLoc(),
7597                diag::err_static_data_member_not_allowed_in_anon_struct)
7598             << Name << AnonStruct->getTagKind();
7599           Invalid = true;
7600         } else if (RD->isUnion()) {
7601           // C++98 [class.union]p1: If a union contains a static data member,
7602           // the program is ill-formed. C++11 drops this restriction.
7603           Diag(D.getIdentifierLoc(),
7604                getLangOpts().CPlusPlus11
7605                  ? diag::warn_cxx98_compat_static_data_member_in_union
7606                  : diag::ext_static_data_member_in_union) << Name;
7607         }
7608       }
7609     }
7610 
7611     // Match up the template parameter lists with the scope specifier, then
7612     // determine whether we have a template or a template specialization.
7613     bool InvalidScope = false;
7614     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7615         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7616         D.getCXXScopeSpec(),
7617         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7618             ? D.getName().TemplateId
7619             : nullptr,
7620         TemplateParamLists,
7621         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7622     Invalid |= InvalidScope;
7623 
7624     if (TemplateParams) {
7625       if (!TemplateParams->size() &&
7626           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7627         // There is an extraneous 'template<>' for this variable. Complain
7628         // about it, but allow the declaration of the variable.
7629         Diag(TemplateParams->getTemplateLoc(),
7630              diag::err_template_variable_noparams)
7631           << II
7632           << SourceRange(TemplateParams->getTemplateLoc(),
7633                          TemplateParams->getRAngleLoc());
7634         TemplateParams = nullptr;
7635       } else {
7636         // Check that we can declare a template here.
7637         if (CheckTemplateDeclScope(S, TemplateParams))
7638           return nullptr;
7639 
7640         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7641           // This is an explicit specialization or a partial specialization.
7642           IsVariableTemplateSpecialization = true;
7643           IsPartialSpecialization = TemplateParams->size() > 0;
7644         } else { // if (TemplateParams->size() > 0)
7645           // This is a template declaration.
7646           IsVariableTemplate = true;
7647 
7648           // Only C++1y supports variable templates (N3651).
7649           Diag(D.getIdentifierLoc(),
7650                getLangOpts().CPlusPlus14
7651                    ? diag::warn_cxx11_compat_variable_template
7652                    : diag::ext_variable_template);
7653         }
7654       }
7655     } else {
7656       // Check that we can declare a member specialization here.
7657       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7658           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7659         return nullptr;
7660       assert((Invalid ||
7661               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7662              "should have a 'template<>' for this decl");
7663     }
7664 
7665     if (IsVariableTemplateSpecialization) {
7666       SourceLocation TemplateKWLoc =
7667           TemplateParamLists.size() > 0
7668               ? TemplateParamLists[0]->getTemplateLoc()
7669               : SourceLocation();
7670       DeclResult Res = ActOnVarTemplateSpecialization(
7671           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7672           IsPartialSpecialization);
7673       if (Res.isInvalid())
7674         return nullptr;
7675       NewVD = cast<VarDecl>(Res.get());
7676       AddToScope = false;
7677     } else if (D.isDecompositionDeclarator()) {
7678       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7679                                         D.getIdentifierLoc(), R, TInfo, SC,
7680                                         Bindings);
7681     } else
7682       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7683                               D.getIdentifierLoc(), II, R, TInfo, SC);
7684 
7685     // If this is supposed to be a variable template, create it as such.
7686     if (IsVariableTemplate) {
7687       NewTemplate =
7688           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7689                                   TemplateParams, NewVD);
7690       NewVD->setDescribedVarTemplate(NewTemplate);
7691     }
7692 
7693     // If this decl has an auto type in need of deduction, make a note of the
7694     // Decl so we can diagnose uses of it in its own initializer.
7695     if (R->getContainedDeducedType())
7696       ParsingInitForAutoVars.insert(NewVD);
7697 
7698     if (D.isInvalidType() || Invalid) {
7699       NewVD->setInvalidDecl();
7700       if (NewTemplate)
7701         NewTemplate->setInvalidDecl();
7702     }
7703 
7704     SetNestedNameSpecifier(*this, NewVD, D);
7705 
7706     // If we have any template parameter lists that don't directly belong to
7707     // the variable (matching the scope specifier), store them.
7708     // An explicit variable template specialization does not own any template
7709     // parameter lists.
7710     bool IsExplicitSpecialization =
7711         IsVariableTemplateSpecialization && !IsPartialSpecialization;
7712     unsigned VDTemplateParamLists =
7713         (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7714     if (TemplateParamLists.size() > VDTemplateParamLists)
7715       NewVD->setTemplateParameterListsInfo(
7716           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7717   }
7718 
7719   if (D.getDeclSpec().isInlineSpecified()) {
7720     if (!getLangOpts().CPlusPlus) {
7721       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7722           << 0;
7723     } else if (CurContext->isFunctionOrMethod()) {
7724       // 'inline' is not allowed on block scope variable declaration.
7725       Diag(D.getDeclSpec().getInlineSpecLoc(),
7726            diag::err_inline_declaration_block_scope) << Name
7727         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7728     } else {
7729       Diag(D.getDeclSpec().getInlineSpecLoc(),
7730            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7731                                      : diag::ext_inline_variable);
7732       NewVD->setInlineSpecified();
7733     }
7734   }
7735 
7736   // Set the lexical context. If the declarator has a C++ scope specifier, the
7737   // lexical context will be different from the semantic context.
7738   NewVD->setLexicalDeclContext(CurContext);
7739   if (NewTemplate)
7740     NewTemplate->setLexicalDeclContext(CurContext);
7741 
7742   if (IsLocalExternDecl) {
7743     if (D.isDecompositionDeclarator())
7744       for (auto *B : Bindings)
7745         B->setLocalExternDecl();
7746     else
7747       NewVD->setLocalExternDecl();
7748   }
7749 
7750   bool EmitTLSUnsupportedError = false;
7751   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7752     // C++11 [dcl.stc]p4:
7753     //   When thread_local is applied to a variable of block scope the
7754     //   storage-class-specifier static is implied if it does not appear
7755     //   explicitly.
7756     // Core issue: 'static' is not implied if the variable is declared
7757     //   'extern'.
7758     if (NewVD->hasLocalStorage() &&
7759         (SCSpec != DeclSpec::SCS_unspecified ||
7760          TSCS != DeclSpec::TSCS_thread_local ||
7761          !DC->isFunctionOrMethod()))
7762       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7763            diag::err_thread_non_global)
7764         << DeclSpec::getSpecifierName(TSCS);
7765     else if (!Context.getTargetInfo().isTLSSupported()) {
7766       if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7767           getLangOpts().SYCLIsDevice) {
7768         // Postpone error emission until we've collected attributes required to
7769         // figure out whether it's a host or device variable and whether the
7770         // error should be ignored.
7771         EmitTLSUnsupportedError = true;
7772         // We still need to mark the variable as TLS so it shows up in AST with
7773         // proper storage class for other tools to use even if we're not going
7774         // to emit any code for it.
7775         NewVD->setTSCSpec(TSCS);
7776       } else
7777         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7778              diag::err_thread_unsupported);
7779     } else
7780       NewVD->setTSCSpec(TSCS);
7781   }
7782 
7783   switch (D.getDeclSpec().getConstexprSpecifier()) {
7784   case ConstexprSpecKind::Unspecified:
7785     break;
7786 
7787   case ConstexprSpecKind::Consteval:
7788     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7789          diag::err_constexpr_wrong_decl_kind)
7790         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7791     [[fallthrough]];
7792 
7793   case ConstexprSpecKind::Constexpr:
7794     NewVD->setConstexpr(true);
7795     // C++1z [dcl.spec.constexpr]p1:
7796     //   A static data member declared with the constexpr specifier is
7797     //   implicitly an inline variable.
7798     if (NewVD->isStaticDataMember() &&
7799         (getLangOpts().CPlusPlus17 ||
7800          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7801       NewVD->setImplicitlyInline();
7802     break;
7803 
7804   case ConstexprSpecKind::Constinit:
7805     if (!NewVD->hasGlobalStorage())
7806       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7807            diag::err_constinit_local_variable);
7808     else
7809       NewVD->addAttr(
7810           ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7811                                 ConstInitAttr::Keyword_constinit));
7812     break;
7813   }
7814 
7815   // C99 6.7.4p3
7816   //   An inline definition of a function with external linkage shall
7817   //   not contain a definition of a modifiable object with static or
7818   //   thread storage duration...
7819   // We only apply this when the function is required to be defined
7820   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7821   // that a local variable with thread storage duration still has to
7822   // be marked 'static'.  Also note that it's possible to get these
7823   // semantics in C++ using __attribute__((gnu_inline)).
7824   if (SC == SC_Static && S->getFnParent() != nullptr &&
7825       !NewVD->getType().isConstQualified()) {
7826     FunctionDecl *CurFD = getCurFunctionDecl();
7827     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7828       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7829            diag::warn_static_local_in_extern_inline);
7830       MaybeSuggestAddingStaticToDecl(CurFD);
7831     }
7832   }
7833 
7834   if (D.getDeclSpec().isModulePrivateSpecified()) {
7835     if (IsVariableTemplateSpecialization)
7836       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7837           << (IsPartialSpecialization ? 1 : 0)
7838           << FixItHint::CreateRemoval(
7839                  D.getDeclSpec().getModulePrivateSpecLoc());
7840     else if (IsMemberSpecialization)
7841       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7842         << 2
7843         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7844     else if (NewVD->hasLocalStorage())
7845       Diag(NewVD->getLocation(), diag::err_module_private_local)
7846           << 0 << NewVD
7847           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7848           << FixItHint::CreateRemoval(
7849                  D.getDeclSpec().getModulePrivateSpecLoc());
7850     else {
7851       NewVD->setModulePrivate();
7852       if (NewTemplate)
7853         NewTemplate->setModulePrivate();
7854       for (auto *B : Bindings)
7855         B->setModulePrivate();
7856     }
7857   }
7858 
7859   if (getLangOpts().OpenCL) {
7860     deduceOpenCLAddressSpace(NewVD);
7861 
7862     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7863     if (TSC != TSCS_unspecified) {
7864       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7865            diag::err_opencl_unknown_type_specifier)
7866           << getLangOpts().getOpenCLVersionString()
7867           << DeclSpec::getSpecifierName(TSC) << 1;
7868       NewVD->setInvalidDecl();
7869     }
7870   }
7871 
7872   // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7873   // address space if the table has local storage (semantic checks elsewhere
7874   // will produce an error anyway).
7875   if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7876     if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7877         !NewVD->hasLocalStorage()) {
7878       QualType Type = Context.getAddrSpaceQualType(
7879           NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7880       NewVD->setType(Type);
7881     }
7882   }
7883 
7884   // Handle attributes prior to checking for duplicates in MergeVarDecl
7885   ProcessDeclAttributes(S, NewVD, D);
7886 
7887   // FIXME: This is probably the wrong location to be doing this and we should
7888   // probably be doing this for more attributes (especially for function
7889   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7890   // the code to copy attributes would be generated by TableGen.
7891   if (R->isFunctionPointerType())
7892     if (const auto *TT = R->getAs<TypedefType>())
7893       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7894 
7895   if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7896       getLangOpts().SYCLIsDevice) {
7897     if (EmitTLSUnsupportedError &&
7898         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7899          (getLangOpts().OpenMPIsTargetDevice &&
7900           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7901       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7902            diag::err_thread_unsupported);
7903 
7904     if (EmitTLSUnsupportedError &&
7905         (LangOpts.SYCLIsDevice ||
7906          (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7907       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7908     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7909     // storage [duration]."
7910     if (SC == SC_None && S->getFnParent() != nullptr &&
7911         (NewVD->hasAttr<CUDASharedAttr>() ||
7912          NewVD->hasAttr<CUDAConstantAttr>())) {
7913       NewVD->setStorageClass(SC_Static);
7914     }
7915   }
7916 
7917   // Ensure that dllimport globals without explicit storage class are treated as
7918   // extern. The storage class is set above using parsed attributes. Now we can
7919   // check the VarDecl itself.
7920   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7921          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7922          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7923 
7924   // In auto-retain/release, infer strong retension for variables of
7925   // retainable type.
7926   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7927     NewVD->setInvalidDecl();
7928 
7929   // Handle GNU asm-label extension (encoded as an attribute).
7930   if (Expr *E = (Expr*)D.getAsmLabel()) {
7931     // The parser guarantees this is a string.
7932     StringLiteral *SE = cast<StringLiteral>(E);
7933     StringRef Label = SE->getString();
7934     if (S->getFnParent() != nullptr) {
7935       switch (SC) {
7936       case SC_None:
7937       case SC_Auto:
7938         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7939         break;
7940       case SC_Register:
7941         // Local Named register
7942         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7943             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7944           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7945         break;
7946       case SC_Static:
7947       case SC_Extern:
7948       case SC_PrivateExtern:
7949         break;
7950       }
7951     } else if (SC == SC_Register) {
7952       // Global Named register
7953       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7954         const auto &TI = Context.getTargetInfo();
7955         bool HasSizeMismatch;
7956 
7957         if (!TI.isValidGCCRegisterName(Label))
7958           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7959         else if (!TI.validateGlobalRegisterVariable(Label,
7960                                                     Context.getTypeSize(R),
7961                                                     HasSizeMismatch))
7962           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7963         else if (HasSizeMismatch)
7964           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7965       }
7966 
7967       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7968         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7969         NewVD->setInvalidDecl(true);
7970       }
7971     }
7972 
7973     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7974                                         /*IsLiteralLabel=*/true,
7975                                         SE->getStrTokenLoc(0)));
7976   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7977     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7978       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7979     if (I != ExtnameUndeclaredIdentifiers.end()) {
7980       if (isDeclExternC(NewVD)) {
7981         NewVD->addAttr(I->second);
7982         ExtnameUndeclaredIdentifiers.erase(I);
7983       } else
7984         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7985             << /*Variable*/1 << NewVD;
7986     }
7987   }
7988 
7989   // Find the shadowed declaration before filtering for scope.
7990   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7991                                 ? getShadowedDeclaration(NewVD, Previous)
7992                                 : nullptr;
7993 
7994   // Don't consider existing declarations that are in a different
7995   // scope and are out-of-semantic-context declarations (if the new
7996   // declaration has linkage).
7997   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7998                        D.getCXXScopeSpec().isNotEmpty() ||
7999                        IsMemberSpecialization ||
8000                        IsVariableTemplateSpecialization);
8001 
8002   // Check whether the previous declaration is in the same block scope. This
8003   // affects whether we merge types with it, per C++11 [dcl.array]p3.
8004   if (getLangOpts().CPlusPlus &&
8005       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8006     NewVD->setPreviousDeclInSameBlockScope(
8007         Previous.isSingleResult() && !Previous.isShadowed() &&
8008         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8009 
8010   if (!getLangOpts().CPlusPlus) {
8011     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8012   } else {
8013     // If this is an explicit specialization of a static data member, check it.
8014     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8015         CheckMemberSpecialization(NewVD, Previous))
8016       NewVD->setInvalidDecl();
8017 
8018     // Merge the decl with the existing one if appropriate.
8019     if (!Previous.empty()) {
8020       if (Previous.isSingleResult() &&
8021           isa<FieldDecl>(Previous.getFoundDecl()) &&
8022           D.getCXXScopeSpec().isSet()) {
8023         // The user tried to define a non-static data member
8024         // out-of-line (C++ [dcl.meaning]p1).
8025         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8026           << D.getCXXScopeSpec().getRange();
8027         Previous.clear();
8028         NewVD->setInvalidDecl();
8029       }
8030     } else if (D.getCXXScopeSpec().isSet()) {
8031       // No previous declaration in the qualifying scope.
8032       Diag(D.getIdentifierLoc(), diag::err_no_member)
8033         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8034         << D.getCXXScopeSpec().getRange();
8035       NewVD->setInvalidDecl();
8036     }
8037 
8038     if (!IsVariableTemplateSpecialization)
8039       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8040 
8041     // CheckVariableDeclaration will set NewVD as invalid if something is in
8042     // error like WebAssembly tables being declared as arrays with a non-zero
8043     // size, but then parsing continues and emits further errors on that line.
8044     // To avoid that we check here if it happened and return nullptr.
8045     if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8046       return nullptr;
8047 
8048     if (NewTemplate) {
8049       VarTemplateDecl *PrevVarTemplate =
8050           NewVD->getPreviousDecl()
8051               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8052               : nullptr;
8053 
8054       // Check the template parameter list of this declaration, possibly
8055       // merging in the template parameter list from the previous variable
8056       // template declaration.
8057       if (CheckTemplateParameterList(
8058               TemplateParams,
8059               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8060                               : nullptr,
8061               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8062                DC->isDependentContext())
8063                   ? TPC_ClassTemplateMember
8064                   : TPC_VarTemplate))
8065         NewVD->setInvalidDecl();
8066 
8067       // If we are providing an explicit specialization of a static variable
8068       // template, make a note of that.
8069       if (PrevVarTemplate &&
8070           PrevVarTemplate->getInstantiatedFromMemberTemplate())
8071         PrevVarTemplate->setMemberSpecialization();
8072     }
8073   }
8074 
8075   // Diagnose shadowed variables iff this isn't a redeclaration.
8076   if (ShadowedDecl && !D.isRedeclaration())
8077     CheckShadow(NewVD, ShadowedDecl, Previous);
8078 
8079   ProcessPragmaWeak(S, NewVD);
8080 
8081   // If this is the first declaration of an extern C variable, update
8082   // the map of such variables.
8083   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8084       isIncompleteDeclExternC(*this, NewVD))
8085     RegisterLocallyScopedExternCDecl(NewVD, S);
8086 
8087   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8088     MangleNumberingContext *MCtx;
8089     Decl *ManglingContextDecl;
8090     std::tie(MCtx, ManglingContextDecl) =
8091         getCurrentMangleNumberContext(NewVD->getDeclContext());
8092     if (MCtx) {
8093       Context.setManglingNumber(
8094           NewVD, MCtx->getManglingNumber(
8095                      NewVD, getMSManglingNumber(getLangOpts(), S)));
8096       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8097     }
8098   }
8099 
8100   // Special handling of variable named 'main'.
8101   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8102       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8103       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8104 
8105     // C++ [basic.start.main]p3
8106     // A program that declares a variable main at global scope is ill-formed.
8107     if (getLangOpts().CPlusPlus)
8108       Diag(D.getBeginLoc(), diag::err_main_global_variable);
8109 
8110     // In C, and external-linkage variable named main results in undefined
8111     // behavior.
8112     else if (NewVD->hasExternalFormalLinkage())
8113       Diag(D.getBeginLoc(), diag::warn_main_redefined);
8114   }
8115 
8116   if (D.isRedeclaration() && !Previous.empty()) {
8117     NamedDecl *Prev = Previous.getRepresentativeDecl();
8118     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8119                                    D.isFunctionDefinition());
8120   }
8121 
8122   if (NewTemplate) {
8123     if (NewVD->isInvalidDecl())
8124       NewTemplate->setInvalidDecl();
8125     ActOnDocumentableDecl(NewTemplate);
8126     return NewTemplate;
8127   }
8128 
8129   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8130     CompleteMemberSpecialization(NewVD, Previous);
8131 
8132   emitReadOnlyPlacementAttrWarning(*this, NewVD);
8133 
8134   return NewVD;
8135 }
8136 
8137 /// Enum describing the %select options in diag::warn_decl_shadow.
8138 enum ShadowedDeclKind {
8139   SDK_Local,
8140   SDK_Global,
8141   SDK_StaticMember,
8142   SDK_Field,
8143   SDK_Typedef,
8144   SDK_Using,
8145   SDK_StructuredBinding
8146 };
8147 
8148 /// Determine what kind of declaration we're shadowing.
8149 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8150                                                 const DeclContext *OldDC) {
8151   if (isa<TypeAliasDecl>(ShadowedDecl))
8152     return SDK_Using;
8153   else if (isa<TypedefDecl>(ShadowedDecl))
8154     return SDK_Typedef;
8155   else if (isa<BindingDecl>(ShadowedDecl))
8156     return SDK_StructuredBinding;
8157   else if (isa<RecordDecl>(OldDC))
8158     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8159 
8160   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8161 }
8162 
8163 /// Return the location of the capture if the given lambda captures the given
8164 /// variable \p VD, or an invalid source location otherwise.
8165 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8166                                          const VarDecl *VD) {
8167   for (const Capture &Capture : LSI->Captures) {
8168     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8169       return Capture.getLocation();
8170   }
8171   return SourceLocation();
8172 }
8173 
8174 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8175                                      const LookupResult &R) {
8176   // Only diagnose if we're shadowing an unambiguous field or variable.
8177   if (R.getResultKind() != LookupResult::Found)
8178     return false;
8179 
8180   // Return false if warning is ignored.
8181   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8182 }
8183 
8184 /// Return the declaration shadowed by the given variable \p D, or null
8185 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8186 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8187                                         const LookupResult &R) {
8188   if (!shouldWarnIfShadowedDecl(Diags, R))
8189     return nullptr;
8190 
8191   // Don't diagnose declarations at file scope.
8192   if (D->hasGlobalStorage() && !D->isStaticLocal())
8193     return nullptr;
8194 
8195   NamedDecl *ShadowedDecl = R.getFoundDecl();
8196   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8197                                                             : nullptr;
8198 }
8199 
8200 /// Return the declaration shadowed by the given typedef \p D, or null
8201 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8202 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8203                                         const LookupResult &R) {
8204   // Don't warn if typedef declaration is part of a class
8205   if (D->getDeclContext()->isRecord())
8206     return nullptr;
8207 
8208   if (!shouldWarnIfShadowedDecl(Diags, R))
8209     return nullptr;
8210 
8211   NamedDecl *ShadowedDecl = R.getFoundDecl();
8212   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8213 }
8214 
8215 /// Return the declaration shadowed by the given variable \p D, or null
8216 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8217 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8218                                         const LookupResult &R) {
8219   if (!shouldWarnIfShadowedDecl(Diags, R))
8220     return nullptr;
8221 
8222   NamedDecl *ShadowedDecl = R.getFoundDecl();
8223   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8224                                                             : nullptr;
8225 }
8226 
8227 /// Diagnose variable or built-in function shadowing.  Implements
8228 /// -Wshadow.
8229 ///
8230 /// This method is called whenever a VarDecl is added to a "useful"
8231 /// scope.
8232 ///
8233 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8234 /// \param R the lookup of the name
8235 ///
8236 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8237                        const LookupResult &R) {
8238   DeclContext *NewDC = D->getDeclContext();
8239 
8240   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8241     // Fields are not shadowed by variables in C++ static methods.
8242     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8243       if (MD->isStatic())
8244         return;
8245 
8246     // Fields shadowed by constructor parameters are a special case. Usually
8247     // the constructor initializes the field with the parameter.
8248     if (isa<CXXConstructorDecl>(NewDC))
8249       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8250         // Remember that this was shadowed so we can either warn about its
8251         // modification or its existence depending on warning settings.
8252         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8253         return;
8254       }
8255   }
8256 
8257   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8258     if (shadowedVar->isExternC()) {
8259       // For shadowing external vars, make sure that we point to the global
8260       // declaration, not a locally scoped extern declaration.
8261       for (auto *I : shadowedVar->redecls())
8262         if (I->isFileVarDecl()) {
8263           ShadowedDecl = I;
8264           break;
8265         }
8266     }
8267 
8268   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8269 
8270   unsigned WarningDiag = diag::warn_decl_shadow;
8271   SourceLocation CaptureLoc;
8272   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8273       isa<CXXMethodDecl>(NewDC)) {
8274     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8275       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8276         if (RD->getLambdaCaptureDefault() == LCD_None) {
8277           // Try to avoid warnings for lambdas with an explicit capture list.
8278           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8279           // Warn only when the lambda captures the shadowed decl explicitly.
8280           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8281           if (CaptureLoc.isInvalid())
8282             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8283         } else {
8284           // Remember that this was shadowed so we can avoid the warning if the
8285           // shadowed decl isn't captured and the warning settings allow it.
8286           cast<LambdaScopeInfo>(getCurFunction())
8287               ->ShadowingDecls.push_back(
8288                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8289           return;
8290         }
8291       }
8292 
8293       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8294         // A variable can't shadow a local variable in an enclosing scope, if
8295         // they are separated by a non-capturing declaration context.
8296         for (DeclContext *ParentDC = NewDC;
8297              ParentDC && !ParentDC->Equals(OldDC);
8298              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8299           // Only block literals, captured statements, and lambda expressions
8300           // can capture; other scopes don't.
8301           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8302               !isLambdaCallOperator(ParentDC)) {
8303             return;
8304           }
8305         }
8306       }
8307     }
8308   }
8309 
8310   // Only warn about certain kinds of shadowing for class members.
8311   if (NewDC && NewDC->isRecord()) {
8312     // In particular, don't warn about shadowing non-class members.
8313     if (!OldDC->isRecord())
8314       return;
8315 
8316     // TODO: should we warn about static data members shadowing
8317     // static data members from base classes?
8318 
8319     // TODO: don't diagnose for inaccessible shadowed members.
8320     // This is hard to do perfectly because we might friend the
8321     // shadowing context, but that's just a false negative.
8322   }
8323 
8324 
8325   DeclarationName Name = R.getLookupName();
8326 
8327   // Emit warning and note.
8328   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8329   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8330   if (!CaptureLoc.isInvalid())
8331     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8332         << Name << /*explicitly*/ 1;
8333   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8334 }
8335 
8336 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8337 /// when these variables are captured by the lambda.
8338 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8339   for (const auto &Shadow : LSI->ShadowingDecls) {
8340     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8341     // Try to avoid the warning when the shadowed decl isn't captured.
8342     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8343     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8344     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8345                                        ? diag::warn_decl_shadow_uncaptured_local
8346                                        : diag::warn_decl_shadow)
8347         << Shadow.VD->getDeclName()
8348         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8349     if (!CaptureLoc.isInvalid())
8350       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8351           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8352     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8353   }
8354 }
8355 
8356 /// Check -Wshadow without the advantage of a previous lookup.
8357 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8358   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8359     return;
8360 
8361   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8362                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8363   LookupName(R, S);
8364   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8365     CheckShadow(D, ShadowedDecl, R);
8366 }
8367 
8368 /// Check if 'E', which is an expression that is about to be modified, refers
8369 /// to a constructor parameter that shadows a field.
8370 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8371   // Quickly ignore expressions that can't be shadowing ctor parameters.
8372   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8373     return;
8374   E = E->IgnoreParenImpCasts();
8375   auto *DRE = dyn_cast<DeclRefExpr>(E);
8376   if (!DRE)
8377     return;
8378   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8379   auto I = ShadowingDecls.find(D);
8380   if (I == ShadowingDecls.end())
8381     return;
8382   const NamedDecl *ShadowedDecl = I->second;
8383   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8384   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8385   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8386   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8387 
8388   // Avoid issuing multiple warnings about the same decl.
8389   ShadowingDecls.erase(I);
8390 }
8391 
8392 /// Check for conflict between this global or extern "C" declaration and
8393 /// previous global or extern "C" declarations. This is only used in C++.
8394 template<typename T>
8395 static bool checkGlobalOrExternCConflict(
8396     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8397   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8398   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8399 
8400   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8401     // The common case: this global doesn't conflict with any extern "C"
8402     // declaration.
8403     return false;
8404   }
8405 
8406   if (Prev) {
8407     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8408       // Both the old and new declarations have C language linkage. This is a
8409       // redeclaration.
8410       Previous.clear();
8411       Previous.addDecl(Prev);
8412       return true;
8413     }
8414 
8415     // This is a global, non-extern "C" declaration, and there is a previous
8416     // non-global extern "C" declaration. Diagnose if this is a variable
8417     // declaration.
8418     if (!isa<VarDecl>(ND))
8419       return false;
8420   } else {
8421     // The declaration is extern "C". Check for any declaration in the
8422     // translation unit which might conflict.
8423     if (IsGlobal) {
8424       // We have already performed the lookup into the translation unit.
8425       IsGlobal = false;
8426       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8427            I != E; ++I) {
8428         if (isa<VarDecl>(*I)) {
8429           Prev = *I;
8430           break;
8431         }
8432       }
8433     } else {
8434       DeclContext::lookup_result R =
8435           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8436       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8437            I != E; ++I) {
8438         if (isa<VarDecl>(*I)) {
8439           Prev = *I;
8440           break;
8441         }
8442         // FIXME: If we have any other entity with this name in global scope,
8443         // the declaration is ill-formed, but that is a defect: it breaks the
8444         // 'stat' hack, for instance. Only variables can have mangled name
8445         // clashes with extern "C" declarations, so only they deserve a
8446         // diagnostic.
8447       }
8448     }
8449 
8450     if (!Prev)
8451       return false;
8452   }
8453 
8454   // Use the first declaration's location to ensure we point at something which
8455   // is lexically inside an extern "C" linkage-spec.
8456   assert(Prev && "should have found a previous declaration to diagnose");
8457   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8458     Prev = FD->getFirstDecl();
8459   else
8460     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8461 
8462   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8463     << IsGlobal << ND;
8464   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8465     << IsGlobal;
8466   return false;
8467 }
8468 
8469 /// Apply special rules for handling extern "C" declarations. Returns \c true
8470 /// if we have found that this is a redeclaration of some prior entity.
8471 ///
8472 /// Per C++ [dcl.link]p6:
8473 ///   Two declarations [for a function or variable] with C language linkage
8474 ///   with the same name that appear in different scopes refer to the same
8475 ///   [entity]. An entity with C language linkage shall not be declared with
8476 ///   the same name as an entity in global scope.
8477 template<typename T>
8478 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8479                                                   LookupResult &Previous) {
8480   if (!S.getLangOpts().CPlusPlus) {
8481     // In C, when declaring a global variable, look for a corresponding 'extern'
8482     // variable declared in function scope. We don't need this in C++, because
8483     // we find local extern decls in the surrounding file-scope DeclContext.
8484     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8485       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8486         Previous.clear();
8487         Previous.addDecl(Prev);
8488         return true;
8489       }
8490     }
8491     return false;
8492   }
8493 
8494   // A declaration in the translation unit can conflict with an extern "C"
8495   // declaration.
8496   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8497     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8498 
8499   // An extern "C" declaration can conflict with a declaration in the
8500   // translation unit or can be a redeclaration of an extern "C" declaration
8501   // in another scope.
8502   if (isIncompleteDeclExternC(S,ND))
8503     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8504 
8505   // Neither global nor extern "C": nothing to do.
8506   return false;
8507 }
8508 
8509 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8510   // If the decl is already known invalid, don't check it.
8511   if (NewVD->isInvalidDecl())
8512     return;
8513 
8514   QualType T = NewVD->getType();
8515 
8516   // Defer checking an 'auto' type until its initializer is attached.
8517   if (T->isUndeducedType())
8518     return;
8519 
8520   if (NewVD->hasAttrs())
8521     CheckAlignasUnderalignment(NewVD);
8522 
8523   if (T->isObjCObjectType()) {
8524     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8525       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8526     T = Context.getObjCObjectPointerType(T);
8527     NewVD->setType(T);
8528   }
8529 
8530   // Emit an error if an address space was applied to decl with local storage.
8531   // This includes arrays of objects with address space qualifiers, but not
8532   // automatic variables that point to other address spaces.
8533   // ISO/IEC TR 18037 S5.1.2
8534   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8535       T.getAddressSpace() != LangAS::Default) {
8536     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8537     NewVD->setInvalidDecl();
8538     return;
8539   }
8540 
8541   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8542   // scope.
8543   if (getLangOpts().OpenCLVersion == 120 &&
8544       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8545                                             getLangOpts()) &&
8546       NewVD->isStaticLocal()) {
8547     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8548     NewVD->setInvalidDecl();
8549     return;
8550   }
8551 
8552   if (getLangOpts().OpenCL) {
8553     if (!diagnoseOpenCLTypes(*this, NewVD))
8554       return;
8555 
8556     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8557     if (NewVD->hasAttr<BlocksAttr>()) {
8558       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8559       return;
8560     }
8561 
8562     if (T->isBlockPointerType()) {
8563       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8564       // can't use 'extern' storage class.
8565       if (!T.isConstQualified()) {
8566         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8567             << 0 /*const*/;
8568         NewVD->setInvalidDecl();
8569         return;
8570       }
8571       if (NewVD->hasExternalStorage()) {
8572         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8573         NewVD->setInvalidDecl();
8574         return;
8575       }
8576     }
8577 
8578     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8579     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8580         NewVD->hasExternalStorage()) {
8581       if (!T->isSamplerT() && !T->isDependentType() &&
8582           !(T.getAddressSpace() == LangAS::opencl_constant ||
8583             (T.getAddressSpace() == LangAS::opencl_global &&
8584              getOpenCLOptions().areProgramScopeVariablesSupported(
8585                  getLangOpts())))) {
8586         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8587         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8588           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8589               << Scope << "global or constant";
8590         else
8591           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8592               << Scope << "constant";
8593         NewVD->setInvalidDecl();
8594         return;
8595       }
8596     } else {
8597       if (T.getAddressSpace() == LangAS::opencl_global) {
8598         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8599             << 1 /*is any function*/ << "global";
8600         NewVD->setInvalidDecl();
8601         return;
8602       }
8603       if (T.getAddressSpace() == LangAS::opencl_constant ||
8604           T.getAddressSpace() == LangAS::opencl_local) {
8605         FunctionDecl *FD = getCurFunctionDecl();
8606         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8607         // in functions.
8608         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8609           if (T.getAddressSpace() == LangAS::opencl_constant)
8610             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8611                 << 0 /*non-kernel only*/ << "constant";
8612           else
8613             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8614                 << 0 /*non-kernel only*/ << "local";
8615           NewVD->setInvalidDecl();
8616           return;
8617         }
8618         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8619         // in the outermost scope of a kernel function.
8620         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8621           if (!getCurScope()->isFunctionScope()) {
8622             if (T.getAddressSpace() == LangAS::opencl_constant)
8623               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8624                   << "constant";
8625             else
8626               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8627                   << "local";
8628             NewVD->setInvalidDecl();
8629             return;
8630           }
8631         }
8632       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8633                  // If we are parsing a template we didn't deduce an addr
8634                  // space yet.
8635                  T.getAddressSpace() != LangAS::Default) {
8636         // Do not allow other address spaces on automatic variable.
8637         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8638         NewVD->setInvalidDecl();
8639         return;
8640       }
8641     }
8642   }
8643 
8644   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8645       && !NewVD->hasAttr<BlocksAttr>()) {
8646     if (getLangOpts().getGC() != LangOptions::NonGC)
8647       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8648     else {
8649       assert(!getLangOpts().ObjCAutoRefCount);
8650       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8651     }
8652   }
8653 
8654   // WebAssembly tables must be static with a zero length and can't be
8655   // declared within functions.
8656   if (T->isWebAssemblyTableType()) {
8657     if (getCurScope()->getParent()) { // Parent is null at top-level
8658       Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8659       NewVD->setInvalidDecl();
8660       return;
8661     }
8662     if (NewVD->getStorageClass() != SC_Static) {
8663       Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8664       NewVD->setInvalidDecl();
8665       return;
8666     }
8667     const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8668     if (!ATy || ATy->getSize().getSExtValue() != 0) {
8669       Diag(NewVD->getLocation(),
8670            diag::err_typecheck_wasm_table_must_have_zero_length);
8671       NewVD->setInvalidDecl();
8672       return;
8673     }
8674   }
8675 
8676   bool isVM = T->isVariablyModifiedType();
8677   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8678       NewVD->hasAttr<BlocksAttr>())
8679     setFunctionHasBranchProtectedScope();
8680 
8681   if ((isVM && NewVD->hasLinkage()) ||
8682       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8683     bool SizeIsNegative;
8684     llvm::APSInt Oversized;
8685     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8686         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8687     QualType FixedT;
8688     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8689       FixedT = FixedTInfo->getType();
8690     else if (FixedTInfo) {
8691       // Type and type-as-written are canonically different. We need to fix up
8692       // both types separately.
8693       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8694                                                    Oversized);
8695     }
8696     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8697       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8698       // FIXME: This won't give the correct result for
8699       // int a[10][n];
8700       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8701 
8702       if (NewVD->isFileVarDecl())
8703         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8704         << SizeRange;
8705       else if (NewVD->isStaticLocal())
8706         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8707         << SizeRange;
8708       else
8709         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8710         << SizeRange;
8711       NewVD->setInvalidDecl();
8712       return;
8713     }
8714 
8715     if (!FixedTInfo) {
8716       if (NewVD->isFileVarDecl())
8717         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8718       else
8719         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8720       NewVD->setInvalidDecl();
8721       return;
8722     }
8723 
8724     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8725     NewVD->setType(FixedT);
8726     NewVD->setTypeSourceInfo(FixedTInfo);
8727   }
8728 
8729   if (T->isVoidType()) {
8730     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8731     //                    of objects and functions.
8732     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8733       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8734         << T;
8735       NewVD->setInvalidDecl();
8736       return;
8737     }
8738   }
8739 
8740   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8741     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8742     NewVD->setInvalidDecl();
8743     return;
8744   }
8745 
8746   if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8747       !T.isWebAssemblyReferenceType()) {
8748     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8749     NewVD->setInvalidDecl();
8750     return;
8751   }
8752 
8753   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8754     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8755     NewVD->setInvalidDecl();
8756     return;
8757   }
8758 
8759   if (NewVD->isConstexpr() && !T->isDependentType() &&
8760       RequireLiteralType(NewVD->getLocation(), T,
8761                          diag::err_constexpr_var_non_literal)) {
8762     NewVD->setInvalidDecl();
8763     return;
8764   }
8765 
8766   // PPC MMA non-pointer types are not allowed as non-local variable types.
8767   if (Context.getTargetInfo().getTriple().isPPC64() &&
8768       !NewVD->isLocalVarDecl() &&
8769       CheckPPCMMAType(T, NewVD->getLocation())) {
8770     NewVD->setInvalidDecl();
8771     return;
8772   }
8773 
8774   // Check that SVE types are only used in functions with SVE available.
8775   if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8776     const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8777     llvm::StringMap<bool> CallerFeatureMap;
8778     Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8779     if (!Builtin::evaluateRequiredTargetFeatures(
8780         "sve", CallerFeatureMap)) {
8781       Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8782       NewVD->setInvalidDecl();
8783       return;
8784     }
8785   }
8786 
8787   if (T->isRVVType())
8788     checkRVVTypeSupport(T, NewVD->getLocation(), cast<ValueDecl>(CurContext));
8789 }
8790 
8791 /// Perform semantic checking on a newly-created variable
8792 /// declaration.
8793 ///
8794 /// This routine performs all of the type-checking required for a
8795 /// variable declaration once it has been built. It is used both to
8796 /// check variables after they have been parsed and their declarators
8797 /// have been translated into a declaration, and to check variables
8798 /// that have been instantiated from a template.
8799 ///
8800 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8801 ///
8802 /// Returns true if the variable declaration is a redeclaration.
8803 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8804   CheckVariableDeclarationType(NewVD);
8805 
8806   // If the decl is already known invalid, don't check it.
8807   if (NewVD->isInvalidDecl())
8808     return false;
8809 
8810   // If we did not find anything by this name, look for a non-visible
8811   // extern "C" declaration with the same name.
8812   if (Previous.empty() &&
8813       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8814     Previous.setShadowed();
8815 
8816   if (!Previous.empty()) {
8817     MergeVarDecl(NewVD, Previous);
8818     return true;
8819   }
8820   return false;
8821 }
8822 
8823 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8824 /// and if so, check that it's a valid override and remember it.
8825 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8826   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8827 
8828   // Look for methods in base classes that this method might override.
8829   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8830                      /*DetectVirtual=*/false);
8831   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8832     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8833     DeclarationName Name = MD->getDeclName();
8834 
8835     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8836       // We really want to find the base class destructor here.
8837       QualType T = Context.getTypeDeclType(BaseRecord);
8838       CanQualType CT = Context.getCanonicalType(T);
8839       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8840     }
8841 
8842     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8843       CXXMethodDecl *BaseMD =
8844           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8845       if (!BaseMD || !BaseMD->isVirtual() ||
8846           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8847                      /*ConsiderCudaAttrs=*/true,
8848                      // C++2a [class.virtual]p2 does not consider requires
8849                      // clauses when overriding.
8850                      /*ConsiderRequiresClauses=*/false))
8851         continue;
8852 
8853       if (Overridden.insert(BaseMD).second) {
8854         MD->addOverriddenMethod(BaseMD);
8855         CheckOverridingFunctionReturnType(MD, BaseMD);
8856         CheckOverridingFunctionAttributes(MD, BaseMD);
8857         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8858         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8859       }
8860 
8861       // A method can only override one function from each base class. We
8862       // don't track indirectly overridden methods from bases of bases.
8863       return true;
8864     }
8865 
8866     return false;
8867   };
8868 
8869   DC->lookupInBases(VisitBase, Paths);
8870   return !Overridden.empty();
8871 }
8872 
8873 namespace {
8874   // Struct for holding all of the extra arguments needed by
8875   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8876   struct ActOnFDArgs {
8877     Scope *S;
8878     Declarator &D;
8879     MultiTemplateParamsArg TemplateParamLists;
8880     bool AddToScope;
8881   };
8882 } // end anonymous namespace
8883 
8884 namespace {
8885 
8886 // Callback to only accept typo corrections that have a non-zero edit distance.
8887 // Also only accept corrections that have the same parent decl.
8888 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8889  public:
8890   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8891                             CXXRecordDecl *Parent)
8892       : Context(Context), OriginalFD(TypoFD),
8893         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8894 
8895   bool ValidateCandidate(const TypoCorrection &candidate) override {
8896     if (candidate.getEditDistance() == 0)
8897       return false;
8898 
8899     SmallVector<unsigned, 1> MismatchedParams;
8900     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8901                                           CDeclEnd = candidate.end();
8902          CDecl != CDeclEnd; ++CDecl) {
8903       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8904 
8905       if (FD && !FD->hasBody() &&
8906           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8907         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8908           CXXRecordDecl *Parent = MD->getParent();
8909           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8910             return true;
8911         } else if (!ExpectedParent) {
8912           return true;
8913         }
8914       }
8915     }
8916 
8917     return false;
8918   }
8919 
8920   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8921     return std::make_unique<DifferentNameValidatorCCC>(*this);
8922   }
8923 
8924  private:
8925   ASTContext &Context;
8926   FunctionDecl *OriginalFD;
8927   CXXRecordDecl *ExpectedParent;
8928 };
8929 
8930 } // end anonymous namespace
8931 
8932 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8933   TypoCorrectedFunctionDefinitions.insert(F);
8934 }
8935 
8936 /// Generate diagnostics for an invalid function redeclaration.
8937 ///
8938 /// This routine handles generating the diagnostic messages for an invalid
8939 /// function redeclaration, including finding possible similar declarations
8940 /// or performing typo correction if there are no previous declarations with
8941 /// the same name.
8942 ///
8943 /// Returns a NamedDecl iff typo correction was performed and substituting in
8944 /// the new declaration name does not cause new errors.
8945 static NamedDecl *DiagnoseInvalidRedeclaration(
8946     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8947     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8948   DeclarationName Name = NewFD->getDeclName();
8949   DeclContext *NewDC = NewFD->getDeclContext();
8950   SmallVector<unsigned, 1> MismatchedParams;
8951   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8952   TypoCorrection Correction;
8953   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8954   unsigned DiagMsg =
8955     IsLocalFriend ? diag::err_no_matching_local_friend :
8956     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8957     diag::err_member_decl_does_not_match;
8958   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8959                     IsLocalFriend ? Sema::LookupLocalFriendName
8960                                   : Sema::LookupOrdinaryName,
8961                     Sema::ForVisibleRedeclaration);
8962 
8963   NewFD->setInvalidDecl();
8964   if (IsLocalFriend)
8965     SemaRef.LookupName(Prev, S);
8966   else
8967     SemaRef.LookupQualifiedName(Prev, NewDC);
8968   assert(!Prev.isAmbiguous() &&
8969          "Cannot have an ambiguity in previous-declaration lookup");
8970   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8971   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8972                                 MD ? MD->getParent() : nullptr);
8973   if (!Prev.empty()) {
8974     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8975          Func != FuncEnd; ++Func) {
8976       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8977       if (FD &&
8978           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8979         // Add 1 to the index so that 0 can mean the mismatch didn't
8980         // involve a parameter
8981         unsigned ParamNum =
8982             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8983         NearMatches.push_back(std::make_pair(FD, ParamNum));
8984       }
8985     }
8986   // If the qualified name lookup yielded nothing, try typo correction
8987   } else if ((Correction = SemaRef.CorrectTypo(
8988                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8989                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8990                   IsLocalFriend ? nullptr : NewDC))) {
8991     // Set up everything for the call to ActOnFunctionDeclarator
8992     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8993                               ExtraArgs.D.getIdentifierLoc());
8994     Previous.clear();
8995     Previous.setLookupName(Correction.getCorrection());
8996     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8997                                     CDeclEnd = Correction.end();
8998          CDecl != CDeclEnd; ++CDecl) {
8999       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9000       if (FD && !FD->hasBody() &&
9001           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9002         Previous.addDecl(FD);
9003       }
9004     }
9005     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9006 
9007     NamedDecl *Result;
9008     // Retry building the function declaration with the new previous
9009     // declarations, and with errors suppressed.
9010     {
9011       // Trap errors.
9012       Sema::SFINAETrap Trap(SemaRef);
9013 
9014       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9015       // pieces need to verify the typo-corrected C++ declaration and hopefully
9016       // eliminate the need for the parameter pack ExtraArgs.
9017       Result = SemaRef.ActOnFunctionDeclarator(
9018           ExtraArgs.S, ExtraArgs.D,
9019           Correction.getCorrectionDecl()->getDeclContext(),
9020           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9021           ExtraArgs.AddToScope);
9022 
9023       if (Trap.hasErrorOccurred())
9024         Result = nullptr;
9025     }
9026 
9027     if (Result) {
9028       // Determine which correction we picked.
9029       Decl *Canonical = Result->getCanonicalDecl();
9030       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9031            I != E; ++I)
9032         if ((*I)->getCanonicalDecl() == Canonical)
9033           Correction.setCorrectionDecl(*I);
9034 
9035       // Let Sema know about the correction.
9036       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9037       SemaRef.diagnoseTypo(
9038           Correction,
9039           SemaRef.PDiag(IsLocalFriend
9040                           ? diag::err_no_matching_local_friend_suggest
9041                           : diag::err_member_decl_does_not_match_suggest)
9042             << Name << NewDC << IsDefinition);
9043       return Result;
9044     }
9045 
9046     // Pretend the typo correction never occurred
9047     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9048                               ExtraArgs.D.getIdentifierLoc());
9049     ExtraArgs.D.setRedeclaration(wasRedeclaration);
9050     Previous.clear();
9051     Previous.setLookupName(Name);
9052   }
9053 
9054   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9055       << Name << NewDC << IsDefinition << NewFD->getLocation();
9056 
9057   bool NewFDisConst = false;
9058   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9059     NewFDisConst = NewMD->isConst();
9060 
9061   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9062        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9063        NearMatch != NearMatchEnd; ++NearMatch) {
9064     FunctionDecl *FD = NearMatch->first;
9065     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9066     bool FDisConst = MD && MD->isConst();
9067     bool IsMember = MD || !IsLocalFriend;
9068 
9069     // FIXME: These notes are poorly worded for the local friend case.
9070     if (unsigned Idx = NearMatch->second) {
9071       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9072       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9073       if (Loc.isInvalid()) Loc = FD->getLocation();
9074       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9075                                  : diag::note_local_decl_close_param_match)
9076         << Idx << FDParam->getType()
9077         << NewFD->getParamDecl(Idx - 1)->getType();
9078     } else if (FDisConst != NewFDisConst) {
9079       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9080           << NewFDisConst << FD->getSourceRange().getEnd()
9081           << (NewFDisConst
9082                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9083                                                  .getConstQualifierLoc())
9084                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9085                                                    .getRParenLoc()
9086                                                    .getLocWithOffset(1),
9087                                                " const"));
9088     } else
9089       SemaRef.Diag(FD->getLocation(),
9090                    IsMember ? diag::note_member_def_close_match
9091                             : diag::note_local_decl_close_match);
9092   }
9093   return nullptr;
9094 }
9095 
9096 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9097   switch (D.getDeclSpec().getStorageClassSpec()) {
9098   default: llvm_unreachable("Unknown storage class!");
9099   case DeclSpec::SCS_auto:
9100   case DeclSpec::SCS_register:
9101   case DeclSpec::SCS_mutable:
9102     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9103                  diag::err_typecheck_sclass_func);
9104     D.getMutableDeclSpec().ClearStorageClassSpecs();
9105     D.setInvalidType();
9106     break;
9107   case DeclSpec::SCS_unspecified: break;
9108   case DeclSpec::SCS_extern:
9109     if (D.getDeclSpec().isExternInLinkageSpec())
9110       return SC_None;
9111     return SC_Extern;
9112   case DeclSpec::SCS_static: {
9113     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9114       // C99 6.7.1p5:
9115       //   The declaration of an identifier for a function that has
9116       //   block scope shall have no explicit storage-class specifier
9117       //   other than extern
9118       // See also (C++ [dcl.stc]p4).
9119       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9120                    diag::err_static_block_func);
9121       break;
9122     } else
9123       return SC_Static;
9124   }
9125   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9126   }
9127 
9128   // No explicit storage class has already been returned
9129   return SC_None;
9130 }
9131 
9132 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9133                                            DeclContext *DC, QualType &R,
9134                                            TypeSourceInfo *TInfo,
9135                                            StorageClass SC,
9136                                            bool &IsVirtualOkay) {
9137   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9138   DeclarationName Name = NameInfo.getName();
9139 
9140   FunctionDecl *NewFD = nullptr;
9141   bool isInline = D.getDeclSpec().isInlineSpecified();
9142 
9143   if (!SemaRef.getLangOpts().CPlusPlus) {
9144     // Determine whether the function was written with a prototype. This is
9145     // true when:
9146     //   - there is a prototype in the declarator, or
9147     //   - the type R of the function is some kind of typedef or other non-
9148     //     attributed reference to a type name (which eventually refers to a
9149     //     function type). Note, we can't always look at the adjusted type to
9150     //     check this case because attributes may cause a non-function
9151     //     declarator to still have a function type. e.g.,
9152     //       typedef void func(int a);
9153     //       __attribute__((noreturn)) func other_func; // This has a prototype
9154     bool HasPrototype =
9155         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9156         (D.getDeclSpec().isTypeRep() &&
9157          SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9158              ->isFunctionProtoType()) ||
9159         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9160     assert(
9161         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9162         "Strict prototypes are required");
9163 
9164     NewFD = FunctionDecl::Create(
9165         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9166         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9167         ConstexprSpecKind::Unspecified,
9168         /*TrailingRequiresClause=*/nullptr);
9169     if (D.isInvalidType())
9170       NewFD->setInvalidDecl();
9171 
9172     return NewFD;
9173   }
9174 
9175   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9176 
9177   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9178   if (ConstexprKind == ConstexprSpecKind::Constinit) {
9179     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9180                  diag::err_constexpr_wrong_decl_kind)
9181         << static_cast<int>(ConstexprKind);
9182     ConstexprKind = ConstexprSpecKind::Unspecified;
9183     D.getMutableDeclSpec().ClearConstexprSpec();
9184   }
9185   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9186 
9187   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9188     // This is a C++ constructor declaration.
9189     assert(DC->isRecord() &&
9190            "Constructors can only be declared in a member context");
9191 
9192     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9193     return CXXConstructorDecl::Create(
9194         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9195         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9196         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9197         InheritedConstructor(), TrailingRequiresClause);
9198 
9199   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9200     // This is a C++ destructor declaration.
9201     if (DC->isRecord()) {
9202       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9203       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9204       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9205           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9206           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9207           /*isImplicitlyDeclared=*/false, ConstexprKind,
9208           TrailingRequiresClause);
9209       // User defined destructors start as not selected if the class definition is still
9210       // not done.
9211       if (Record->isBeingDefined())
9212         NewDD->setIneligibleOrNotSelected(true);
9213 
9214       // If the destructor needs an implicit exception specification, set it
9215       // now. FIXME: It'd be nice to be able to create the right type to start
9216       // with, but the type needs to reference the destructor declaration.
9217       if (SemaRef.getLangOpts().CPlusPlus11)
9218         SemaRef.AdjustDestructorExceptionSpec(NewDD);
9219 
9220       IsVirtualOkay = true;
9221       return NewDD;
9222 
9223     } else {
9224       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9225       D.setInvalidType();
9226 
9227       // Create a FunctionDecl to satisfy the function definition parsing
9228       // code path.
9229       return FunctionDecl::Create(
9230           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9231           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9232           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9233     }
9234 
9235   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9236     if (!DC->isRecord()) {
9237       SemaRef.Diag(D.getIdentifierLoc(),
9238            diag::err_conv_function_not_member);
9239       return nullptr;
9240     }
9241 
9242     SemaRef.CheckConversionDeclarator(D, R, SC);
9243     if (D.isInvalidType())
9244       return nullptr;
9245 
9246     IsVirtualOkay = true;
9247     return CXXConversionDecl::Create(
9248         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9249         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9250         ExplicitSpecifier, ConstexprKind, SourceLocation(),
9251         TrailingRequiresClause);
9252 
9253   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9254     if (TrailingRequiresClause)
9255       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9256                    diag::err_trailing_requires_clause_on_deduction_guide)
9257           << TrailingRequiresClause->getSourceRange();
9258     if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9259       return nullptr;
9260     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9261                                          ExplicitSpecifier, NameInfo, R, TInfo,
9262                                          D.getEndLoc());
9263   } else if (DC->isRecord()) {
9264     // If the name of the function is the same as the name of the record,
9265     // then this must be an invalid constructor that has a return type.
9266     // (The parser checks for a return type and makes the declarator a
9267     // constructor if it has no return type).
9268     if (Name.getAsIdentifierInfo() &&
9269         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9270       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9271         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9272         << SourceRange(D.getIdentifierLoc());
9273       return nullptr;
9274     }
9275 
9276     // This is a C++ method declaration.
9277     CXXMethodDecl *Ret = CXXMethodDecl::Create(
9278         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9279         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9280         ConstexprKind, SourceLocation(), TrailingRequiresClause);
9281     IsVirtualOkay = !Ret->isStatic();
9282     return Ret;
9283   } else {
9284     bool isFriend =
9285         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9286     if (!isFriend && SemaRef.CurContext->isRecord())
9287       return nullptr;
9288 
9289     // Determine whether the function was written with a
9290     // prototype. This true when:
9291     //   - we're in C++ (where every function has a prototype),
9292     return FunctionDecl::Create(
9293         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9294         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9295         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9296   }
9297 }
9298 
9299 enum OpenCLParamType {
9300   ValidKernelParam,
9301   PtrPtrKernelParam,
9302   PtrKernelParam,
9303   InvalidAddrSpacePtrKernelParam,
9304   InvalidKernelParam,
9305   RecordKernelParam
9306 };
9307 
9308 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9309   // Size dependent types are just typedefs to normal integer types
9310   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9311   // integers other than by their names.
9312   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9313 
9314   // Remove typedefs one by one until we reach a typedef
9315   // for a size dependent type.
9316   QualType DesugaredTy = Ty;
9317   do {
9318     ArrayRef<StringRef> Names(SizeTypeNames);
9319     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9320     if (Names.end() != Match)
9321       return true;
9322 
9323     Ty = DesugaredTy;
9324     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9325   } while (DesugaredTy != Ty);
9326 
9327   return false;
9328 }
9329 
9330 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9331   if (PT->isDependentType())
9332     return InvalidKernelParam;
9333 
9334   if (PT->isPointerType() || PT->isReferenceType()) {
9335     QualType PointeeType = PT->getPointeeType();
9336     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9337         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9338         PointeeType.getAddressSpace() == LangAS::Default)
9339       return InvalidAddrSpacePtrKernelParam;
9340 
9341     if (PointeeType->isPointerType()) {
9342       // This is a pointer to pointer parameter.
9343       // Recursively check inner type.
9344       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9345       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9346           ParamKind == InvalidKernelParam)
9347         return ParamKind;
9348 
9349       // OpenCL v3.0 s6.11.a:
9350       // A restriction to pass pointers to pointers only applies to OpenCL C
9351       // v1.2 or below.
9352       if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9353         return ValidKernelParam;
9354 
9355       return PtrPtrKernelParam;
9356     }
9357 
9358     // C++ for OpenCL v1.0 s2.4:
9359     // Moreover the types used in parameters of the kernel functions must be:
9360     // Standard layout types for pointer parameters. The same applies to
9361     // reference if an implementation supports them in kernel parameters.
9362     if (S.getLangOpts().OpenCLCPlusPlus &&
9363         !S.getOpenCLOptions().isAvailableOption(
9364             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9365      auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9366      bool IsStandardLayoutType = true;
9367      if (CXXRec) {
9368        // If template type is not ODR-used its definition is only available
9369        // in the template definition not its instantiation.
9370        // FIXME: This logic doesn't work for types that depend on template
9371        // parameter (PR58590).
9372        if (!CXXRec->hasDefinition())
9373          CXXRec = CXXRec->getTemplateInstantiationPattern();
9374        if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9375          IsStandardLayoutType = false;
9376      }
9377      if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9378         !IsStandardLayoutType)
9379       return InvalidKernelParam;
9380     }
9381 
9382     // OpenCL v1.2 s6.9.p:
9383     // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9384     if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9385       return ValidKernelParam;
9386 
9387     return PtrKernelParam;
9388   }
9389 
9390   // OpenCL v1.2 s6.9.k:
9391   // Arguments to kernel functions in a program cannot be declared with the
9392   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9393   // uintptr_t or a struct and/or union that contain fields declared to be one
9394   // of these built-in scalar types.
9395   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9396     return InvalidKernelParam;
9397 
9398   if (PT->isImageType())
9399     return PtrKernelParam;
9400 
9401   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9402     return InvalidKernelParam;
9403 
9404   // OpenCL extension spec v1.2 s9.5:
9405   // This extension adds support for half scalar and vector types as built-in
9406   // types that can be used for arithmetic operations, conversions etc.
9407   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9408       PT->isHalfType())
9409     return InvalidKernelParam;
9410 
9411   // Look into an array argument to check if it has a forbidden type.
9412   if (PT->isArrayType()) {
9413     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9414     // Call ourself to check an underlying type of an array. Since the
9415     // getPointeeOrArrayElementType returns an innermost type which is not an
9416     // array, this recursive call only happens once.
9417     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9418   }
9419 
9420   // C++ for OpenCL v1.0 s2.4:
9421   // Moreover the types used in parameters of the kernel functions must be:
9422   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9423   // types) for parameters passed by value;
9424   if (S.getLangOpts().OpenCLCPlusPlus &&
9425       !S.getOpenCLOptions().isAvailableOption(
9426           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9427       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9428     return InvalidKernelParam;
9429 
9430   if (PT->isRecordType())
9431     return RecordKernelParam;
9432 
9433   return ValidKernelParam;
9434 }
9435 
9436 static void checkIsValidOpenCLKernelParameter(
9437   Sema &S,
9438   Declarator &D,
9439   ParmVarDecl *Param,
9440   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9441   QualType PT = Param->getType();
9442 
9443   // Cache the valid types we encounter to avoid rechecking structs that are
9444   // used again
9445   if (ValidTypes.count(PT.getTypePtr()))
9446     return;
9447 
9448   switch (getOpenCLKernelParameterType(S, PT)) {
9449   case PtrPtrKernelParam:
9450     // OpenCL v3.0 s6.11.a:
9451     // A kernel function argument cannot be declared as a pointer to a pointer
9452     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9453     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9454     D.setInvalidType();
9455     return;
9456 
9457   case InvalidAddrSpacePtrKernelParam:
9458     // OpenCL v1.0 s6.5:
9459     // __kernel function arguments declared to be a pointer of a type can point
9460     // to one of the following address spaces only : __global, __local or
9461     // __constant.
9462     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9463     D.setInvalidType();
9464     return;
9465 
9466     // OpenCL v1.2 s6.9.k:
9467     // Arguments to kernel functions in a program cannot be declared with the
9468     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9469     // uintptr_t or a struct and/or union that contain fields declared to be
9470     // one of these built-in scalar types.
9471 
9472   case InvalidKernelParam:
9473     // OpenCL v1.2 s6.8 n:
9474     // A kernel function argument cannot be declared
9475     // of event_t type.
9476     // Do not diagnose half type since it is diagnosed as invalid argument
9477     // type for any function elsewhere.
9478     if (!PT->isHalfType()) {
9479       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9480 
9481       // Explain what typedefs are involved.
9482       const TypedefType *Typedef = nullptr;
9483       while ((Typedef = PT->getAs<TypedefType>())) {
9484         SourceLocation Loc = Typedef->getDecl()->getLocation();
9485         // SourceLocation may be invalid for a built-in type.
9486         if (Loc.isValid())
9487           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9488         PT = Typedef->desugar();
9489       }
9490     }
9491 
9492     D.setInvalidType();
9493     return;
9494 
9495   case PtrKernelParam:
9496   case ValidKernelParam:
9497     ValidTypes.insert(PT.getTypePtr());
9498     return;
9499 
9500   case RecordKernelParam:
9501     break;
9502   }
9503 
9504   // Track nested structs we will inspect
9505   SmallVector<const Decl *, 4> VisitStack;
9506 
9507   // Track where we are in the nested structs. Items will migrate from
9508   // VisitStack to HistoryStack as we do the DFS for bad field.
9509   SmallVector<const FieldDecl *, 4> HistoryStack;
9510   HistoryStack.push_back(nullptr);
9511 
9512   // At this point we already handled everything except of a RecordType or
9513   // an ArrayType of a RecordType.
9514   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9515   const RecordType *RecTy =
9516       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9517   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9518 
9519   VisitStack.push_back(RecTy->getDecl());
9520   assert(VisitStack.back() && "First decl null?");
9521 
9522   do {
9523     const Decl *Next = VisitStack.pop_back_val();
9524     if (!Next) {
9525       assert(!HistoryStack.empty());
9526       // Found a marker, we have gone up a level
9527       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9528         ValidTypes.insert(Hist->getType().getTypePtr());
9529 
9530       continue;
9531     }
9532 
9533     // Adds everything except the original parameter declaration (which is not a
9534     // field itself) to the history stack.
9535     const RecordDecl *RD;
9536     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9537       HistoryStack.push_back(Field);
9538 
9539       QualType FieldTy = Field->getType();
9540       // Other field types (known to be valid or invalid) are handled while we
9541       // walk around RecordDecl::fields().
9542       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9543              "Unexpected type.");
9544       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9545 
9546       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9547     } else {
9548       RD = cast<RecordDecl>(Next);
9549     }
9550 
9551     // Add a null marker so we know when we've gone back up a level
9552     VisitStack.push_back(nullptr);
9553 
9554     for (const auto *FD : RD->fields()) {
9555       QualType QT = FD->getType();
9556 
9557       if (ValidTypes.count(QT.getTypePtr()))
9558         continue;
9559 
9560       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9561       if (ParamType == ValidKernelParam)
9562         continue;
9563 
9564       if (ParamType == RecordKernelParam) {
9565         VisitStack.push_back(FD);
9566         continue;
9567       }
9568 
9569       // OpenCL v1.2 s6.9.p:
9570       // Arguments to kernel functions that are declared to be a struct or union
9571       // do not allow OpenCL objects to be passed as elements of the struct or
9572       // union. This restriction was lifted in OpenCL v2.0 with the introduction
9573       // of SVM.
9574       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9575           ParamType == InvalidAddrSpacePtrKernelParam) {
9576         S.Diag(Param->getLocation(),
9577                diag::err_record_with_pointers_kernel_param)
9578           << PT->isUnionType()
9579           << PT;
9580       } else {
9581         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9582       }
9583 
9584       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9585           << OrigRecDecl->getDeclName();
9586 
9587       // We have an error, now let's go back up through history and show where
9588       // the offending field came from
9589       for (ArrayRef<const FieldDecl *>::const_iterator
9590                I = HistoryStack.begin() + 1,
9591                E = HistoryStack.end();
9592            I != E; ++I) {
9593         const FieldDecl *OuterField = *I;
9594         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9595           << OuterField->getType();
9596       }
9597 
9598       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9599         << QT->isPointerType()
9600         << QT;
9601       D.setInvalidType();
9602       return;
9603     }
9604   } while (!VisitStack.empty());
9605 }
9606 
9607 /// Find the DeclContext in which a tag is implicitly declared if we see an
9608 /// elaborated type specifier in the specified context, and lookup finds
9609 /// nothing.
9610 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9611   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9612     DC = DC->getParent();
9613   return DC;
9614 }
9615 
9616 /// Find the Scope in which a tag is implicitly declared if we see an
9617 /// elaborated type specifier in the specified context, and lookup finds
9618 /// nothing.
9619 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9620   while (S->isClassScope() ||
9621          (LangOpts.CPlusPlus &&
9622           S->isFunctionPrototypeScope()) ||
9623          ((S->getFlags() & Scope::DeclScope) == 0) ||
9624          (S->getEntity() && S->getEntity()->isTransparentContext()))
9625     S = S->getParent();
9626   return S;
9627 }
9628 
9629 /// Determine whether a declaration matches a known function in namespace std.
9630 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9631                          unsigned BuiltinID) {
9632   switch (BuiltinID) {
9633   case Builtin::BI__GetExceptionInfo:
9634     // No type checking whatsoever.
9635     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9636 
9637   case Builtin::BIaddressof:
9638   case Builtin::BI__addressof:
9639   case Builtin::BIforward:
9640   case Builtin::BIforward_like:
9641   case Builtin::BImove:
9642   case Builtin::BImove_if_noexcept:
9643   case Builtin::BIas_const: {
9644     // Ensure that we don't treat the algorithm
9645     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9646     // as the builtin std::move.
9647     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9648     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9649   }
9650 
9651   default:
9652     return false;
9653   }
9654 }
9655 
9656 NamedDecl*
9657 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9658                               TypeSourceInfo *TInfo, LookupResult &Previous,
9659                               MultiTemplateParamsArg TemplateParamListsRef,
9660                               bool &AddToScope) {
9661   QualType R = TInfo->getType();
9662 
9663   assert(R->isFunctionType());
9664   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9665     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9666 
9667   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9668   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9669   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9670     if (!TemplateParamLists.empty() &&
9671         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9672       TemplateParamLists.back() = Invented;
9673     else
9674       TemplateParamLists.push_back(Invented);
9675   }
9676 
9677   // TODO: consider using NameInfo for diagnostic.
9678   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9679   DeclarationName Name = NameInfo.getName();
9680   StorageClass SC = getFunctionStorageClass(*this, D);
9681 
9682   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9683     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9684          diag::err_invalid_thread)
9685       << DeclSpec::getSpecifierName(TSCS);
9686 
9687   if (D.isFirstDeclarationOfMember())
9688     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9689                            D.getIdentifierLoc());
9690 
9691   bool isFriend = false;
9692   FunctionTemplateDecl *FunctionTemplate = nullptr;
9693   bool isMemberSpecialization = false;
9694   bool isFunctionTemplateSpecialization = false;
9695 
9696   bool isDependentClassScopeExplicitSpecialization = false;
9697   bool HasExplicitTemplateArgs = false;
9698   TemplateArgumentListInfo TemplateArgs;
9699 
9700   bool isVirtualOkay = false;
9701 
9702   DeclContext *OriginalDC = DC;
9703   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9704 
9705   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9706                                               isVirtualOkay);
9707   if (!NewFD) return nullptr;
9708 
9709   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9710     NewFD->setTopLevelDeclInObjCContainer();
9711 
9712   // Set the lexical context. If this is a function-scope declaration, or has a
9713   // C++ scope specifier, or is the object of a friend declaration, the lexical
9714   // context will be different from the semantic context.
9715   NewFD->setLexicalDeclContext(CurContext);
9716 
9717   if (IsLocalExternDecl)
9718     NewFD->setLocalExternDecl();
9719 
9720   if (getLangOpts().CPlusPlus) {
9721     // The rules for implicit inlines changed in C++20 for methods and friends
9722     // with an in-class definition (when such a definition is not attached to
9723     // the global module).  User-specified 'inline' overrides this (set when
9724     // the function decl is created above).
9725     // FIXME: We need a better way to separate C++ standard and clang modules.
9726     bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9727                                !NewFD->getOwningModule() ||
9728                                NewFD->getOwningModule()->isGlobalModule() ||
9729                                NewFD->getOwningModule()->isHeaderLikeModule();
9730     bool isInline = D.getDeclSpec().isInlineSpecified();
9731     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9732     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9733     isFriend = D.getDeclSpec().isFriendSpecified();
9734     if (isFriend && !isInline && D.isFunctionDefinition()) {
9735       // Pre-C++20 [class.friend]p5
9736       //   A function can be defined in a friend declaration of a
9737       //   class . . . . Such a function is implicitly inline.
9738       // Post C++20 [class.friend]p7
9739       //   Such a function is implicitly an inline function if it is attached
9740       //   to the global module.
9741       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9742     }
9743 
9744     // If this is a method defined in an __interface, and is not a constructor
9745     // or an overloaded operator, then set the pure flag (isVirtual will already
9746     // return true).
9747     if (const CXXRecordDecl *Parent =
9748           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9749       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9750         NewFD->setPure(true);
9751 
9752       // C++ [class.union]p2
9753       //   A union can have member functions, but not virtual functions.
9754       if (isVirtual && Parent->isUnion()) {
9755         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9756         NewFD->setInvalidDecl();
9757       }
9758       if ((Parent->isClass() || Parent->isStruct()) &&
9759           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9760           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9761           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9762         if (auto *Def = Parent->getDefinition())
9763           Def->setInitMethod(true);
9764       }
9765     }
9766 
9767     SetNestedNameSpecifier(*this, NewFD, D);
9768     isMemberSpecialization = false;
9769     isFunctionTemplateSpecialization = false;
9770     if (D.isInvalidType())
9771       NewFD->setInvalidDecl();
9772 
9773     // Match up the template parameter lists with the scope specifier, then
9774     // determine whether we have a template or a template specialization.
9775     bool Invalid = false;
9776     TemplateParameterList *TemplateParams =
9777         MatchTemplateParametersToScopeSpecifier(
9778             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9779             D.getCXXScopeSpec(),
9780             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9781                 ? D.getName().TemplateId
9782                 : nullptr,
9783             TemplateParamLists, isFriend, isMemberSpecialization,
9784             Invalid);
9785     if (TemplateParams) {
9786       // Check that we can declare a template here.
9787       if (CheckTemplateDeclScope(S, TemplateParams))
9788         NewFD->setInvalidDecl();
9789 
9790       if (TemplateParams->size() > 0) {
9791         // This is a function template
9792 
9793         // A destructor cannot be a template.
9794         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9795           Diag(NewFD->getLocation(), diag::err_destructor_template);
9796           NewFD->setInvalidDecl();
9797         }
9798 
9799         // If we're adding a template to a dependent context, we may need to
9800         // rebuilding some of the types used within the template parameter list,
9801         // now that we know what the current instantiation is.
9802         if (DC->isDependentContext()) {
9803           ContextRAII SavedContext(*this, DC);
9804           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9805             Invalid = true;
9806         }
9807 
9808         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9809                                                         NewFD->getLocation(),
9810                                                         Name, TemplateParams,
9811                                                         NewFD);
9812         FunctionTemplate->setLexicalDeclContext(CurContext);
9813         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9814 
9815         // For source fidelity, store the other template param lists.
9816         if (TemplateParamLists.size() > 1) {
9817           NewFD->setTemplateParameterListsInfo(Context,
9818               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9819                   .drop_back(1));
9820         }
9821       } else {
9822         // This is a function template specialization.
9823         isFunctionTemplateSpecialization = true;
9824         // For source fidelity, store all the template param lists.
9825         if (TemplateParamLists.size() > 0)
9826           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9827 
9828         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9829         if (isFriend) {
9830           // We want to remove the "template<>", found here.
9831           SourceRange RemoveRange = TemplateParams->getSourceRange();
9832 
9833           // If we remove the template<> and the name is not a
9834           // template-id, we're actually silently creating a problem:
9835           // the friend declaration will refer to an untemplated decl,
9836           // and clearly the user wants a template specialization.  So
9837           // we need to insert '<>' after the name.
9838           SourceLocation InsertLoc;
9839           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9840             InsertLoc = D.getName().getSourceRange().getEnd();
9841             InsertLoc = getLocForEndOfToken(InsertLoc);
9842           }
9843 
9844           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9845             << Name << RemoveRange
9846             << FixItHint::CreateRemoval(RemoveRange)
9847             << FixItHint::CreateInsertion(InsertLoc, "<>");
9848           Invalid = true;
9849         }
9850       }
9851     } else {
9852       // Check that we can declare a template here.
9853       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9854           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9855         NewFD->setInvalidDecl();
9856 
9857       // All template param lists were matched against the scope specifier:
9858       // this is NOT (an explicit specialization of) a template.
9859       if (TemplateParamLists.size() > 0)
9860         // For source fidelity, store all the template param lists.
9861         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9862     }
9863 
9864     if (Invalid) {
9865       NewFD->setInvalidDecl();
9866       if (FunctionTemplate)
9867         FunctionTemplate->setInvalidDecl();
9868     }
9869 
9870     // C++ [dcl.fct.spec]p5:
9871     //   The virtual specifier shall only be used in declarations of
9872     //   nonstatic class member functions that appear within a
9873     //   member-specification of a class declaration; see 10.3.
9874     //
9875     if (isVirtual && !NewFD->isInvalidDecl()) {
9876       if (!isVirtualOkay) {
9877         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9878              diag::err_virtual_non_function);
9879       } else if (!CurContext->isRecord()) {
9880         // 'virtual' was specified outside of the class.
9881         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9882              diag::err_virtual_out_of_class)
9883           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9884       } else if (NewFD->getDescribedFunctionTemplate()) {
9885         // C++ [temp.mem]p3:
9886         //  A member function template shall not be virtual.
9887         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9888              diag::err_virtual_member_function_template)
9889           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9890       } else {
9891         // Okay: Add virtual to the method.
9892         NewFD->setVirtualAsWritten(true);
9893       }
9894 
9895       if (getLangOpts().CPlusPlus14 &&
9896           NewFD->getReturnType()->isUndeducedType())
9897         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9898     }
9899 
9900     if (getLangOpts().CPlusPlus14 &&
9901         (NewFD->isDependentContext() ||
9902          (isFriend && CurContext->isDependentContext())) &&
9903         NewFD->getReturnType()->isUndeducedType()) {
9904       // If the function template is referenced directly (for instance, as a
9905       // member of the current instantiation), pretend it has a dependent type.
9906       // This is not really justified by the standard, but is the only sane
9907       // thing to do.
9908       // FIXME: For a friend function, we have not marked the function as being
9909       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9910       const FunctionProtoType *FPT =
9911           NewFD->getType()->castAs<FunctionProtoType>();
9912       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9913       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9914                                              FPT->getExtProtoInfo()));
9915     }
9916 
9917     // C++ [dcl.fct.spec]p3:
9918     //  The inline specifier shall not appear on a block scope function
9919     //  declaration.
9920     if (isInline && !NewFD->isInvalidDecl()) {
9921       if (CurContext->isFunctionOrMethod()) {
9922         // 'inline' is not allowed on block scope function declaration.
9923         Diag(D.getDeclSpec().getInlineSpecLoc(),
9924              diag::err_inline_declaration_block_scope) << Name
9925           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9926       }
9927     }
9928 
9929     // C++ [dcl.fct.spec]p6:
9930     //  The explicit specifier shall be used only in the declaration of a
9931     //  constructor or conversion function within its class definition;
9932     //  see 12.3.1 and 12.3.2.
9933     if (hasExplicit && !NewFD->isInvalidDecl() &&
9934         !isa<CXXDeductionGuideDecl>(NewFD)) {
9935       if (!CurContext->isRecord()) {
9936         // 'explicit' was specified outside of the class.
9937         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9938              diag::err_explicit_out_of_class)
9939             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9940       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9941                  !isa<CXXConversionDecl>(NewFD)) {
9942         // 'explicit' was specified on a function that wasn't a constructor
9943         // or conversion function.
9944         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9945              diag::err_explicit_non_ctor_or_conv_function)
9946             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9947       }
9948     }
9949 
9950     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9951     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9952       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9953       // are implicitly inline.
9954       NewFD->setImplicitlyInline();
9955 
9956       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9957       // be either constructors or to return a literal type. Therefore,
9958       // destructors cannot be declared constexpr.
9959       if (isa<CXXDestructorDecl>(NewFD) &&
9960           (!getLangOpts().CPlusPlus20 ||
9961            ConstexprKind == ConstexprSpecKind::Consteval)) {
9962         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9963             << static_cast<int>(ConstexprKind);
9964         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9965                                     ? ConstexprSpecKind::Unspecified
9966                                     : ConstexprSpecKind::Constexpr);
9967       }
9968       // C++20 [dcl.constexpr]p2: An allocation function, or a
9969       // deallocation function shall not be declared with the consteval
9970       // specifier.
9971       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9972           (NewFD->getOverloadedOperator() == OO_New ||
9973            NewFD->getOverloadedOperator() == OO_Array_New ||
9974            NewFD->getOverloadedOperator() == OO_Delete ||
9975            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9976         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9977              diag::err_invalid_consteval_decl_kind)
9978             << NewFD;
9979         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9980       }
9981     }
9982 
9983     // If __module_private__ was specified, mark the function accordingly.
9984     if (D.getDeclSpec().isModulePrivateSpecified()) {
9985       if (isFunctionTemplateSpecialization) {
9986         SourceLocation ModulePrivateLoc
9987           = D.getDeclSpec().getModulePrivateSpecLoc();
9988         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9989           << 0
9990           << FixItHint::CreateRemoval(ModulePrivateLoc);
9991       } else {
9992         NewFD->setModulePrivate();
9993         if (FunctionTemplate)
9994           FunctionTemplate->setModulePrivate();
9995       }
9996     }
9997 
9998     if (isFriend) {
9999       if (FunctionTemplate) {
10000         FunctionTemplate->setObjectOfFriendDecl();
10001         FunctionTemplate->setAccess(AS_public);
10002       }
10003       NewFD->setObjectOfFriendDecl();
10004       NewFD->setAccess(AS_public);
10005     }
10006 
10007     // If a function is defined as defaulted or deleted, mark it as such now.
10008     // We'll do the relevant checks on defaulted / deleted functions later.
10009     switch (D.getFunctionDefinitionKind()) {
10010     case FunctionDefinitionKind::Declaration:
10011     case FunctionDefinitionKind::Definition:
10012       break;
10013 
10014     case FunctionDefinitionKind::Defaulted:
10015       NewFD->setDefaulted();
10016       break;
10017 
10018     case FunctionDefinitionKind::Deleted:
10019       NewFD->setDeletedAsWritten();
10020       break;
10021     }
10022 
10023     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10024         D.isFunctionDefinition() && !isInline) {
10025       // Pre C++20 [class.mfct]p2:
10026       //   A member function may be defined (8.4) in its class definition, in
10027       //   which case it is an inline member function (7.1.2)
10028       // Post C++20 [class.mfct]p1:
10029       //   If a member function is attached to the global module and is defined
10030       //   in its class definition, it is inline.
10031       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10032     }
10033 
10034     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10035         !CurContext->isRecord()) {
10036       // C++ [class.static]p1:
10037       //   A data or function member of a class may be declared static
10038       //   in a class definition, in which case it is a static member of
10039       //   the class.
10040 
10041       // Complain about the 'static' specifier if it's on an out-of-line
10042       // member function definition.
10043 
10044       // MSVC permits the use of a 'static' storage specifier on an out-of-line
10045       // member function template declaration and class member template
10046       // declaration (MSVC versions before 2015), warn about this.
10047       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10048            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10049              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10050            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10051            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10052         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10053     }
10054 
10055     // C++11 [except.spec]p15:
10056     //   A deallocation function with no exception-specification is treated
10057     //   as if it were specified with noexcept(true).
10058     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10059     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10060          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10061         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10062       NewFD->setType(Context.getFunctionType(
10063           FPT->getReturnType(), FPT->getParamTypes(),
10064           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10065 
10066     // C++20 [dcl.inline]/7
10067     // If an inline function or variable that is attached to a named module
10068     // is declared in a definition domain, it shall be defined in that
10069     // domain.
10070     // So, if the current declaration does not have a definition, we must
10071     // check at the end of the TU (or when the PMF starts) to see that we
10072     // have a definition at that point.
10073     if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10074         NewFD->hasOwningModule() &&
10075         NewFD->getOwningModule()->isModulePurview()) {
10076       PendingInlineFuncDecls.insert(NewFD);
10077     }
10078   }
10079 
10080   // Filter out previous declarations that don't match the scope.
10081   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10082                        D.getCXXScopeSpec().isNotEmpty() ||
10083                        isMemberSpecialization ||
10084                        isFunctionTemplateSpecialization);
10085 
10086   // Handle GNU asm-label extension (encoded as an attribute).
10087   if (Expr *E = (Expr*) D.getAsmLabel()) {
10088     // The parser guarantees this is a string.
10089     StringLiteral *SE = cast<StringLiteral>(E);
10090     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10091                                         /*IsLiteralLabel=*/true,
10092                                         SE->getStrTokenLoc(0)));
10093   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10094     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10095       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10096     if (I != ExtnameUndeclaredIdentifiers.end()) {
10097       if (isDeclExternC(NewFD)) {
10098         NewFD->addAttr(I->second);
10099         ExtnameUndeclaredIdentifiers.erase(I);
10100       } else
10101         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10102             << /*Variable*/0 << NewFD;
10103     }
10104   }
10105 
10106   // Copy the parameter declarations from the declarator D to the function
10107   // declaration NewFD, if they are available.  First scavenge them into Params.
10108   SmallVector<ParmVarDecl*, 16> Params;
10109   unsigned FTIIdx;
10110   if (D.isFunctionDeclarator(FTIIdx)) {
10111     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10112 
10113     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10114     // function that takes no arguments, not a function that takes a
10115     // single void argument.
10116     // We let through "const void" here because Sema::GetTypeForDeclarator
10117     // already checks for that case.
10118     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10119       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10120         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10121         assert(Param->getDeclContext() != NewFD && "Was set before ?");
10122         Param->setDeclContext(NewFD);
10123         Params.push_back(Param);
10124 
10125         if (Param->isInvalidDecl())
10126           NewFD->setInvalidDecl();
10127       }
10128     }
10129 
10130     if (!getLangOpts().CPlusPlus) {
10131       // In C, find all the tag declarations from the prototype and move them
10132       // into the function DeclContext. Remove them from the surrounding tag
10133       // injection context of the function, which is typically but not always
10134       // the TU.
10135       DeclContext *PrototypeTagContext =
10136           getTagInjectionContext(NewFD->getLexicalDeclContext());
10137       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10138         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10139 
10140         // We don't want to reparent enumerators. Look at their parent enum
10141         // instead.
10142         if (!TD) {
10143           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10144             TD = cast<EnumDecl>(ECD->getDeclContext());
10145         }
10146         if (!TD)
10147           continue;
10148         DeclContext *TagDC = TD->getLexicalDeclContext();
10149         if (!TagDC->containsDecl(TD))
10150           continue;
10151         TagDC->removeDecl(TD);
10152         TD->setDeclContext(NewFD);
10153         NewFD->addDecl(TD);
10154 
10155         // Preserve the lexical DeclContext if it is not the surrounding tag
10156         // injection context of the FD. In this example, the semantic context of
10157         // E will be f and the lexical context will be S, while both the
10158         // semantic and lexical contexts of S will be f:
10159         //   void f(struct S { enum E { a } f; } s);
10160         if (TagDC != PrototypeTagContext)
10161           TD->setLexicalDeclContext(TagDC);
10162       }
10163     }
10164   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10165     // When we're declaring a function with a typedef, typeof, etc as in the
10166     // following example, we'll need to synthesize (unnamed)
10167     // parameters for use in the declaration.
10168     //
10169     // @code
10170     // typedef void fn(int);
10171     // fn f;
10172     // @endcode
10173 
10174     // Synthesize a parameter for each argument type.
10175     for (const auto &AI : FT->param_types()) {
10176       ParmVarDecl *Param =
10177           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10178       Param->setScopeInfo(0, Params.size());
10179       Params.push_back(Param);
10180     }
10181   } else {
10182     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10183            "Should not need args for typedef of non-prototype fn");
10184   }
10185 
10186   // Finally, we know we have the right number of parameters, install them.
10187   NewFD->setParams(Params);
10188 
10189   if (D.getDeclSpec().isNoreturnSpecified())
10190     NewFD->addAttr(
10191         C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10192 
10193   // Functions returning a variably modified type violate C99 6.7.5.2p2
10194   // because all functions have linkage.
10195   if (!NewFD->isInvalidDecl() &&
10196       NewFD->getReturnType()->isVariablyModifiedType()) {
10197     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10198     NewFD->setInvalidDecl();
10199   }
10200 
10201   // Apply an implicit SectionAttr if '#pragma clang section text' is active
10202   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10203       !NewFD->hasAttr<SectionAttr>())
10204     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10205         Context, PragmaClangTextSection.SectionName,
10206         PragmaClangTextSection.PragmaLocation));
10207 
10208   // Apply an implicit SectionAttr if #pragma code_seg is active.
10209   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10210       !NewFD->hasAttr<SectionAttr>()) {
10211     NewFD->addAttr(SectionAttr::CreateImplicit(
10212         Context, CodeSegStack.CurrentValue->getString(),
10213         CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10214     if (UnifySection(CodeSegStack.CurrentValue->getString(),
10215                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10216                          ASTContext::PSF_Read,
10217                      NewFD))
10218       NewFD->dropAttr<SectionAttr>();
10219   }
10220 
10221   // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10222   // active.
10223   if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10224       !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10225     NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10226         Context, PragmaClangTextSection.PragmaLocation));
10227 
10228   // Apply an implicit CodeSegAttr from class declspec or
10229   // apply an implicit SectionAttr from #pragma code_seg if active.
10230   if (!NewFD->hasAttr<CodeSegAttr>()) {
10231     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10232                                                                  D.isFunctionDefinition())) {
10233       NewFD->addAttr(SAttr);
10234     }
10235   }
10236 
10237   // Handle attributes.
10238   ProcessDeclAttributes(S, NewFD, D);
10239   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10240   if (NewTVA && !NewTVA->isDefaultVersion() &&
10241       !Context.getTargetInfo().hasFeature("fmv")) {
10242     // Don't add to scope fmv functions declarations if fmv disabled
10243     AddToScope = false;
10244     return NewFD;
10245   }
10246 
10247   if (getLangOpts().OpenCL) {
10248     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10249     // type declaration will generate a compilation error.
10250     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10251     if (AddressSpace != LangAS::Default) {
10252       Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10253       NewFD->setInvalidDecl();
10254     }
10255   }
10256 
10257   if (getLangOpts().HLSL) {
10258     auto &TargetInfo = getASTContext().getTargetInfo();
10259     // Skip operator overload which not identifier.
10260     // Also make sure NewFD is in translation-unit scope.
10261     if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10262         NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10263         S->getDepth() == 0) {
10264       CheckHLSLEntryPoint(NewFD);
10265       if (!NewFD->isInvalidDecl()) {
10266         auto Env = TargetInfo.getTriple().getEnvironment();
10267         HLSLShaderAttr::ShaderType ShaderType =
10268             static_cast<HLSLShaderAttr::ShaderType>(
10269                 hlsl::getStageFromEnvironment(Env));
10270         // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10271         // function.
10272         if (HLSLShaderAttr *NT = NewFD->getAttr<HLSLShaderAttr>()) {
10273           if (NT->getType() != ShaderType)
10274             Diag(NT->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
10275                 << NT;
10276         } else {
10277           NewFD->addAttr(HLSLShaderAttr::Create(Context, ShaderType,
10278                                                 NewFD->getBeginLoc()));
10279         }
10280       }
10281     }
10282     // HLSL does not support specifying an address space on a function return
10283     // type.
10284     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10285     if (AddressSpace != LangAS::Default) {
10286       Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10287       NewFD->setInvalidDecl();
10288     }
10289   }
10290 
10291   if (!getLangOpts().CPlusPlus) {
10292     // Perform semantic checking on the function declaration.
10293     if (!NewFD->isInvalidDecl() && NewFD->isMain())
10294       CheckMain(NewFD, D.getDeclSpec());
10295 
10296     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10297       CheckMSVCRTEntryPoint(NewFD);
10298 
10299     if (!NewFD->isInvalidDecl())
10300       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10301                                                   isMemberSpecialization,
10302                                                   D.isFunctionDefinition()));
10303     else if (!Previous.empty())
10304       // Recover gracefully from an invalid redeclaration.
10305       D.setRedeclaration(true);
10306     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10307             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10308            "previous declaration set still overloaded");
10309 
10310     // Diagnose no-prototype function declarations with calling conventions that
10311     // don't support variadic calls. Only do this in C and do it after merging
10312     // possibly prototyped redeclarations.
10313     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10314     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10315       CallingConv CC = FT->getExtInfo().getCC();
10316       if (!supportsVariadicCall(CC)) {
10317         // Windows system headers sometimes accidentally use stdcall without
10318         // (void) parameters, so we relax this to a warning.
10319         int DiagID =
10320             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10321         Diag(NewFD->getLocation(), DiagID)
10322             << FunctionType::getNameForCallConv(CC);
10323       }
10324     }
10325 
10326    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10327        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10328      checkNonTrivialCUnion(NewFD->getReturnType(),
10329                            NewFD->getReturnTypeSourceRange().getBegin(),
10330                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10331   } else {
10332     // C++11 [replacement.functions]p3:
10333     //  The program's definitions shall not be specified as inline.
10334     //
10335     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10336     //
10337     // Suppress the diagnostic if the function is __attribute__((used)), since
10338     // that forces an external definition to be emitted.
10339     if (D.getDeclSpec().isInlineSpecified() &&
10340         NewFD->isReplaceableGlobalAllocationFunction() &&
10341         !NewFD->hasAttr<UsedAttr>())
10342       Diag(D.getDeclSpec().getInlineSpecLoc(),
10343            diag::ext_operator_new_delete_declared_inline)
10344         << NewFD->getDeclName();
10345 
10346     // If the declarator is a template-id, translate the parser's template
10347     // argument list into our AST format.
10348     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10349       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10350       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10351       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10352       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10353                                          TemplateId->NumArgs);
10354       translateTemplateArguments(TemplateArgsPtr,
10355                                  TemplateArgs);
10356 
10357       HasExplicitTemplateArgs = true;
10358 
10359       if (NewFD->isInvalidDecl()) {
10360         HasExplicitTemplateArgs = false;
10361       } else if (FunctionTemplate) {
10362         // Function template with explicit template arguments.
10363         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10364           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10365 
10366         HasExplicitTemplateArgs = false;
10367       } else {
10368         assert((isFunctionTemplateSpecialization ||
10369                 D.getDeclSpec().isFriendSpecified()) &&
10370                "should have a 'template<>' for this decl");
10371         // "friend void foo<>(int);" is an implicit specialization decl.
10372         isFunctionTemplateSpecialization = true;
10373       }
10374     } else if (isFriend && isFunctionTemplateSpecialization) {
10375       // This combination is only possible in a recovery case;  the user
10376       // wrote something like:
10377       //   template <> friend void foo(int);
10378       // which we're recovering from as if the user had written:
10379       //   friend void foo<>(int);
10380       // Go ahead and fake up a template id.
10381       HasExplicitTemplateArgs = true;
10382       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10383       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10384     }
10385 
10386     // We do not add HD attributes to specializations here because
10387     // they may have different constexpr-ness compared to their
10388     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10389     // may end up with different effective targets. Instead, a
10390     // specialization inherits its target attributes from its template
10391     // in the CheckFunctionTemplateSpecialization() call below.
10392     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10393       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10394 
10395     // If it's a friend (and only if it's a friend), it's possible
10396     // that either the specialized function type or the specialized
10397     // template is dependent, and therefore matching will fail.  In
10398     // this case, don't check the specialization yet.
10399     if (isFunctionTemplateSpecialization && isFriend &&
10400         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10401          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10402              TemplateArgs.arguments()))) {
10403       assert(HasExplicitTemplateArgs &&
10404              "friend function specialization without template args");
10405       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10406                                                        Previous))
10407         NewFD->setInvalidDecl();
10408     } else if (isFunctionTemplateSpecialization) {
10409       if (CurContext->isDependentContext() && CurContext->isRecord()
10410           && !isFriend) {
10411         isDependentClassScopeExplicitSpecialization = true;
10412       } else if (!NewFD->isInvalidDecl() &&
10413                  CheckFunctionTemplateSpecialization(
10414                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10415                      Previous))
10416         NewFD->setInvalidDecl();
10417 
10418       // C++ [dcl.stc]p1:
10419       //   A storage-class-specifier shall not be specified in an explicit
10420       //   specialization (14.7.3)
10421       FunctionTemplateSpecializationInfo *Info =
10422           NewFD->getTemplateSpecializationInfo();
10423       if (Info && SC != SC_None) {
10424         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10425           Diag(NewFD->getLocation(),
10426                diag::err_explicit_specialization_inconsistent_storage_class)
10427             << SC
10428             << FixItHint::CreateRemoval(
10429                                       D.getDeclSpec().getStorageClassSpecLoc());
10430 
10431         else
10432           Diag(NewFD->getLocation(),
10433                diag::ext_explicit_specialization_storage_class)
10434             << FixItHint::CreateRemoval(
10435                                       D.getDeclSpec().getStorageClassSpecLoc());
10436       }
10437     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10438       if (CheckMemberSpecialization(NewFD, Previous))
10439           NewFD->setInvalidDecl();
10440     }
10441 
10442     // Perform semantic checking on the function declaration.
10443     if (!isDependentClassScopeExplicitSpecialization) {
10444       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10445         CheckMain(NewFD, D.getDeclSpec());
10446 
10447       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10448         CheckMSVCRTEntryPoint(NewFD);
10449 
10450       if (!NewFD->isInvalidDecl())
10451         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10452                                                     isMemberSpecialization,
10453                                                     D.isFunctionDefinition()));
10454       else if (!Previous.empty())
10455         // Recover gracefully from an invalid redeclaration.
10456         D.setRedeclaration(true);
10457     }
10458 
10459     assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10460             !D.isRedeclaration() ||
10461             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10462            "previous declaration set still overloaded");
10463 
10464     NamedDecl *PrincipalDecl = (FunctionTemplate
10465                                 ? cast<NamedDecl>(FunctionTemplate)
10466                                 : NewFD);
10467 
10468     if (isFriend && NewFD->getPreviousDecl()) {
10469       AccessSpecifier Access = AS_public;
10470       if (!NewFD->isInvalidDecl())
10471         Access = NewFD->getPreviousDecl()->getAccess();
10472 
10473       NewFD->setAccess(Access);
10474       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10475     }
10476 
10477     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10478         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10479       PrincipalDecl->setNonMemberOperator();
10480 
10481     // If we have a function template, check the template parameter
10482     // list. This will check and merge default template arguments.
10483     if (FunctionTemplate) {
10484       FunctionTemplateDecl *PrevTemplate =
10485                                      FunctionTemplate->getPreviousDecl();
10486       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10487                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10488                                     : nullptr,
10489                             D.getDeclSpec().isFriendSpecified()
10490                               ? (D.isFunctionDefinition()
10491                                    ? TPC_FriendFunctionTemplateDefinition
10492                                    : TPC_FriendFunctionTemplate)
10493                               : (D.getCXXScopeSpec().isSet() &&
10494                                  DC && DC->isRecord() &&
10495                                  DC->isDependentContext())
10496                                   ? TPC_ClassTemplateMember
10497                                   : TPC_FunctionTemplate);
10498     }
10499 
10500     if (NewFD->isInvalidDecl()) {
10501       // Ignore all the rest of this.
10502     } else if (!D.isRedeclaration()) {
10503       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10504                                        AddToScope };
10505       // Fake up an access specifier if it's supposed to be a class member.
10506       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10507         NewFD->setAccess(AS_public);
10508 
10509       // Qualified decls generally require a previous declaration.
10510       if (D.getCXXScopeSpec().isSet()) {
10511         // ...with the major exception of templated-scope or
10512         // dependent-scope friend declarations.
10513 
10514         // TODO: we currently also suppress this check in dependent
10515         // contexts because (1) the parameter depth will be off when
10516         // matching friend templates and (2) we might actually be
10517         // selecting a friend based on a dependent factor.  But there
10518         // are situations where these conditions don't apply and we
10519         // can actually do this check immediately.
10520         //
10521         // Unless the scope is dependent, it's always an error if qualified
10522         // redeclaration lookup found nothing at all. Diagnose that now;
10523         // nothing will diagnose that error later.
10524         if (isFriend &&
10525             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10526              (!Previous.empty() && CurContext->isDependentContext()))) {
10527           // ignore these
10528         } else if (NewFD->isCPUDispatchMultiVersion() ||
10529                    NewFD->isCPUSpecificMultiVersion()) {
10530           // ignore this, we allow the redeclaration behavior here to create new
10531           // versions of the function.
10532         } else {
10533           // The user tried to provide an out-of-line definition for a
10534           // function that is a member of a class or namespace, but there
10535           // was no such member function declared (C++ [class.mfct]p2,
10536           // C++ [namespace.memdef]p2). For example:
10537           //
10538           // class X {
10539           //   void f() const;
10540           // };
10541           //
10542           // void X::f() { } // ill-formed
10543           //
10544           // Complain about this problem, and attempt to suggest close
10545           // matches (e.g., those that differ only in cv-qualifiers and
10546           // whether the parameter types are references).
10547 
10548           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10549                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10550             AddToScope = ExtraArgs.AddToScope;
10551             return Result;
10552           }
10553         }
10554 
10555         // Unqualified local friend declarations are required to resolve
10556         // to something.
10557       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10558         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10559                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10560           AddToScope = ExtraArgs.AddToScope;
10561           return Result;
10562         }
10563       }
10564     } else if (!D.isFunctionDefinition() &&
10565                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10566                !isFriend && !isFunctionTemplateSpecialization &&
10567                !isMemberSpecialization) {
10568       // An out-of-line member function declaration must also be a
10569       // definition (C++ [class.mfct]p2).
10570       // Note that this is not the case for explicit specializations of
10571       // function templates or member functions of class templates, per
10572       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10573       // extension for compatibility with old SWIG code which likes to
10574       // generate them.
10575       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10576         << D.getCXXScopeSpec().getRange();
10577     }
10578   }
10579 
10580   // If this is the first declaration of a library builtin function, add
10581   // attributes as appropriate.
10582   if (!D.isRedeclaration()) {
10583     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10584       if (unsigned BuiltinID = II->getBuiltinID()) {
10585         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10586         if (!InStdNamespace &&
10587             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10588           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10589             // Validate the type matches unless this builtin is specified as
10590             // matching regardless of its declared type.
10591             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10592               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10593             } else {
10594               ASTContext::GetBuiltinTypeError Error;
10595               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10596               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10597 
10598               if (!Error && !BuiltinType.isNull() &&
10599                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10600                       NewFD->getType(), BuiltinType))
10601                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10602             }
10603           }
10604         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10605                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10606           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10607         }
10608       }
10609     }
10610   }
10611 
10612   ProcessPragmaWeak(S, NewFD);
10613   checkAttributesAfterMerging(*this, *NewFD);
10614 
10615   AddKnownFunctionAttributes(NewFD);
10616 
10617   if (NewFD->hasAttr<OverloadableAttr>() &&
10618       !NewFD->getType()->getAs<FunctionProtoType>()) {
10619     Diag(NewFD->getLocation(),
10620          diag::err_attribute_overloadable_no_prototype)
10621       << NewFD;
10622     NewFD->dropAttr<OverloadableAttr>();
10623   }
10624 
10625   // If there's a #pragma GCC visibility in scope, and this isn't a class
10626   // member, set the visibility of this function.
10627   if (!DC->isRecord() && NewFD->isExternallyVisible())
10628     AddPushedVisibilityAttribute(NewFD);
10629 
10630   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10631   // marking the function.
10632   AddCFAuditedAttribute(NewFD);
10633 
10634   // If this is a function definition, check if we have to apply any
10635   // attributes (i.e. optnone and no_builtin) due to a pragma.
10636   if (D.isFunctionDefinition()) {
10637     AddRangeBasedOptnone(NewFD);
10638     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10639     AddSectionMSAllocText(NewFD);
10640     ModifyFnAttributesMSPragmaOptimize(NewFD);
10641   }
10642 
10643   // If this is the first declaration of an extern C variable, update
10644   // the map of such variables.
10645   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10646       isIncompleteDeclExternC(*this, NewFD))
10647     RegisterLocallyScopedExternCDecl(NewFD, S);
10648 
10649   // Set this FunctionDecl's range up to the right paren.
10650   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10651 
10652   if (D.isRedeclaration() && !Previous.empty()) {
10653     NamedDecl *Prev = Previous.getRepresentativeDecl();
10654     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10655                                    isMemberSpecialization ||
10656                                        isFunctionTemplateSpecialization,
10657                                    D.isFunctionDefinition());
10658   }
10659 
10660   if (getLangOpts().CUDA) {
10661     IdentifierInfo *II = NewFD->getIdentifier();
10662     if (II && II->isStr(getCudaConfigureFuncName()) &&
10663         !NewFD->isInvalidDecl() &&
10664         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10665       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10666         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10667             << getCudaConfigureFuncName();
10668       Context.setcudaConfigureCallDecl(NewFD);
10669     }
10670 
10671     // Variadic functions, other than a *declaration* of printf, are not allowed
10672     // in device-side CUDA code, unless someone passed
10673     // -fcuda-allow-variadic-functions.
10674     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10675         (NewFD->hasAttr<CUDADeviceAttr>() ||
10676          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10677         !(II && II->isStr("printf") && NewFD->isExternC() &&
10678           !D.isFunctionDefinition())) {
10679       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10680     }
10681   }
10682 
10683   MarkUnusedFileScopedDecl(NewFD);
10684 
10685 
10686 
10687   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10688     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10689     if (SC == SC_Static) {
10690       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10691       D.setInvalidType();
10692     }
10693 
10694     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10695     if (!NewFD->getReturnType()->isVoidType()) {
10696       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10697       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10698           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10699                                 : FixItHint());
10700       D.setInvalidType();
10701     }
10702 
10703     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10704     for (auto *Param : NewFD->parameters())
10705       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10706 
10707     if (getLangOpts().OpenCLCPlusPlus) {
10708       if (DC->isRecord()) {
10709         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10710         D.setInvalidType();
10711       }
10712       if (FunctionTemplate) {
10713         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10714         D.setInvalidType();
10715       }
10716     }
10717   }
10718 
10719   if (getLangOpts().CPlusPlus) {
10720     // Precalculate whether this is a friend function template with a constraint
10721     // that depends on an enclosing template, per [temp.friend]p9.
10722     if (isFriend && FunctionTemplate &&
10723         FriendConstraintsDependOnEnclosingTemplate(NewFD))
10724       NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10725 
10726     if (FunctionTemplate) {
10727       if (NewFD->isInvalidDecl())
10728         FunctionTemplate->setInvalidDecl();
10729       return FunctionTemplate;
10730     }
10731 
10732     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10733       CompleteMemberSpecialization(NewFD, Previous);
10734   }
10735 
10736   for (const ParmVarDecl *Param : NewFD->parameters()) {
10737     QualType PT = Param->getType();
10738 
10739     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10740     // types.
10741     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10742       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10743         QualType ElemTy = PipeTy->getElementType();
10744           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10745             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10746             D.setInvalidType();
10747           }
10748       }
10749     }
10750     // WebAssembly tables can't be used as function parameters.
10751     if (Context.getTargetInfo().getTriple().isWasm()) {
10752       if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10753         Diag(Param->getTypeSpecStartLoc(),
10754              diag::err_wasm_table_as_function_parameter);
10755         D.setInvalidType();
10756       }
10757     }
10758   }
10759 
10760   // Here we have an function template explicit specialization at class scope.
10761   // The actual specialization will be postponed to template instatiation
10762   // time via the ClassScopeFunctionSpecializationDecl node.
10763   if (isDependentClassScopeExplicitSpecialization) {
10764     ClassScopeFunctionSpecializationDecl *NewSpec =
10765                          ClassScopeFunctionSpecializationDecl::Create(
10766                                 Context, CurContext, NewFD->getLocation(),
10767                                 cast<CXXMethodDecl>(NewFD),
10768                                 HasExplicitTemplateArgs, TemplateArgs);
10769     CurContext->addDecl(NewSpec);
10770     AddToScope = false;
10771   }
10772 
10773   // Diagnose availability attributes. Availability cannot be used on functions
10774   // that are run during load/unload.
10775   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10776     if (NewFD->hasAttr<ConstructorAttr>()) {
10777       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10778           << 1;
10779       NewFD->dropAttr<AvailabilityAttr>();
10780     }
10781     if (NewFD->hasAttr<DestructorAttr>()) {
10782       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10783           << 2;
10784       NewFD->dropAttr<AvailabilityAttr>();
10785     }
10786   }
10787 
10788   // Diagnose no_builtin attribute on function declaration that are not a
10789   // definition.
10790   // FIXME: We should really be doing this in
10791   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10792   // the FunctionDecl and at this point of the code
10793   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10794   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10795   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10796     switch (D.getFunctionDefinitionKind()) {
10797     case FunctionDefinitionKind::Defaulted:
10798     case FunctionDefinitionKind::Deleted:
10799       Diag(NBA->getLocation(),
10800            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10801           << NBA->getSpelling();
10802       break;
10803     case FunctionDefinitionKind::Declaration:
10804       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10805           << NBA->getSpelling();
10806       break;
10807     case FunctionDefinitionKind::Definition:
10808       break;
10809     }
10810 
10811   return NewFD;
10812 }
10813 
10814 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10815 /// when __declspec(code_seg) "is applied to a class, all member functions of
10816 /// the class and nested classes -- this includes compiler-generated special
10817 /// member functions -- are put in the specified segment."
10818 /// The actual behavior is a little more complicated. The Microsoft compiler
10819 /// won't check outer classes if there is an active value from #pragma code_seg.
10820 /// The CodeSeg is always applied from the direct parent but only from outer
10821 /// classes when the #pragma code_seg stack is empty. See:
10822 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10823 /// available since MS has removed the page.
10824 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10825   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10826   if (!Method)
10827     return nullptr;
10828   const CXXRecordDecl *Parent = Method->getParent();
10829   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10830     Attr *NewAttr = SAttr->clone(S.getASTContext());
10831     NewAttr->setImplicit(true);
10832     return NewAttr;
10833   }
10834 
10835   // The Microsoft compiler won't check outer classes for the CodeSeg
10836   // when the #pragma code_seg stack is active.
10837   if (S.CodeSegStack.CurrentValue)
10838    return nullptr;
10839 
10840   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10841     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10842       Attr *NewAttr = SAttr->clone(S.getASTContext());
10843       NewAttr->setImplicit(true);
10844       return NewAttr;
10845     }
10846   }
10847   return nullptr;
10848 }
10849 
10850 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10851 /// containing class. Otherwise it will return implicit SectionAttr if the
10852 /// function is a definition and there is an active value on CodeSegStack
10853 /// (from the current #pragma code-seg value).
10854 ///
10855 /// \param FD Function being declared.
10856 /// \param IsDefinition Whether it is a definition or just a declaration.
10857 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10858 ///          nullptr if no attribute should be added.
10859 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10860                                                        bool IsDefinition) {
10861   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10862     return A;
10863   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10864       CodeSegStack.CurrentValue)
10865     return SectionAttr::CreateImplicit(
10866         getASTContext(), CodeSegStack.CurrentValue->getString(),
10867         CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10868   return nullptr;
10869 }
10870 
10871 /// Determines if we can perform a correct type check for \p D as a
10872 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10873 /// best-effort check.
10874 ///
10875 /// \param NewD The new declaration.
10876 /// \param OldD The old declaration.
10877 /// \param NewT The portion of the type of the new declaration to check.
10878 /// \param OldT The portion of the type of the old declaration to check.
10879 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10880                                           QualType NewT, QualType OldT) {
10881   if (!NewD->getLexicalDeclContext()->isDependentContext())
10882     return true;
10883 
10884   // For dependently-typed local extern declarations and friends, we can't
10885   // perform a correct type check in general until instantiation:
10886   //
10887   //   int f();
10888   //   template<typename T> void g() { T f(); }
10889   //
10890   // (valid if g() is only instantiated with T = int).
10891   if (NewT->isDependentType() &&
10892       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10893     return false;
10894 
10895   // Similarly, if the previous declaration was a dependent local extern
10896   // declaration, we don't really know its type yet.
10897   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10898     return false;
10899 
10900   return true;
10901 }
10902 
10903 /// Checks if the new declaration declared in dependent context must be
10904 /// put in the same redeclaration chain as the specified declaration.
10905 ///
10906 /// \param D Declaration that is checked.
10907 /// \param PrevDecl Previous declaration found with proper lookup method for the
10908 ///                 same declaration name.
10909 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10910 ///          belongs to.
10911 ///
10912 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10913   if (!D->getLexicalDeclContext()->isDependentContext())
10914     return true;
10915 
10916   // Don't chain dependent friend function definitions until instantiation, to
10917   // permit cases like
10918   //
10919   //   void func();
10920   //   template<typename T> class C1 { friend void func() {} };
10921   //   template<typename T> class C2 { friend void func() {} };
10922   //
10923   // ... which is valid if only one of C1 and C2 is ever instantiated.
10924   //
10925   // FIXME: This need only apply to function definitions. For now, we proxy
10926   // this by checking for a file-scope function. We do not want this to apply
10927   // to friend declarations nominating member functions, because that gets in
10928   // the way of access checks.
10929   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10930     return false;
10931 
10932   auto *VD = dyn_cast<ValueDecl>(D);
10933   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10934   return !VD || !PrevVD ||
10935          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10936                                         PrevVD->getType());
10937 }
10938 
10939 /// Check the target or target_version attribute of the function for
10940 /// MultiVersion validity.
10941 ///
10942 /// Returns true if there was an error, false otherwise.
10943 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10944   const auto *TA = FD->getAttr<TargetAttr>();
10945   const auto *TVA = FD->getAttr<TargetVersionAttr>();
10946   assert(
10947       (TA || TVA) &&
10948       "MultiVersion candidate requires a target or target_version attribute");
10949   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10950   enum ErrType { Feature = 0, Architecture = 1 };
10951 
10952   if (TA) {
10953     ParsedTargetAttr ParseInfo =
10954         S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10955     if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10956       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10957           << Architecture << ParseInfo.CPU;
10958       return true;
10959     }
10960     for (const auto &Feat : ParseInfo.Features) {
10961       auto BareFeat = StringRef{Feat}.substr(1);
10962       if (Feat[0] == '-') {
10963         S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10964             << Feature << ("no-" + BareFeat).str();
10965         return true;
10966       }
10967 
10968       if (!TargetInfo.validateCpuSupports(BareFeat) ||
10969           !TargetInfo.isValidFeatureName(BareFeat)) {
10970         S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10971             << Feature << BareFeat;
10972         return true;
10973       }
10974     }
10975   }
10976 
10977   if (TVA) {
10978     llvm::SmallVector<StringRef, 8> Feats;
10979     TVA->getFeatures(Feats);
10980     for (const auto &Feat : Feats) {
10981       if (!TargetInfo.validateCpuSupports(Feat)) {
10982         S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10983             << Feature << Feat;
10984         return true;
10985       }
10986     }
10987   }
10988   return false;
10989 }
10990 
10991 // Provide a white-list of attributes that are allowed to be combined with
10992 // multiversion functions.
10993 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10994                                            MultiVersionKind MVKind) {
10995   // Note: this list/diagnosis must match the list in
10996   // checkMultiversionAttributesAllSame.
10997   switch (Kind) {
10998   default:
10999     return false;
11000   case attr::Used:
11001     return MVKind == MultiVersionKind::Target;
11002   case attr::NonNull:
11003   case attr::NoThrow:
11004     return true;
11005   }
11006 }
11007 
11008 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11009                                                  const FunctionDecl *FD,
11010                                                  const FunctionDecl *CausedFD,
11011                                                  MultiVersionKind MVKind) {
11012   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11013     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11014         << static_cast<unsigned>(MVKind) << A;
11015     if (CausedFD)
11016       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11017     return true;
11018   };
11019 
11020   for (const Attr *A : FD->attrs()) {
11021     switch (A->getKind()) {
11022     case attr::CPUDispatch:
11023     case attr::CPUSpecific:
11024       if (MVKind != MultiVersionKind::CPUDispatch &&
11025           MVKind != MultiVersionKind::CPUSpecific)
11026         return Diagnose(S, A);
11027       break;
11028     case attr::Target:
11029       if (MVKind != MultiVersionKind::Target)
11030         return Diagnose(S, A);
11031       break;
11032     case attr::TargetVersion:
11033       if (MVKind != MultiVersionKind::TargetVersion)
11034         return Diagnose(S, A);
11035       break;
11036     case attr::TargetClones:
11037       if (MVKind != MultiVersionKind::TargetClones)
11038         return Diagnose(S, A);
11039       break;
11040     default:
11041       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11042         return Diagnose(S, A);
11043       break;
11044     }
11045   }
11046   return false;
11047 }
11048 
11049 bool Sema::areMultiversionVariantFunctionsCompatible(
11050     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11051     const PartialDiagnostic &NoProtoDiagID,
11052     const PartialDiagnosticAt &NoteCausedDiagIDAt,
11053     const PartialDiagnosticAt &NoSupportDiagIDAt,
11054     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11055     bool ConstexprSupported, bool CLinkageMayDiffer) {
11056   enum DoesntSupport {
11057     FuncTemplates = 0,
11058     VirtFuncs = 1,
11059     DeducedReturn = 2,
11060     Constructors = 3,
11061     Destructors = 4,
11062     DeletedFuncs = 5,
11063     DefaultedFuncs = 6,
11064     ConstexprFuncs = 7,
11065     ConstevalFuncs = 8,
11066     Lambda = 9,
11067   };
11068   enum Different {
11069     CallingConv = 0,
11070     ReturnType = 1,
11071     ConstexprSpec = 2,
11072     InlineSpec = 3,
11073     Linkage = 4,
11074     LanguageLinkage = 5,
11075   };
11076 
11077   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11078       !OldFD->getType()->getAs<FunctionProtoType>()) {
11079     Diag(OldFD->getLocation(), NoProtoDiagID);
11080     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11081     return true;
11082   }
11083 
11084   if (NoProtoDiagID.getDiagID() != 0 &&
11085       !NewFD->getType()->getAs<FunctionProtoType>())
11086     return Diag(NewFD->getLocation(), NoProtoDiagID);
11087 
11088   if (!TemplatesSupported &&
11089       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11090     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11091            << FuncTemplates;
11092 
11093   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11094     if (NewCXXFD->isVirtual())
11095       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11096              << VirtFuncs;
11097 
11098     if (isa<CXXConstructorDecl>(NewCXXFD))
11099       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11100              << Constructors;
11101 
11102     if (isa<CXXDestructorDecl>(NewCXXFD))
11103       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11104              << Destructors;
11105   }
11106 
11107   if (NewFD->isDeleted())
11108     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11109            << DeletedFuncs;
11110 
11111   if (NewFD->isDefaulted())
11112     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11113            << DefaultedFuncs;
11114 
11115   if (!ConstexprSupported && NewFD->isConstexpr())
11116     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11117            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11118 
11119   QualType NewQType = Context.getCanonicalType(NewFD->getType());
11120   const auto *NewType = cast<FunctionType>(NewQType);
11121   QualType NewReturnType = NewType->getReturnType();
11122 
11123   if (NewReturnType->isUndeducedType())
11124     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11125            << DeducedReturn;
11126 
11127   // Ensure the return type is identical.
11128   if (OldFD) {
11129     QualType OldQType = Context.getCanonicalType(OldFD->getType());
11130     const auto *OldType = cast<FunctionType>(OldQType);
11131     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11132     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11133 
11134     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11135       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11136 
11137     QualType OldReturnType = OldType->getReturnType();
11138 
11139     if (OldReturnType != NewReturnType)
11140       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11141 
11142     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11143       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11144 
11145     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11146       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11147 
11148     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11149       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11150 
11151     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11152       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11153 
11154     if (CheckEquivalentExceptionSpec(
11155             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11156             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11157       return true;
11158   }
11159   return false;
11160 }
11161 
11162 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11163                                              const FunctionDecl *NewFD,
11164                                              bool CausesMV,
11165                                              MultiVersionKind MVKind) {
11166   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11167     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11168     if (OldFD)
11169       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11170     return true;
11171   }
11172 
11173   bool IsCPUSpecificCPUDispatchMVKind =
11174       MVKind == MultiVersionKind::CPUDispatch ||
11175       MVKind == MultiVersionKind::CPUSpecific;
11176 
11177   if (CausesMV && OldFD &&
11178       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11179     return true;
11180 
11181   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11182     return true;
11183 
11184   // Only allow transition to MultiVersion if it hasn't been used.
11185   if (OldFD && CausesMV && OldFD->isUsed(false))
11186     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11187 
11188   return S.areMultiversionVariantFunctionsCompatible(
11189       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11190       PartialDiagnosticAt(NewFD->getLocation(),
11191                           S.PDiag(diag::note_multiversioning_caused_here)),
11192       PartialDiagnosticAt(NewFD->getLocation(),
11193                           S.PDiag(diag::err_multiversion_doesnt_support)
11194                               << static_cast<unsigned>(MVKind)),
11195       PartialDiagnosticAt(NewFD->getLocation(),
11196                           S.PDiag(diag::err_multiversion_diff)),
11197       /*TemplatesSupported=*/false,
11198       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11199       /*CLinkageMayDiffer=*/false);
11200 }
11201 
11202 /// Check the validity of a multiversion function declaration that is the
11203 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11204 ///
11205 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11206 ///
11207 /// Returns true if there was an error, false otherwise.
11208 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11209   MultiVersionKind MVKind = FD->getMultiVersionKind();
11210   assert(MVKind != MultiVersionKind::None &&
11211          "Function lacks multiversion attribute");
11212   const auto *TA = FD->getAttr<TargetAttr>();
11213   const auto *TVA = FD->getAttr<TargetVersionAttr>();
11214   // Target and target_version only causes MV if it is default, otherwise this
11215   // is a normal function.
11216   if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11217     return false;
11218 
11219   if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11220     FD->setInvalidDecl();
11221     return true;
11222   }
11223 
11224   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11225     FD->setInvalidDecl();
11226     return true;
11227   }
11228 
11229   FD->setIsMultiVersion();
11230   return false;
11231 }
11232 
11233 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11234   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11235     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11236       return true;
11237   }
11238 
11239   return false;
11240 }
11241 
11242 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11243                                              FunctionDecl *NewFD,
11244                                              bool &Redeclaration,
11245                                              NamedDecl *&OldDecl,
11246                                              LookupResult &Previous) {
11247   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11248   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11249   const auto *OldTA = OldFD->getAttr<TargetAttr>();
11250   const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11251   // If the old decl is NOT MultiVersioned yet, and we don't cause that
11252   // to change, this is a simple redeclaration.
11253   if ((NewTA && !NewTA->isDefaultVersion() &&
11254        (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11255       (NewTVA && !NewTVA->isDefaultVersion() &&
11256        (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11257     return false;
11258 
11259   // Otherwise, this decl causes MultiVersioning.
11260   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11261                                        NewTVA ? MultiVersionKind::TargetVersion
11262                                               : MultiVersionKind::Target)) {
11263     NewFD->setInvalidDecl();
11264     return true;
11265   }
11266 
11267   if (CheckMultiVersionValue(S, NewFD)) {
11268     NewFD->setInvalidDecl();
11269     return true;
11270   }
11271 
11272   // If this is 'default', permit the forward declaration.
11273   if (!OldFD->isMultiVersion() &&
11274       ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11275        (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11276     Redeclaration = true;
11277     OldDecl = OldFD;
11278     OldFD->setIsMultiVersion();
11279     NewFD->setIsMultiVersion();
11280     return false;
11281   }
11282 
11283   if (CheckMultiVersionValue(S, OldFD)) {
11284     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11285     NewFD->setInvalidDecl();
11286     return true;
11287   }
11288 
11289   if (NewTA) {
11290     ParsedTargetAttr OldParsed =
11291         S.getASTContext().getTargetInfo().parseTargetAttr(
11292             OldTA->getFeaturesStr());
11293     llvm::sort(OldParsed.Features);
11294     ParsedTargetAttr NewParsed =
11295         S.getASTContext().getTargetInfo().parseTargetAttr(
11296             NewTA->getFeaturesStr());
11297     // Sort order doesn't matter, it just needs to be consistent.
11298     llvm::sort(NewParsed.Features);
11299     if (OldParsed == NewParsed) {
11300       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11301       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11302       NewFD->setInvalidDecl();
11303       return true;
11304     }
11305   }
11306 
11307   if (NewTVA) {
11308     llvm::SmallVector<StringRef, 8> Feats;
11309     OldTVA->getFeatures(Feats);
11310     llvm::sort(Feats);
11311     llvm::SmallVector<StringRef, 8> NewFeats;
11312     NewTVA->getFeatures(NewFeats);
11313     llvm::sort(NewFeats);
11314 
11315     if (Feats == NewFeats) {
11316       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11317       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11318       NewFD->setInvalidDecl();
11319       return true;
11320     }
11321   }
11322 
11323   for (const auto *FD : OldFD->redecls()) {
11324     const auto *CurTA = FD->getAttr<TargetAttr>();
11325     const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11326     // We allow forward declarations before ANY multiversioning attributes, but
11327     // nothing after the fact.
11328     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11329         ((NewTA && (!CurTA || CurTA->isInherited())) ||
11330          (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11331       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11332           << (NewTA ? 0 : 2);
11333       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11334       NewFD->setInvalidDecl();
11335       return true;
11336     }
11337   }
11338 
11339   OldFD->setIsMultiVersion();
11340   NewFD->setIsMultiVersion();
11341   Redeclaration = false;
11342   OldDecl = nullptr;
11343   Previous.clear();
11344   return false;
11345 }
11346 
11347 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11348                                         MultiVersionKind New) {
11349   if (Old == New || Old == MultiVersionKind::None ||
11350       New == MultiVersionKind::None)
11351     return true;
11352 
11353   return (Old == MultiVersionKind::CPUDispatch &&
11354           New == MultiVersionKind::CPUSpecific) ||
11355          (Old == MultiVersionKind::CPUSpecific &&
11356           New == MultiVersionKind::CPUDispatch);
11357 }
11358 
11359 /// Check the validity of a new function declaration being added to an existing
11360 /// multiversioned declaration collection.
11361 static bool CheckMultiVersionAdditionalDecl(
11362     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11363     MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11364     const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11365     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11366   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11367   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11368   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11369   // Disallow mixing of multiversioning types.
11370   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11371     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11372     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11373     NewFD->setInvalidDecl();
11374     return true;
11375   }
11376 
11377   ParsedTargetAttr NewParsed;
11378   if (NewTA) {
11379     NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11380         NewTA->getFeaturesStr());
11381     llvm::sort(NewParsed.Features);
11382   }
11383   llvm::SmallVector<StringRef, 8> NewFeats;
11384   if (NewTVA) {
11385     NewTVA->getFeatures(NewFeats);
11386     llvm::sort(NewFeats);
11387   }
11388 
11389   bool UseMemberUsingDeclRules =
11390       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11391 
11392   bool MayNeedOverloadableChecks =
11393       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11394 
11395   // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11396   // of a previous member of the MultiVersion set.
11397   for (NamedDecl *ND : Previous) {
11398     FunctionDecl *CurFD = ND->getAsFunction();
11399     if (!CurFD || CurFD->isInvalidDecl())
11400       continue;
11401     if (MayNeedOverloadableChecks &&
11402         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11403       continue;
11404 
11405     if (NewMVKind == MultiVersionKind::None &&
11406         OldMVKind == MultiVersionKind::TargetVersion) {
11407       NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11408           S.Context, "default", NewFD->getSourceRange()));
11409       NewFD->setIsMultiVersion();
11410       NewMVKind = MultiVersionKind::TargetVersion;
11411       if (!NewTVA) {
11412         NewTVA = NewFD->getAttr<TargetVersionAttr>();
11413         NewTVA->getFeatures(NewFeats);
11414         llvm::sort(NewFeats);
11415       }
11416     }
11417 
11418     switch (NewMVKind) {
11419     case MultiVersionKind::None:
11420       assert(OldMVKind == MultiVersionKind::TargetClones &&
11421              "Only target_clones can be omitted in subsequent declarations");
11422       break;
11423     case MultiVersionKind::Target: {
11424       const auto *CurTA = CurFD->getAttr<TargetAttr>();
11425       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11426         NewFD->setIsMultiVersion();
11427         Redeclaration = true;
11428         OldDecl = ND;
11429         return false;
11430       }
11431 
11432       ParsedTargetAttr CurParsed =
11433           S.getASTContext().getTargetInfo().parseTargetAttr(
11434               CurTA->getFeaturesStr());
11435       llvm::sort(CurParsed.Features);
11436       if (CurParsed == NewParsed) {
11437         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11438         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11439         NewFD->setInvalidDecl();
11440         return true;
11441       }
11442       break;
11443     }
11444     case MultiVersionKind::TargetVersion: {
11445       const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11446       if (CurTVA->getName() == NewTVA->getName()) {
11447         NewFD->setIsMultiVersion();
11448         Redeclaration = true;
11449         OldDecl = ND;
11450         return false;
11451       }
11452       llvm::SmallVector<StringRef, 8> CurFeats;
11453       if (CurTVA) {
11454         CurTVA->getFeatures(CurFeats);
11455         llvm::sort(CurFeats);
11456       }
11457       if (CurFeats == NewFeats) {
11458         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11459         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11460         NewFD->setInvalidDecl();
11461         return true;
11462       }
11463       break;
11464     }
11465     case MultiVersionKind::TargetClones: {
11466       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11467       Redeclaration = true;
11468       OldDecl = CurFD;
11469       NewFD->setIsMultiVersion();
11470 
11471       if (CurClones && NewClones &&
11472           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11473            !std::equal(CurClones->featuresStrs_begin(),
11474                        CurClones->featuresStrs_end(),
11475                        NewClones->featuresStrs_begin()))) {
11476         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11477         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11478         NewFD->setInvalidDecl();
11479         return true;
11480       }
11481 
11482       return false;
11483     }
11484     case MultiVersionKind::CPUSpecific:
11485     case MultiVersionKind::CPUDispatch: {
11486       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11487       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11488       // Handle CPUDispatch/CPUSpecific versions.
11489       // Only 1 CPUDispatch function is allowed, this will make it go through
11490       // the redeclaration errors.
11491       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11492           CurFD->hasAttr<CPUDispatchAttr>()) {
11493         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11494             std::equal(
11495                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11496                 NewCPUDisp->cpus_begin(),
11497                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11498                   return Cur->getName() == New->getName();
11499                 })) {
11500           NewFD->setIsMultiVersion();
11501           Redeclaration = true;
11502           OldDecl = ND;
11503           return false;
11504         }
11505 
11506         // If the declarations don't match, this is an error condition.
11507         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11508         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11509         NewFD->setInvalidDecl();
11510         return true;
11511       }
11512       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11513         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11514             std::equal(
11515                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11516                 NewCPUSpec->cpus_begin(),
11517                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11518                   return Cur->getName() == New->getName();
11519                 })) {
11520           NewFD->setIsMultiVersion();
11521           Redeclaration = true;
11522           OldDecl = ND;
11523           return false;
11524         }
11525 
11526         // Only 1 version of CPUSpecific is allowed for each CPU.
11527         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11528           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11529             if (CurII == NewII) {
11530               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11531                   << NewII;
11532               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11533               NewFD->setInvalidDecl();
11534               return true;
11535             }
11536           }
11537         }
11538       }
11539       break;
11540     }
11541     }
11542   }
11543 
11544   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11545   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11546   // handled in the attribute adding step.
11547   if ((NewMVKind == MultiVersionKind::TargetVersion ||
11548        NewMVKind == MultiVersionKind::Target) &&
11549       CheckMultiVersionValue(S, NewFD)) {
11550     NewFD->setInvalidDecl();
11551     return true;
11552   }
11553 
11554   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11555                                        !OldFD->isMultiVersion(), NewMVKind)) {
11556     NewFD->setInvalidDecl();
11557     return true;
11558   }
11559 
11560   // Permit forward declarations in the case where these two are compatible.
11561   if (!OldFD->isMultiVersion()) {
11562     OldFD->setIsMultiVersion();
11563     NewFD->setIsMultiVersion();
11564     Redeclaration = true;
11565     OldDecl = OldFD;
11566     return false;
11567   }
11568 
11569   NewFD->setIsMultiVersion();
11570   Redeclaration = false;
11571   OldDecl = nullptr;
11572   Previous.clear();
11573   return false;
11574 }
11575 
11576 /// Check the validity of a mulitversion function declaration.
11577 /// Also sets the multiversion'ness' of the function itself.
11578 ///
11579 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11580 ///
11581 /// Returns true if there was an error, false otherwise.
11582 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11583                                       bool &Redeclaration, NamedDecl *&OldDecl,
11584                                       LookupResult &Previous) {
11585   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11586   const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11587   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11588   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11589   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11590   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11591 
11592   // Main isn't allowed to become a multiversion function, however it IS
11593   // permitted to have 'main' be marked with the 'target' optimization hint,
11594   // for 'target_version' only default is allowed.
11595   if (NewFD->isMain()) {
11596     if (MVKind != MultiVersionKind::None &&
11597         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11598         !(MVKind == MultiVersionKind::TargetVersion &&
11599           NewTVA->isDefaultVersion())) {
11600       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11601       NewFD->setInvalidDecl();
11602       return true;
11603     }
11604     return false;
11605   }
11606 
11607   // Target attribute on AArch64 is not used for multiversioning
11608   if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11609     return false;
11610 
11611   if (!OldDecl || !OldDecl->getAsFunction() ||
11612       OldDecl->getDeclContext()->getRedeclContext() !=
11613           NewFD->getDeclContext()->getRedeclContext()) {
11614     // If there's no previous declaration, AND this isn't attempting to cause
11615     // multiversioning, this isn't an error condition.
11616     if (MVKind == MultiVersionKind::None)
11617       return false;
11618     return CheckMultiVersionFirstFunction(S, NewFD);
11619   }
11620 
11621   FunctionDecl *OldFD = OldDecl->getAsFunction();
11622 
11623   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11624     // No target_version attributes mean default
11625     if (!NewTVA) {
11626       const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11627       if (OldTVA) {
11628         NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11629             S.Context, "default", NewFD->getSourceRange()));
11630         NewFD->setIsMultiVersion();
11631         OldFD->setIsMultiVersion();
11632         OldDecl = OldFD;
11633         Redeclaration = true;
11634         return true;
11635       }
11636     }
11637     return false;
11638   }
11639 
11640   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11641   // for target_clones and target_version.
11642   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11643       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11644       OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11645     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11646         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11647     NewFD->setInvalidDecl();
11648     return true;
11649   }
11650 
11651   if (!OldFD->isMultiVersion()) {
11652     switch (MVKind) {
11653     case MultiVersionKind::Target:
11654     case MultiVersionKind::TargetVersion:
11655       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11656                                               OldDecl, Previous);
11657     case MultiVersionKind::TargetClones:
11658       if (OldFD->isUsed(false)) {
11659         NewFD->setInvalidDecl();
11660         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11661       }
11662       OldFD->setIsMultiVersion();
11663       break;
11664 
11665     case MultiVersionKind::CPUDispatch:
11666     case MultiVersionKind::CPUSpecific:
11667     case MultiVersionKind::None:
11668       break;
11669     }
11670   }
11671 
11672   // At this point, we have a multiversion function decl (in OldFD) AND an
11673   // appropriate attribute in the current function decl.  Resolve that these are
11674   // still compatible with previous declarations.
11675   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11676                                          NewCPUSpec, NewClones, Redeclaration,
11677                                          OldDecl, Previous);
11678 }
11679 
11680 /// Perform semantic checking of a new function declaration.
11681 ///
11682 /// Performs semantic analysis of the new function declaration
11683 /// NewFD. This routine performs all semantic checking that does not
11684 /// require the actual declarator involved in the declaration, and is
11685 /// used both for the declaration of functions as they are parsed
11686 /// (called via ActOnDeclarator) and for the declaration of functions
11687 /// that have been instantiated via C++ template instantiation (called
11688 /// via InstantiateDecl).
11689 ///
11690 /// \param IsMemberSpecialization whether this new function declaration is
11691 /// a member specialization (that replaces any definition provided by the
11692 /// previous declaration).
11693 ///
11694 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11695 ///
11696 /// \returns true if the function declaration is a redeclaration.
11697 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11698                                     LookupResult &Previous,
11699                                     bool IsMemberSpecialization,
11700                                     bool DeclIsDefn) {
11701   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11702          "Variably modified return types are not handled here");
11703 
11704   // Determine whether the type of this function should be merged with
11705   // a previous visible declaration. This never happens for functions in C++,
11706   // and always happens in C if the previous declaration was visible.
11707   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11708                                !Previous.isShadowed();
11709 
11710   bool Redeclaration = false;
11711   NamedDecl *OldDecl = nullptr;
11712   bool MayNeedOverloadableChecks = false;
11713 
11714   // Merge or overload the declaration with an existing declaration of
11715   // the same name, if appropriate.
11716   if (!Previous.empty()) {
11717     // Determine whether NewFD is an overload of PrevDecl or
11718     // a declaration that requires merging. If it's an overload,
11719     // there's no more work to do here; we'll just add the new
11720     // function to the scope.
11721     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11722       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11723       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11724         Redeclaration = true;
11725         OldDecl = Candidate;
11726       }
11727     } else {
11728       MayNeedOverloadableChecks = true;
11729       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11730                             /*NewIsUsingDecl*/ false)) {
11731       case Ovl_Match:
11732         Redeclaration = true;
11733         break;
11734 
11735       case Ovl_NonFunction:
11736         Redeclaration = true;
11737         break;
11738 
11739       case Ovl_Overload:
11740         Redeclaration = false;
11741         break;
11742       }
11743     }
11744   }
11745 
11746   // Check for a previous extern "C" declaration with this name.
11747   if (!Redeclaration &&
11748       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11749     if (!Previous.empty()) {
11750       // This is an extern "C" declaration with the same name as a previous
11751       // declaration, and thus redeclares that entity...
11752       Redeclaration = true;
11753       OldDecl = Previous.getFoundDecl();
11754       MergeTypeWithPrevious = false;
11755 
11756       // ... except in the presence of __attribute__((overloadable)).
11757       if (OldDecl->hasAttr<OverloadableAttr>() ||
11758           NewFD->hasAttr<OverloadableAttr>()) {
11759         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11760           MayNeedOverloadableChecks = true;
11761           Redeclaration = false;
11762           OldDecl = nullptr;
11763         }
11764       }
11765     }
11766   }
11767 
11768   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11769     return Redeclaration;
11770 
11771   // PPC MMA non-pointer types are not allowed as function return types.
11772   if (Context.getTargetInfo().getTriple().isPPC64() &&
11773       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11774     NewFD->setInvalidDecl();
11775   }
11776 
11777   // C++11 [dcl.constexpr]p8:
11778   //   A constexpr specifier for a non-static member function that is not
11779   //   a constructor declares that member function to be const.
11780   //
11781   // This needs to be delayed until we know whether this is an out-of-line
11782   // definition of a static member function.
11783   //
11784   // This rule is not present in C++1y, so we produce a backwards
11785   // compatibility warning whenever it happens in C++11.
11786   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11787   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11788       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11789       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11790     CXXMethodDecl *OldMD = nullptr;
11791     if (OldDecl)
11792       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11793     if (!OldMD || !OldMD->isStatic()) {
11794       const FunctionProtoType *FPT =
11795         MD->getType()->castAs<FunctionProtoType>();
11796       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11797       EPI.TypeQuals.addConst();
11798       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11799                                           FPT->getParamTypes(), EPI));
11800 
11801       // Warn that we did this, if we're not performing template instantiation.
11802       // In that case, we'll have warned already when the template was defined.
11803       if (!inTemplateInstantiation()) {
11804         SourceLocation AddConstLoc;
11805         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11806                 .IgnoreParens().getAs<FunctionTypeLoc>())
11807           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11808 
11809         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11810           << FixItHint::CreateInsertion(AddConstLoc, " const");
11811       }
11812     }
11813   }
11814 
11815   if (Redeclaration) {
11816     // NewFD and OldDecl represent declarations that need to be
11817     // merged.
11818     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11819                           DeclIsDefn)) {
11820       NewFD->setInvalidDecl();
11821       return Redeclaration;
11822     }
11823 
11824     Previous.clear();
11825     Previous.addDecl(OldDecl);
11826 
11827     if (FunctionTemplateDecl *OldTemplateDecl =
11828             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11829       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11830       FunctionTemplateDecl *NewTemplateDecl
11831         = NewFD->getDescribedFunctionTemplate();
11832       assert(NewTemplateDecl && "Template/non-template mismatch");
11833 
11834       // The call to MergeFunctionDecl above may have created some state in
11835       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11836       // can add it as a redeclaration.
11837       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11838 
11839       NewFD->setPreviousDeclaration(OldFD);
11840       if (NewFD->isCXXClassMember()) {
11841         NewFD->setAccess(OldTemplateDecl->getAccess());
11842         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11843       }
11844 
11845       // If this is an explicit specialization of a member that is a function
11846       // template, mark it as a member specialization.
11847       if (IsMemberSpecialization &&
11848           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11849         NewTemplateDecl->setMemberSpecialization();
11850         assert(OldTemplateDecl->isMemberSpecialization());
11851         // Explicit specializations of a member template do not inherit deleted
11852         // status from the parent member template that they are specializing.
11853         if (OldFD->isDeleted()) {
11854           // FIXME: This assert will not hold in the presence of modules.
11855           assert(OldFD->getCanonicalDecl() == OldFD);
11856           // FIXME: We need an update record for this AST mutation.
11857           OldFD->setDeletedAsWritten(false);
11858         }
11859       }
11860 
11861     } else {
11862       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11863         auto *OldFD = cast<FunctionDecl>(OldDecl);
11864         // This needs to happen first so that 'inline' propagates.
11865         NewFD->setPreviousDeclaration(OldFD);
11866         if (NewFD->isCXXClassMember())
11867           NewFD->setAccess(OldFD->getAccess());
11868       }
11869     }
11870   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11871              !NewFD->getAttr<OverloadableAttr>()) {
11872     assert((Previous.empty() ||
11873             llvm::any_of(Previous,
11874                          [](const NamedDecl *ND) {
11875                            return ND->hasAttr<OverloadableAttr>();
11876                          })) &&
11877            "Non-redecls shouldn't happen without overloadable present");
11878 
11879     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11880       const auto *FD = dyn_cast<FunctionDecl>(ND);
11881       return FD && !FD->hasAttr<OverloadableAttr>();
11882     });
11883 
11884     if (OtherUnmarkedIter != Previous.end()) {
11885       Diag(NewFD->getLocation(),
11886            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11887       Diag((*OtherUnmarkedIter)->getLocation(),
11888            diag::note_attribute_overloadable_prev_overload)
11889           << false;
11890 
11891       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11892     }
11893   }
11894 
11895   if (LangOpts.OpenMP)
11896     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11897 
11898   // Semantic checking for this function declaration (in isolation).
11899 
11900   if (getLangOpts().CPlusPlus) {
11901     // C++-specific checks.
11902     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11903       CheckConstructor(Constructor);
11904     } else if (CXXDestructorDecl *Destructor =
11905                    dyn_cast<CXXDestructorDecl>(NewFD)) {
11906       // We check here for invalid destructor names.
11907       // If we have a friend destructor declaration that is dependent, we can't
11908       // diagnose right away because cases like this are still valid:
11909       // template <class T> struct A { friend T::X::~Y(); };
11910       // struct B { struct Y { ~Y(); }; using X = Y; };
11911       // template struct A<B>;
11912       if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
11913           !Destructor->getThisType()->isDependentType()) {
11914         CXXRecordDecl *Record = Destructor->getParent();
11915         QualType ClassType = Context.getTypeDeclType(Record);
11916 
11917         DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
11918             Context.getCanonicalType(ClassType));
11919         if (NewFD->getDeclName() != Name) {
11920           Diag(NewFD->getLocation(), diag::err_destructor_name);
11921           NewFD->setInvalidDecl();
11922           return Redeclaration;
11923         }
11924       }
11925     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11926       if (auto *TD = Guide->getDescribedFunctionTemplate())
11927         CheckDeductionGuideTemplate(TD);
11928 
11929       // A deduction guide is not on the list of entities that can be
11930       // explicitly specialized.
11931       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11932         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11933             << /*explicit specialization*/ 1;
11934     }
11935 
11936     // Find any virtual functions that this function overrides.
11937     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11938       if (!Method->isFunctionTemplateSpecialization() &&
11939           !Method->getDescribedFunctionTemplate() &&
11940           Method->isCanonicalDecl()) {
11941         AddOverriddenMethods(Method->getParent(), Method);
11942       }
11943       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11944         // C++2a [class.virtual]p6
11945         // A virtual method shall not have a requires-clause.
11946         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11947              diag::err_constrained_virtual_method);
11948 
11949       if (Method->isStatic())
11950         checkThisInStaticMemberFunctionType(Method);
11951     }
11952 
11953     // C++20: dcl.decl.general p4:
11954     // The optional requires-clause ([temp.pre]) in an init-declarator or
11955     // member-declarator shall be present only if the declarator declares a
11956     // templated function ([dcl.fct]).
11957     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11958       // [temp.pre]/8:
11959       // An entity is templated if it is
11960       // - a template,
11961       // - an entity defined ([basic.def]) or created ([class.temporary]) in a
11962       // templated entity,
11963       // - a member of a templated entity,
11964       // - an enumerator for an enumeration that is a templated entity, or
11965       // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
11966       // appearing in the declaration of a templated entity. [Note 6: A local
11967       // class, a local or block variable, or a friend function defined in a
11968       // templated entity is a templated entity.  — end note]
11969       //
11970       // A templated function is a function template or a function that is
11971       // templated. A templated class is a class template or a class that is
11972       // templated. A templated variable is a variable template or a variable
11973       // that is templated.
11974 
11975       if (!NewFD->getDescribedFunctionTemplate() && // -a template
11976           // defined... in a templated entity
11977           !(DeclIsDefn && NewFD->isTemplated()) &&
11978           // a member of a templated entity
11979           !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
11980           // Don't complain about instantiations, they've already had these
11981           // rules + others enforced.
11982           !NewFD->isTemplateInstantiation()) {
11983         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11984       }
11985     }
11986 
11987     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11988       ActOnConversionDeclarator(Conversion);
11989 
11990     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11991     if (NewFD->isOverloadedOperator() &&
11992         CheckOverloadedOperatorDeclaration(NewFD)) {
11993       NewFD->setInvalidDecl();
11994       return Redeclaration;
11995     }
11996 
11997     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11998     if (NewFD->getLiteralIdentifier() &&
11999         CheckLiteralOperatorDeclaration(NewFD)) {
12000       NewFD->setInvalidDecl();
12001       return Redeclaration;
12002     }
12003 
12004     // In C++, check default arguments now that we have merged decls. Unless
12005     // the lexical context is the class, because in this case this is done
12006     // during delayed parsing anyway.
12007     if (!CurContext->isRecord())
12008       CheckCXXDefaultArguments(NewFD);
12009 
12010     // If this function is declared as being extern "C", then check to see if
12011     // the function returns a UDT (class, struct, or union type) that is not C
12012     // compatible, and if it does, warn the user.
12013     // But, issue any diagnostic on the first declaration only.
12014     if (Previous.empty() && NewFD->isExternC()) {
12015       QualType R = NewFD->getReturnType();
12016       if (R->isIncompleteType() && !R->isVoidType())
12017         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12018             << NewFD << R;
12019       else if (!R.isPODType(Context) && !R->isVoidType() &&
12020                !R->isObjCObjectPointerType())
12021         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12022     }
12023 
12024     // C++1z [dcl.fct]p6:
12025     //   [...] whether the function has a non-throwing exception-specification
12026     //   [is] part of the function type
12027     //
12028     // This results in an ABI break between C++14 and C++17 for functions whose
12029     // declared type includes an exception-specification in a parameter or
12030     // return type. (Exception specifications on the function itself are OK in
12031     // most cases, and exception specifications are not permitted in most other
12032     // contexts where they could make it into a mangling.)
12033     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12034       auto HasNoexcept = [&](QualType T) -> bool {
12035         // Strip off declarator chunks that could be between us and a function
12036         // type. We don't need to look far, exception specifications are very
12037         // restricted prior to C++17.
12038         if (auto *RT = T->getAs<ReferenceType>())
12039           T = RT->getPointeeType();
12040         else if (T->isAnyPointerType())
12041           T = T->getPointeeType();
12042         else if (auto *MPT = T->getAs<MemberPointerType>())
12043           T = MPT->getPointeeType();
12044         if (auto *FPT = T->getAs<FunctionProtoType>())
12045           if (FPT->isNothrow())
12046             return true;
12047         return false;
12048       };
12049 
12050       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12051       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12052       for (QualType T : FPT->param_types())
12053         AnyNoexcept |= HasNoexcept(T);
12054       if (AnyNoexcept)
12055         Diag(NewFD->getLocation(),
12056              diag::warn_cxx17_compat_exception_spec_in_signature)
12057             << NewFD;
12058     }
12059 
12060     if (!Redeclaration && LangOpts.CUDA)
12061       checkCUDATargetOverload(NewFD, Previous);
12062   }
12063   return Redeclaration;
12064 }
12065 
12066 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12067   // C++11 [basic.start.main]p3:
12068   //   A program that [...] declares main to be inline, static or
12069   //   constexpr is ill-formed.
12070   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
12071   //   appear in a declaration of main.
12072   // static main is not an error under C99, but we should warn about it.
12073   // We accept _Noreturn main as an extension.
12074   if (FD->getStorageClass() == SC_Static)
12075     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12076          ? diag::err_static_main : diag::warn_static_main)
12077       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12078   if (FD->isInlineSpecified())
12079     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12080       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12081   if (DS.isNoreturnSpecified()) {
12082     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12083     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12084     Diag(NoreturnLoc, diag::ext_noreturn_main);
12085     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12086       << FixItHint::CreateRemoval(NoreturnRange);
12087   }
12088   if (FD->isConstexpr()) {
12089     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12090         << FD->isConsteval()
12091         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12092     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12093   }
12094 
12095   if (getLangOpts().OpenCL) {
12096     Diag(FD->getLocation(), diag::err_opencl_no_main)
12097         << FD->hasAttr<OpenCLKernelAttr>();
12098     FD->setInvalidDecl();
12099     return;
12100   }
12101 
12102   // Functions named main in hlsl are default entries, but don't have specific
12103   // signatures they are required to conform to.
12104   if (getLangOpts().HLSL)
12105     return;
12106 
12107   QualType T = FD->getType();
12108   assert(T->isFunctionType() && "function decl is not of function type");
12109   const FunctionType* FT = T->castAs<FunctionType>();
12110 
12111   // Set default calling convention for main()
12112   if (FT->getCallConv() != CC_C) {
12113     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12114     FD->setType(QualType(FT, 0));
12115     T = Context.getCanonicalType(FD->getType());
12116   }
12117 
12118   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12119     // In C with GNU extensions we allow main() to have non-integer return
12120     // type, but we should warn about the extension, and we disable the
12121     // implicit-return-zero rule.
12122 
12123     // GCC in C mode accepts qualified 'int'.
12124     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12125       FD->setHasImplicitReturnZero(true);
12126     else {
12127       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12128       SourceRange RTRange = FD->getReturnTypeSourceRange();
12129       if (RTRange.isValid())
12130         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12131             << FixItHint::CreateReplacement(RTRange, "int");
12132     }
12133   } else {
12134     // In C and C++, main magically returns 0 if you fall off the end;
12135     // set the flag which tells us that.
12136     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12137 
12138     // All the standards say that main() should return 'int'.
12139     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12140       FD->setHasImplicitReturnZero(true);
12141     else {
12142       // Otherwise, this is just a flat-out error.
12143       SourceRange RTRange = FD->getReturnTypeSourceRange();
12144       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12145           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12146                                 : FixItHint());
12147       FD->setInvalidDecl(true);
12148     }
12149   }
12150 
12151   // Treat protoless main() as nullary.
12152   if (isa<FunctionNoProtoType>(FT)) return;
12153 
12154   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12155   unsigned nparams = FTP->getNumParams();
12156   assert(FD->getNumParams() == nparams);
12157 
12158   bool HasExtraParameters = (nparams > 3);
12159 
12160   if (FTP->isVariadic()) {
12161     Diag(FD->getLocation(), diag::ext_variadic_main);
12162     // FIXME: if we had information about the location of the ellipsis, we
12163     // could add a FixIt hint to remove it as a parameter.
12164   }
12165 
12166   // Darwin passes an undocumented fourth argument of type char**.  If
12167   // other platforms start sprouting these, the logic below will start
12168   // getting shifty.
12169   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12170     HasExtraParameters = false;
12171 
12172   if (HasExtraParameters) {
12173     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12174     FD->setInvalidDecl(true);
12175     nparams = 3;
12176   }
12177 
12178   // FIXME: a lot of the following diagnostics would be improved
12179   // if we had some location information about types.
12180 
12181   QualType CharPP =
12182     Context.getPointerType(Context.getPointerType(Context.CharTy));
12183   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12184 
12185   for (unsigned i = 0; i < nparams; ++i) {
12186     QualType AT = FTP->getParamType(i);
12187 
12188     bool mismatch = true;
12189 
12190     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12191       mismatch = false;
12192     else if (Expected[i] == CharPP) {
12193       // As an extension, the following forms are okay:
12194       //   char const **
12195       //   char const * const *
12196       //   char * const *
12197 
12198       QualifierCollector qs;
12199       const PointerType* PT;
12200       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12201           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12202           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12203                               Context.CharTy)) {
12204         qs.removeConst();
12205         mismatch = !qs.empty();
12206       }
12207     }
12208 
12209     if (mismatch) {
12210       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12211       // TODO: suggest replacing given type with expected type
12212       FD->setInvalidDecl(true);
12213     }
12214   }
12215 
12216   if (nparams == 1 && !FD->isInvalidDecl()) {
12217     Diag(FD->getLocation(), diag::warn_main_one_arg);
12218   }
12219 
12220   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12221     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12222     FD->setInvalidDecl();
12223   }
12224 }
12225 
12226 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12227 
12228   // Default calling convention for main and wmain is __cdecl
12229   if (FD->getName() == "main" || FD->getName() == "wmain")
12230     return false;
12231 
12232   // Default calling convention for MinGW is __cdecl
12233   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12234   if (T.isWindowsGNUEnvironment())
12235     return false;
12236 
12237   // Default calling convention for WinMain, wWinMain and DllMain
12238   // is __stdcall on 32 bit Windows
12239   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12240     return true;
12241 
12242   return false;
12243 }
12244 
12245 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12246   QualType T = FD->getType();
12247   assert(T->isFunctionType() && "function decl is not of function type");
12248   const FunctionType *FT = T->castAs<FunctionType>();
12249 
12250   // Set an implicit return of 'zero' if the function can return some integral,
12251   // enumeration, pointer or nullptr type.
12252   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12253       FT->getReturnType()->isAnyPointerType() ||
12254       FT->getReturnType()->isNullPtrType())
12255     // DllMain is exempt because a return value of zero means it failed.
12256     if (FD->getName() != "DllMain")
12257       FD->setHasImplicitReturnZero(true);
12258 
12259   // Explicity specified calling conventions are applied to MSVC entry points
12260   if (!hasExplicitCallingConv(T)) {
12261     if (isDefaultStdCall(FD, *this)) {
12262       if (FT->getCallConv() != CC_X86StdCall) {
12263         FT = Context.adjustFunctionType(
12264             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12265         FD->setType(QualType(FT, 0));
12266       }
12267     } else if (FT->getCallConv() != CC_C) {
12268       FT = Context.adjustFunctionType(FT,
12269                                       FT->getExtInfo().withCallingConv(CC_C));
12270       FD->setType(QualType(FT, 0));
12271     }
12272   }
12273 
12274   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12275     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12276     FD->setInvalidDecl();
12277   }
12278 }
12279 
12280 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12281   auto &TargetInfo = getASTContext().getTargetInfo();
12282   auto const Triple = TargetInfo.getTriple();
12283   switch (Triple.getEnvironment()) {
12284   default:
12285     // FIXME: check all shader profiles.
12286     break;
12287   case llvm::Triple::EnvironmentType::Compute:
12288     if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12289       Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12290           << Triple.getEnvironmentName();
12291       FD->setInvalidDecl();
12292     }
12293     break;
12294   }
12295 
12296   for (const auto *Param : FD->parameters()) {
12297     if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12298       // FIXME: Handle struct parameters where annotations are on struct fields.
12299       // See: https://github.com/llvm/llvm-project/issues/57875
12300       Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12301       Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12302       FD->setInvalidDecl();
12303     }
12304   }
12305   // FIXME: Verify return type semantic annotation.
12306 }
12307 
12308 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12309   // FIXME: Need strict checking.  In C89, we need to check for
12310   // any assignment, increment, decrement, function-calls, or
12311   // commas outside of a sizeof.  In C99, it's the same list,
12312   // except that the aforementioned are allowed in unevaluated
12313   // expressions.  Everything else falls under the
12314   // "may accept other forms of constant expressions" exception.
12315   //
12316   // Regular C++ code will not end up here (exceptions: language extensions,
12317   // OpenCL C++ etc), so the constant expression rules there don't matter.
12318   if (Init->isValueDependent()) {
12319     assert(Init->containsErrors() &&
12320            "Dependent code should only occur in error-recovery path.");
12321     return true;
12322   }
12323   const Expr *Culprit;
12324   if (Init->isConstantInitializer(Context, false, &Culprit))
12325     return false;
12326   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12327     << Culprit->getSourceRange();
12328   return true;
12329 }
12330 
12331 namespace {
12332   // Visits an initialization expression to see if OrigDecl is evaluated in
12333   // its own initialization and throws a warning if it does.
12334   class SelfReferenceChecker
12335       : public EvaluatedExprVisitor<SelfReferenceChecker> {
12336     Sema &S;
12337     Decl *OrigDecl;
12338     bool isRecordType;
12339     bool isPODType;
12340     bool isReferenceType;
12341 
12342     bool isInitList;
12343     llvm::SmallVector<unsigned, 4> InitFieldIndex;
12344 
12345   public:
12346     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12347 
12348     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12349                                                     S(S), OrigDecl(OrigDecl) {
12350       isPODType = false;
12351       isRecordType = false;
12352       isReferenceType = false;
12353       isInitList = false;
12354       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12355         isPODType = VD->getType().isPODType(S.Context);
12356         isRecordType = VD->getType()->isRecordType();
12357         isReferenceType = VD->getType()->isReferenceType();
12358       }
12359     }
12360 
12361     // For most expressions, just call the visitor.  For initializer lists,
12362     // track the index of the field being initialized since fields are
12363     // initialized in order allowing use of previously initialized fields.
12364     void CheckExpr(Expr *E) {
12365       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12366       if (!InitList) {
12367         Visit(E);
12368         return;
12369       }
12370 
12371       // Track and increment the index here.
12372       isInitList = true;
12373       InitFieldIndex.push_back(0);
12374       for (auto *Child : InitList->children()) {
12375         CheckExpr(cast<Expr>(Child));
12376         ++InitFieldIndex.back();
12377       }
12378       InitFieldIndex.pop_back();
12379     }
12380 
12381     // Returns true if MemberExpr is checked and no further checking is needed.
12382     // Returns false if additional checking is required.
12383     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12384       llvm::SmallVector<FieldDecl*, 4> Fields;
12385       Expr *Base = E;
12386       bool ReferenceField = false;
12387 
12388       // Get the field members used.
12389       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12390         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12391         if (!FD)
12392           return false;
12393         Fields.push_back(FD);
12394         if (FD->getType()->isReferenceType())
12395           ReferenceField = true;
12396         Base = ME->getBase()->IgnoreParenImpCasts();
12397       }
12398 
12399       // Keep checking only if the base Decl is the same.
12400       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12401       if (!DRE || DRE->getDecl() != OrigDecl)
12402         return false;
12403 
12404       // A reference field can be bound to an unininitialized field.
12405       if (CheckReference && !ReferenceField)
12406         return true;
12407 
12408       // Convert FieldDecls to their index number.
12409       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12410       for (const FieldDecl *I : llvm::reverse(Fields))
12411         UsedFieldIndex.push_back(I->getFieldIndex());
12412 
12413       // See if a warning is needed by checking the first difference in index
12414       // numbers.  If field being used has index less than the field being
12415       // initialized, then the use is safe.
12416       for (auto UsedIter = UsedFieldIndex.begin(),
12417                 UsedEnd = UsedFieldIndex.end(),
12418                 OrigIter = InitFieldIndex.begin(),
12419                 OrigEnd = InitFieldIndex.end();
12420            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12421         if (*UsedIter < *OrigIter)
12422           return true;
12423         if (*UsedIter > *OrigIter)
12424           break;
12425       }
12426 
12427       // TODO: Add a different warning which will print the field names.
12428       HandleDeclRefExpr(DRE);
12429       return true;
12430     }
12431 
12432     // For most expressions, the cast is directly above the DeclRefExpr.
12433     // For conditional operators, the cast can be outside the conditional
12434     // operator if both expressions are DeclRefExpr's.
12435     void HandleValue(Expr *E) {
12436       E = E->IgnoreParens();
12437       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12438         HandleDeclRefExpr(DRE);
12439         return;
12440       }
12441 
12442       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12443         Visit(CO->getCond());
12444         HandleValue(CO->getTrueExpr());
12445         HandleValue(CO->getFalseExpr());
12446         return;
12447       }
12448 
12449       if (BinaryConditionalOperator *BCO =
12450               dyn_cast<BinaryConditionalOperator>(E)) {
12451         Visit(BCO->getCond());
12452         HandleValue(BCO->getFalseExpr());
12453         return;
12454       }
12455 
12456       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12457         HandleValue(OVE->getSourceExpr());
12458         return;
12459       }
12460 
12461       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12462         if (BO->getOpcode() == BO_Comma) {
12463           Visit(BO->getLHS());
12464           HandleValue(BO->getRHS());
12465           return;
12466         }
12467       }
12468 
12469       if (isa<MemberExpr>(E)) {
12470         if (isInitList) {
12471           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12472                                       false /*CheckReference*/))
12473             return;
12474         }
12475 
12476         Expr *Base = E->IgnoreParenImpCasts();
12477         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12478           // Check for static member variables and don't warn on them.
12479           if (!isa<FieldDecl>(ME->getMemberDecl()))
12480             return;
12481           Base = ME->getBase()->IgnoreParenImpCasts();
12482         }
12483         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12484           HandleDeclRefExpr(DRE);
12485         return;
12486       }
12487 
12488       Visit(E);
12489     }
12490 
12491     // Reference types not handled in HandleValue are handled here since all
12492     // uses of references are bad, not just r-value uses.
12493     void VisitDeclRefExpr(DeclRefExpr *E) {
12494       if (isReferenceType)
12495         HandleDeclRefExpr(E);
12496     }
12497 
12498     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12499       if (E->getCastKind() == CK_LValueToRValue) {
12500         HandleValue(E->getSubExpr());
12501         return;
12502       }
12503 
12504       Inherited::VisitImplicitCastExpr(E);
12505     }
12506 
12507     void VisitMemberExpr(MemberExpr *E) {
12508       if (isInitList) {
12509         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12510           return;
12511       }
12512 
12513       // Don't warn on arrays since they can be treated as pointers.
12514       if (E->getType()->canDecayToPointerType()) return;
12515 
12516       // Warn when a non-static method call is followed by non-static member
12517       // field accesses, which is followed by a DeclRefExpr.
12518       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12519       bool Warn = (MD && !MD->isStatic());
12520       Expr *Base = E->getBase()->IgnoreParenImpCasts();
12521       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12522         if (!isa<FieldDecl>(ME->getMemberDecl()))
12523           Warn = false;
12524         Base = ME->getBase()->IgnoreParenImpCasts();
12525       }
12526 
12527       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12528         if (Warn)
12529           HandleDeclRefExpr(DRE);
12530         return;
12531       }
12532 
12533       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12534       // Visit that expression.
12535       Visit(Base);
12536     }
12537 
12538     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12539       Expr *Callee = E->getCallee();
12540 
12541       if (isa<UnresolvedLookupExpr>(Callee))
12542         return Inherited::VisitCXXOperatorCallExpr(E);
12543 
12544       Visit(Callee);
12545       for (auto Arg: E->arguments())
12546         HandleValue(Arg->IgnoreParenImpCasts());
12547     }
12548 
12549     void VisitUnaryOperator(UnaryOperator *E) {
12550       // For POD record types, addresses of its own members are well-defined.
12551       if (E->getOpcode() == UO_AddrOf && isRecordType &&
12552           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12553         if (!isPODType)
12554           HandleValue(E->getSubExpr());
12555         return;
12556       }
12557 
12558       if (E->isIncrementDecrementOp()) {
12559         HandleValue(E->getSubExpr());
12560         return;
12561       }
12562 
12563       Inherited::VisitUnaryOperator(E);
12564     }
12565 
12566     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12567 
12568     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12569       if (E->getConstructor()->isCopyConstructor()) {
12570         Expr *ArgExpr = E->getArg(0);
12571         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12572           if (ILE->getNumInits() == 1)
12573             ArgExpr = ILE->getInit(0);
12574         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12575           if (ICE->getCastKind() == CK_NoOp)
12576             ArgExpr = ICE->getSubExpr();
12577         HandleValue(ArgExpr);
12578         return;
12579       }
12580       Inherited::VisitCXXConstructExpr(E);
12581     }
12582 
12583     void VisitCallExpr(CallExpr *E) {
12584       // Treat std::move as a use.
12585       if (E->isCallToStdMove()) {
12586         HandleValue(E->getArg(0));
12587         return;
12588       }
12589 
12590       Inherited::VisitCallExpr(E);
12591     }
12592 
12593     void VisitBinaryOperator(BinaryOperator *E) {
12594       if (E->isCompoundAssignmentOp()) {
12595         HandleValue(E->getLHS());
12596         Visit(E->getRHS());
12597         return;
12598       }
12599 
12600       Inherited::VisitBinaryOperator(E);
12601     }
12602 
12603     // A custom visitor for BinaryConditionalOperator is needed because the
12604     // regular visitor would check the condition and true expression separately
12605     // but both point to the same place giving duplicate diagnostics.
12606     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12607       Visit(E->getCond());
12608       Visit(E->getFalseExpr());
12609     }
12610 
12611     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12612       Decl* ReferenceDecl = DRE->getDecl();
12613       if (OrigDecl != ReferenceDecl) return;
12614       unsigned diag;
12615       if (isReferenceType) {
12616         diag = diag::warn_uninit_self_reference_in_reference_init;
12617       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12618         diag = diag::warn_static_self_reference_in_init;
12619       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12620                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12621                  DRE->getDecl()->getType()->isRecordType()) {
12622         diag = diag::warn_uninit_self_reference_in_init;
12623       } else {
12624         // Local variables will be handled by the CFG analysis.
12625         return;
12626       }
12627 
12628       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12629                             S.PDiag(diag)
12630                                 << DRE->getDecl() << OrigDecl->getLocation()
12631                                 << DRE->getSourceRange());
12632     }
12633   };
12634 
12635   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12636   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12637                                  bool DirectInit) {
12638     // Parameters arguments are occassionially constructed with itself,
12639     // for instance, in recursive functions.  Skip them.
12640     if (isa<ParmVarDecl>(OrigDecl))
12641       return;
12642 
12643     E = E->IgnoreParens();
12644 
12645     // Skip checking T a = a where T is not a record or reference type.
12646     // Doing so is a way to silence uninitialized warnings.
12647     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12648       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12649         if (ICE->getCastKind() == CK_LValueToRValue)
12650           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12651             if (DRE->getDecl() == OrigDecl)
12652               return;
12653 
12654     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12655   }
12656 } // end anonymous namespace
12657 
12658 namespace {
12659   // Simple wrapper to add the name of a variable or (if no variable is
12660   // available) a DeclarationName into a diagnostic.
12661   struct VarDeclOrName {
12662     VarDecl *VDecl;
12663     DeclarationName Name;
12664 
12665     friend const Sema::SemaDiagnosticBuilder &
12666     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12667       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12668     }
12669   };
12670 } // end anonymous namespace
12671 
12672 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12673                                             DeclarationName Name, QualType Type,
12674                                             TypeSourceInfo *TSI,
12675                                             SourceRange Range, bool DirectInit,
12676                                             Expr *Init) {
12677   bool IsInitCapture = !VDecl;
12678   assert((!VDecl || !VDecl->isInitCapture()) &&
12679          "init captures are expected to be deduced prior to initialization");
12680 
12681   VarDeclOrName VN{VDecl, Name};
12682 
12683   DeducedType *Deduced = Type->getContainedDeducedType();
12684   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12685 
12686   // C++11 [dcl.spec.auto]p3
12687   if (!Init) {
12688     assert(VDecl && "no init for init capture deduction?");
12689 
12690     // Except for class argument deduction, and then for an initializing
12691     // declaration only, i.e. no static at class scope or extern.
12692     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12693         VDecl->hasExternalStorage() ||
12694         VDecl->isStaticDataMember()) {
12695       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12696         << VDecl->getDeclName() << Type;
12697       return QualType();
12698     }
12699   }
12700 
12701   ArrayRef<Expr*> DeduceInits;
12702   if (Init)
12703     DeduceInits = Init;
12704 
12705   auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12706   if (DirectInit && PL)
12707     DeduceInits = PL->exprs();
12708 
12709   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12710     assert(VDecl && "non-auto type for init capture deduction?");
12711     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12712     InitializationKind Kind = InitializationKind::CreateForInit(
12713         VDecl->getLocation(), DirectInit, Init);
12714     // FIXME: Initialization should not be taking a mutable list of inits.
12715     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12716     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12717                                                        InitsCopy, PL);
12718   }
12719 
12720   if (DirectInit) {
12721     if (auto *IL = dyn_cast<InitListExpr>(Init))
12722       DeduceInits = IL->inits();
12723   }
12724 
12725   // Deduction only works if we have exactly one source expression.
12726   if (DeduceInits.empty()) {
12727     // It isn't possible to write this directly, but it is possible to
12728     // end up in this situation with "auto x(some_pack...);"
12729     Diag(Init->getBeginLoc(), IsInitCapture
12730                                   ? diag::err_init_capture_no_expression
12731                                   : diag::err_auto_var_init_no_expression)
12732         << VN << Type << Range;
12733     return QualType();
12734   }
12735 
12736   if (DeduceInits.size() > 1) {
12737     Diag(DeduceInits[1]->getBeginLoc(),
12738          IsInitCapture ? diag::err_init_capture_multiple_expressions
12739                        : diag::err_auto_var_init_multiple_expressions)
12740         << VN << Type << Range;
12741     return QualType();
12742   }
12743 
12744   Expr *DeduceInit = DeduceInits[0];
12745   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12746     Diag(Init->getBeginLoc(), IsInitCapture
12747                                   ? diag::err_init_capture_paren_braces
12748                                   : diag::err_auto_var_init_paren_braces)
12749         << isa<InitListExpr>(Init) << VN << Type << Range;
12750     return QualType();
12751   }
12752 
12753   // Expressions default to 'id' when we're in a debugger.
12754   bool DefaultedAnyToId = false;
12755   if (getLangOpts().DebuggerCastResultToId &&
12756       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12757     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12758     if (Result.isInvalid()) {
12759       return QualType();
12760     }
12761     Init = Result.get();
12762     DefaultedAnyToId = true;
12763   }
12764 
12765   // C++ [dcl.decomp]p1:
12766   //   If the assignment-expression [...] has array type A and no ref-qualifier
12767   //   is present, e has type cv A
12768   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12769       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12770       DeduceInit->getType()->isConstantArrayType())
12771     return Context.getQualifiedType(DeduceInit->getType(),
12772                                     Type.getQualifiers());
12773 
12774   QualType DeducedType;
12775   TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12776   TemplateDeductionResult Result =
12777       DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12778   if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
12779     if (!IsInitCapture)
12780       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12781     else if (isa<InitListExpr>(Init))
12782       Diag(Range.getBegin(),
12783            diag::err_init_capture_deduction_failure_from_init_list)
12784           << VN
12785           << (DeduceInit->getType().isNull() ? TSI->getType()
12786                                              : DeduceInit->getType())
12787           << DeduceInit->getSourceRange();
12788     else
12789       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12790           << VN << TSI->getType()
12791           << (DeduceInit->getType().isNull() ? TSI->getType()
12792                                              : DeduceInit->getType())
12793           << DeduceInit->getSourceRange();
12794   }
12795 
12796   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12797   // 'id' instead of a specific object type prevents most of our usual
12798   // checks.
12799   // We only want to warn outside of template instantiations, though:
12800   // inside a template, the 'id' could have come from a parameter.
12801   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12802       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12803     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12804     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12805   }
12806 
12807   return DeducedType;
12808 }
12809 
12810 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12811                                          Expr *Init) {
12812   assert(!Init || !Init->containsErrors());
12813   QualType DeducedType = deduceVarTypeFromInitializer(
12814       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12815       VDecl->getSourceRange(), DirectInit, Init);
12816   if (DeducedType.isNull()) {
12817     VDecl->setInvalidDecl();
12818     return true;
12819   }
12820 
12821   VDecl->setType(DeducedType);
12822   assert(VDecl->isLinkageValid());
12823 
12824   // In ARC, infer lifetime.
12825   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12826     VDecl->setInvalidDecl();
12827 
12828   if (getLangOpts().OpenCL)
12829     deduceOpenCLAddressSpace(VDecl);
12830 
12831   // If this is a redeclaration, check that the type we just deduced matches
12832   // the previously declared type.
12833   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12834     // We never need to merge the type, because we cannot form an incomplete
12835     // array of auto, nor deduce such a type.
12836     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12837   }
12838 
12839   // Check the deduced type is valid for a variable declaration.
12840   CheckVariableDeclarationType(VDecl);
12841   return VDecl->isInvalidDecl();
12842 }
12843 
12844 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12845                                               SourceLocation Loc) {
12846   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12847     Init = EWC->getSubExpr();
12848 
12849   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12850     Init = CE->getSubExpr();
12851 
12852   QualType InitType = Init->getType();
12853   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12854           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12855          "shouldn't be called if type doesn't have a non-trivial C struct");
12856   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12857     for (auto *I : ILE->inits()) {
12858       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12859           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12860         continue;
12861       SourceLocation SL = I->getExprLoc();
12862       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12863     }
12864     return;
12865   }
12866 
12867   if (isa<ImplicitValueInitExpr>(Init)) {
12868     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12869       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12870                             NTCUK_Init);
12871   } else {
12872     // Assume all other explicit initializers involving copying some existing
12873     // object.
12874     // TODO: ignore any explicit initializers where we can guarantee
12875     // copy-elision.
12876     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12877       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12878   }
12879 }
12880 
12881 namespace {
12882 
12883 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12884   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12885   // in the source code or implicitly by the compiler if it is in a union
12886   // defined in a system header and has non-trivial ObjC ownership
12887   // qualifications. We don't want those fields to participate in determining
12888   // whether the containing union is non-trivial.
12889   return FD->hasAttr<UnavailableAttr>();
12890 }
12891 
12892 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12893     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12894                                     void> {
12895   using Super =
12896       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12897                                     void>;
12898 
12899   DiagNonTrivalCUnionDefaultInitializeVisitor(
12900       QualType OrigTy, SourceLocation OrigLoc,
12901       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12902       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12903 
12904   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12905                      const FieldDecl *FD, bool InNonTrivialUnion) {
12906     if (const auto *AT = S.Context.getAsArrayType(QT))
12907       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12908                                      InNonTrivialUnion);
12909     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12910   }
12911 
12912   void visitARCStrong(QualType QT, const FieldDecl *FD,
12913                       bool InNonTrivialUnion) {
12914     if (InNonTrivialUnion)
12915       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12916           << 1 << 0 << QT << FD->getName();
12917   }
12918 
12919   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12920     if (InNonTrivialUnion)
12921       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12922           << 1 << 0 << QT << FD->getName();
12923   }
12924 
12925   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12926     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12927     if (RD->isUnion()) {
12928       if (OrigLoc.isValid()) {
12929         bool IsUnion = false;
12930         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12931           IsUnion = OrigRD->isUnion();
12932         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12933             << 0 << OrigTy << IsUnion << UseContext;
12934         // Reset OrigLoc so that this diagnostic is emitted only once.
12935         OrigLoc = SourceLocation();
12936       }
12937       InNonTrivialUnion = true;
12938     }
12939 
12940     if (InNonTrivialUnion)
12941       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12942           << 0 << 0 << QT.getUnqualifiedType() << "";
12943 
12944     for (const FieldDecl *FD : RD->fields())
12945       if (!shouldIgnoreForRecordTriviality(FD))
12946         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12947   }
12948 
12949   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12950 
12951   // The non-trivial C union type or the struct/union type that contains a
12952   // non-trivial C union.
12953   QualType OrigTy;
12954   SourceLocation OrigLoc;
12955   Sema::NonTrivialCUnionContext UseContext;
12956   Sema &S;
12957 };
12958 
12959 struct DiagNonTrivalCUnionDestructedTypeVisitor
12960     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12961   using Super =
12962       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12963 
12964   DiagNonTrivalCUnionDestructedTypeVisitor(
12965       QualType OrigTy, SourceLocation OrigLoc,
12966       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12967       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12968 
12969   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12970                      const FieldDecl *FD, bool InNonTrivialUnion) {
12971     if (const auto *AT = S.Context.getAsArrayType(QT))
12972       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12973                                      InNonTrivialUnion);
12974     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12975   }
12976 
12977   void visitARCStrong(QualType QT, const FieldDecl *FD,
12978                       bool InNonTrivialUnion) {
12979     if (InNonTrivialUnion)
12980       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12981           << 1 << 1 << QT << FD->getName();
12982   }
12983 
12984   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12985     if (InNonTrivialUnion)
12986       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12987           << 1 << 1 << QT << FD->getName();
12988   }
12989 
12990   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12991     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12992     if (RD->isUnion()) {
12993       if (OrigLoc.isValid()) {
12994         bool IsUnion = false;
12995         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12996           IsUnion = OrigRD->isUnion();
12997         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12998             << 1 << OrigTy << IsUnion << UseContext;
12999         // Reset OrigLoc so that this diagnostic is emitted only once.
13000         OrigLoc = SourceLocation();
13001       }
13002       InNonTrivialUnion = true;
13003     }
13004 
13005     if (InNonTrivialUnion)
13006       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13007           << 0 << 1 << QT.getUnqualifiedType() << "";
13008 
13009     for (const FieldDecl *FD : RD->fields())
13010       if (!shouldIgnoreForRecordTriviality(FD))
13011         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13012   }
13013 
13014   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13015   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13016                           bool InNonTrivialUnion) {}
13017 
13018   // The non-trivial C union type or the struct/union type that contains a
13019   // non-trivial C union.
13020   QualType OrigTy;
13021   SourceLocation OrigLoc;
13022   Sema::NonTrivialCUnionContext UseContext;
13023   Sema &S;
13024 };
13025 
13026 struct DiagNonTrivalCUnionCopyVisitor
13027     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13028   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13029 
13030   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13031                                  Sema::NonTrivialCUnionContext UseContext,
13032                                  Sema &S)
13033       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13034 
13035   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13036                      const FieldDecl *FD, bool InNonTrivialUnion) {
13037     if (const auto *AT = S.Context.getAsArrayType(QT))
13038       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13039                                      InNonTrivialUnion);
13040     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13041   }
13042 
13043   void visitARCStrong(QualType QT, const FieldDecl *FD,
13044                       bool InNonTrivialUnion) {
13045     if (InNonTrivialUnion)
13046       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13047           << 1 << 2 << QT << FD->getName();
13048   }
13049 
13050   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13051     if (InNonTrivialUnion)
13052       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13053           << 1 << 2 << QT << FD->getName();
13054   }
13055 
13056   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13057     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13058     if (RD->isUnion()) {
13059       if (OrigLoc.isValid()) {
13060         bool IsUnion = false;
13061         if (auto *OrigRD = OrigTy->getAsRecordDecl())
13062           IsUnion = OrigRD->isUnion();
13063         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13064             << 2 << OrigTy << IsUnion << UseContext;
13065         // Reset OrigLoc so that this diagnostic is emitted only once.
13066         OrigLoc = SourceLocation();
13067       }
13068       InNonTrivialUnion = true;
13069     }
13070 
13071     if (InNonTrivialUnion)
13072       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13073           << 0 << 2 << QT.getUnqualifiedType() << "";
13074 
13075     for (const FieldDecl *FD : RD->fields())
13076       if (!shouldIgnoreForRecordTriviality(FD))
13077         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13078   }
13079 
13080   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13081                 const FieldDecl *FD, bool InNonTrivialUnion) {}
13082   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13083   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13084                             bool InNonTrivialUnion) {}
13085 
13086   // The non-trivial C union type or the struct/union type that contains a
13087   // non-trivial C union.
13088   QualType OrigTy;
13089   SourceLocation OrigLoc;
13090   Sema::NonTrivialCUnionContext UseContext;
13091   Sema &S;
13092 };
13093 
13094 } // namespace
13095 
13096 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13097                                  NonTrivialCUnionContext UseContext,
13098                                  unsigned NonTrivialKind) {
13099   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13100           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13101           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13102          "shouldn't be called if type doesn't have a non-trivial C union");
13103 
13104   if ((NonTrivialKind & NTCUK_Init) &&
13105       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13106     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13107         .visit(QT, nullptr, false);
13108   if ((NonTrivialKind & NTCUK_Destruct) &&
13109       QT.hasNonTrivialToPrimitiveDestructCUnion())
13110     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13111         .visit(QT, nullptr, false);
13112   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13113     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13114         .visit(QT, nullptr, false);
13115 }
13116 
13117 /// AddInitializerToDecl - Adds the initializer Init to the
13118 /// declaration dcl. If DirectInit is true, this is C++ direct
13119 /// initialization rather than copy initialization.
13120 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13121   // If there is no declaration, there was an error parsing it.  Just ignore
13122   // the initializer.
13123   if (!RealDecl || RealDecl->isInvalidDecl()) {
13124     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13125     return;
13126   }
13127 
13128   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13129     // Pure-specifiers are handled in ActOnPureSpecifier.
13130     Diag(Method->getLocation(), diag::err_member_function_initialization)
13131       << Method->getDeclName() << Init->getSourceRange();
13132     Method->setInvalidDecl();
13133     return;
13134   }
13135 
13136   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13137   if (!VDecl) {
13138     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13139     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13140     RealDecl->setInvalidDecl();
13141     return;
13142   }
13143 
13144   // WebAssembly tables can't be used to initialise a variable.
13145   if (Init && !Init->getType().isNull() &&
13146       Init->getType()->isWebAssemblyTableType()) {
13147     Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13148     VDecl->setInvalidDecl();
13149     return;
13150   }
13151 
13152   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13153   if (VDecl->getType()->isUndeducedType()) {
13154     // Attempt typo correction early so that the type of the init expression can
13155     // be deduced based on the chosen correction if the original init contains a
13156     // TypoExpr.
13157     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13158     if (!Res.isUsable()) {
13159       // There are unresolved typos in Init, just drop them.
13160       // FIXME: improve the recovery strategy to preserve the Init.
13161       RealDecl->setInvalidDecl();
13162       return;
13163     }
13164     if (Res.get()->containsErrors()) {
13165       // Invalidate the decl as we don't know the type for recovery-expr yet.
13166       RealDecl->setInvalidDecl();
13167       VDecl->setInit(Res.get());
13168       return;
13169     }
13170     Init = Res.get();
13171 
13172     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13173       return;
13174   }
13175 
13176   // dllimport cannot be used on variable definitions.
13177   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13178     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13179     VDecl->setInvalidDecl();
13180     return;
13181   }
13182 
13183   // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13184   // the identifier has external or internal linkage, the declaration shall
13185   // have no initializer for the identifier.
13186   // C++14 [dcl.init]p5 is the same restriction for C++.
13187   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13188     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13189     VDecl->setInvalidDecl();
13190     return;
13191   }
13192 
13193   if (!VDecl->getType()->isDependentType()) {
13194     // A definition must end up with a complete type, which means it must be
13195     // complete with the restriction that an array type might be completed by
13196     // the initializer; note that later code assumes this restriction.
13197     QualType BaseDeclType = VDecl->getType();
13198     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13199       BaseDeclType = Array->getElementType();
13200     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13201                             diag::err_typecheck_decl_incomplete_type)) {
13202       RealDecl->setInvalidDecl();
13203       return;
13204     }
13205 
13206     // The variable can not have an abstract class type.
13207     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13208                                diag::err_abstract_type_in_decl,
13209                                AbstractVariableType))
13210       VDecl->setInvalidDecl();
13211   }
13212 
13213   // C++ [module.import/6] external definitions are not permitted in header
13214   // units.
13215   if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13216       !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13217       VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
13218       !VDecl->isInline() && !VDecl->isTemplated() &&
13219       !isa<VarTemplateSpecializationDecl>(VDecl)) {
13220     Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13221     VDecl->setInvalidDecl();
13222   }
13223 
13224   // If adding the initializer will turn this declaration into a definition,
13225   // and we already have a definition for this variable, diagnose or otherwise
13226   // handle the situation.
13227   if (VarDecl *Def = VDecl->getDefinition())
13228     if (Def != VDecl &&
13229         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13230         !VDecl->isThisDeclarationADemotedDefinition() &&
13231         checkVarDeclRedefinition(Def, VDecl))
13232       return;
13233 
13234   if (getLangOpts().CPlusPlus) {
13235     // C++ [class.static.data]p4
13236     //   If a static data member is of const integral or const
13237     //   enumeration type, its declaration in the class definition can
13238     //   specify a constant-initializer which shall be an integral
13239     //   constant expression (5.19). In that case, the member can appear
13240     //   in integral constant expressions. The member shall still be
13241     //   defined in a namespace scope if it is used in the program and the
13242     //   namespace scope definition shall not contain an initializer.
13243     //
13244     // We already performed a redefinition check above, but for static
13245     // data members we also need to check whether there was an in-class
13246     // declaration with an initializer.
13247     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13248       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13249           << VDecl->getDeclName();
13250       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13251            diag::note_previous_initializer)
13252           << 0;
13253       return;
13254     }
13255 
13256     if (VDecl->hasLocalStorage())
13257       setFunctionHasBranchProtectedScope();
13258 
13259     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13260       VDecl->setInvalidDecl();
13261       return;
13262     }
13263   }
13264 
13265   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13266   // a kernel function cannot be initialized."
13267   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13268     Diag(VDecl->getLocation(), diag::err_local_cant_init);
13269     VDecl->setInvalidDecl();
13270     return;
13271   }
13272 
13273   // The LoaderUninitialized attribute acts as a definition (of undef).
13274   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13275     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13276     VDecl->setInvalidDecl();
13277     return;
13278   }
13279 
13280   // Get the decls type and save a reference for later, since
13281   // CheckInitializerTypes may change it.
13282   QualType DclT = VDecl->getType(), SavT = DclT;
13283 
13284   // Expressions default to 'id' when we're in a debugger
13285   // and we are assigning it to a variable of Objective-C pointer type.
13286   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13287       Init->getType() == Context.UnknownAnyTy) {
13288     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13289     if (Result.isInvalid()) {
13290       VDecl->setInvalidDecl();
13291       return;
13292     }
13293     Init = Result.get();
13294   }
13295 
13296   // Perform the initialization.
13297   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13298   bool IsParenListInit = false;
13299   if (!VDecl->isInvalidDecl()) {
13300     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13301     InitializationKind Kind = InitializationKind::CreateForInit(
13302         VDecl->getLocation(), DirectInit, Init);
13303 
13304     MultiExprArg Args = Init;
13305     if (CXXDirectInit)
13306       Args = MultiExprArg(CXXDirectInit->getExprs(),
13307                           CXXDirectInit->getNumExprs());
13308 
13309     // Try to correct any TypoExprs in the initialization arguments.
13310     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13311       ExprResult Res = CorrectDelayedTyposInExpr(
13312           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13313           [this, Entity, Kind](Expr *E) {
13314             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13315             return Init.Failed() ? ExprError() : E;
13316           });
13317       if (Res.isInvalid()) {
13318         VDecl->setInvalidDecl();
13319       } else if (Res.get() != Args[Idx]) {
13320         Args[Idx] = Res.get();
13321       }
13322     }
13323     if (VDecl->isInvalidDecl())
13324       return;
13325 
13326     InitializationSequence InitSeq(*this, Entity, Kind, Args,
13327                                    /*TopLevelOfInitList=*/false,
13328                                    /*TreatUnavailableAsInvalid=*/false);
13329     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13330     if (Result.isInvalid()) {
13331       // If the provided initializer fails to initialize the var decl,
13332       // we attach a recovery expr for better recovery.
13333       auto RecoveryExpr =
13334           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13335       if (RecoveryExpr.get())
13336         VDecl->setInit(RecoveryExpr.get());
13337       return;
13338     }
13339 
13340     Init = Result.getAs<Expr>();
13341     IsParenListInit = !InitSeq.steps().empty() &&
13342                       InitSeq.step_begin()->Kind ==
13343                           InitializationSequence::SK_ParenthesizedListInit;
13344   }
13345 
13346   // Check for self-references within variable initializers.
13347   // Variables declared within a function/method body (except for references)
13348   // are handled by a dataflow analysis.
13349   // This is undefined behavior in C++, but valid in C.
13350   if (getLangOpts().CPlusPlus)
13351     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13352         VDecl->getType()->isReferenceType())
13353       CheckSelfReference(*this, RealDecl, Init, DirectInit);
13354 
13355   // If the type changed, it means we had an incomplete type that was
13356   // completed by the initializer. For example:
13357   //   int ary[] = { 1, 3, 5 };
13358   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13359   if (!VDecl->isInvalidDecl() && (DclT != SavT))
13360     VDecl->setType(DclT);
13361 
13362   if (!VDecl->isInvalidDecl()) {
13363     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13364 
13365     if (VDecl->hasAttr<BlocksAttr>())
13366       checkRetainCycles(VDecl, Init);
13367 
13368     // It is safe to assign a weak reference into a strong variable.
13369     // Although this code can still have problems:
13370     //   id x = self.weakProp;
13371     //   id y = self.weakProp;
13372     // we do not warn to warn spuriously when 'x' and 'y' are on separate
13373     // paths through the function. This should be revisited if
13374     // -Wrepeated-use-of-weak is made flow-sensitive.
13375     if (FunctionScopeInfo *FSI = getCurFunction())
13376       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13377            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13378           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13379                            Init->getBeginLoc()))
13380         FSI->markSafeWeakUse(Init);
13381   }
13382 
13383   // The initialization is usually a full-expression.
13384   //
13385   // FIXME: If this is a braced initialization of an aggregate, it is not
13386   // an expression, and each individual field initializer is a separate
13387   // full-expression. For instance, in:
13388   //
13389   //   struct Temp { ~Temp(); };
13390   //   struct S { S(Temp); };
13391   //   struct T { S a, b; } t = { Temp(), Temp() }
13392   //
13393   // we should destroy the first Temp before constructing the second.
13394   ExprResult Result =
13395       ActOnFinishFullExpr(Init, VDecl->getLocation(),
13396                           /*DiscardedValue*/ false, VDecl->isConstexpr());
13397   if (Result.isInvalid()) {
13398     VDecl->setInvalidDecl();
13399     return;
13400   }
13401   Init = Result.get();
13402 
13403   // Attach the initializer to the decl.
13404   VDecl->setInit(Init);
13405 
13406   if (VDecl->isLocalVarDecl()) {
13407     // Don't check the initializer if the declaration is malformed.
13408     if (VDecl->isInvalidDecl()) {
13409       // do nothing
13410 
13411     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13412     // This is true even in C++ for OpenCL.
13413     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13414       CheckForConstantInitializer(Init, DclT);
13415 
13416     // Otherwise, C++ does not restrict the initializer.
13417     } else if (getLangOpts().CPlusPlus) {
13418       // do nothing
13419 
13420     // C99 6.7.8p4: All the expressions in an initializer for an object that has
13421     // static storage duration shall be constant expressions or string literals.
13422     } else if (VDecl->getStorageClass() == SC_Static) {
13423       CheckForConstantInitializer(Init, DclT);
13424 
13425     // C89 is stricter than C99 for aggregate initializers.
13426     // C89 6.5.7p3: All the expressions [...] in an initializer list
13427     // for an object that has aggregate or union type shall be
13428     // constant expressions.
13429     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13430                isa<InitListExpr>(Init)) {
13431       const Expr *Culprit;
13432       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13433         Diag(Culprit->getExprLoc(),
13434              diag::ext_aggregate_init_not_constant)
13435           << Culprit->getSourceRange();
13436       }
13437     }
13438 
13439     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13440       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13441         if (VDecl->hasLocalStorage())
13442           BE->getBlockDecl()->setCanAvoidCopyToHeap();
13443   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13444              VDecl->getLexicalDeclContext()->isRecord()) {
13445     // This is an in-class initialization for a static data member, e.g.,
13446     //
13447     // struct S {
13448     //   static const int value = 17;
13449     // };
13450 
13451     // C++ [class.mem]p4:
13452     //   A member-declarator can contain a constant-initializer only
13453     //   if it declares a static member (9.4) of const integral or
13454     //   const enumeration type, see 9.4.2.
13455     //
13456     // C++11 [class.static.data]p3:
13457     //   If a non-volatile non-inline const static data member is of integral
13458     //   or enumeration type, its declaration in the class definition can
13459     //   specify a brace-or-equal-initializer in which every initializer-clause
13460     //   that is an assignment-expression is a constant expression. A static
13461     //   data member of literal type can be declared in the class definition
13462     //   with the constexpr specifier; if so, its declaration shall specify a
13463     //   brace-or-equal-initializer in which every initializer-clause that is
13464     //   an assignment-expression is a constant expression.
13465 
13466     // Do nothing on dependent types.
13467     if (DclT->isDependentType()) {
13468 
13469     // Allow any 'static constexpr' members, whether or not they are of literal
13470     // type. We separately check that every constexpr variable is of literal
13471     // type.
13472     } else if (VDecl->isConstexpr()) {
13473 
13474     // Require constness.
13475     } else if (!DclT.isConstQualified()) {
13476       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13477         << Init->getSourceRange();
13478       VDecl->setInvalidDecl();
13479 
13480     // We allow integer constant expressions in all cases.
13481     } else if (DclT->isIntegralOrEnumerationType()) {
13482       // Check whether the expression is a constant expression.
13483       SourceLocation Loc;
13484       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13485         // In C++11, a non-constexpr const static data member with an
13486         // in-class initializer cannot be volatile.
13487         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13488       else if (Init->isValueDependent())
13489         ; // Nothing to check.
13490       else if (Init->isIntegerConstantExpr(Context, &Loc))
13491         ; // Ok, it's an ICE!
13492       else if (Init->getType()->isScopedEnumeralType() &&
13493                Init->isCXX11ConstantExpr(Context))
13494         ; // Ok, it is a scoped-enum constant expression.
13495       else if (Init->isEvaluatable(Context)) {
13496         // If we can constant fold the initializer through heroics, accept it,
13497         // but report this as a use of an extension for -pedantic.
13498         Diag(Loc, diag::ext_in_class_initializer_non_constant)
13499           << Init->getSourceRange();
13500       } else {
13501         // Otherwise, this is some crazy unknown case.  Report the issue at the
13502         // location provided by the isIntegerConstantExpr failed check.
13503         Diag(Loc, diag::err_in_class_initializer_non_constant)
13504           << Init->getSourceRange();
13505         VDecl->setInvalidDecl();
13506       }
13507 
13508     // We allow foldable floating-point constants as an extension.
13509     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13510       // In C++98, this is a GNU extension. In C++11, it is not, but we support
13511       // it anyway and provide a fixit to add the 'constexpr'.
13512       if (getLangOpts().CPlusPlus11) {
13513         Diag(VDecl->getLocation(),
13514              diag::ext_in_class_initializer_float_type_cxx11)
13515             << DclT << Init->getSourceRange();
13516         Diag(VDecl->getBeginLoc(),
13517              diag::note_in_class_initializer_float_type_cxx11)
13518             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13519       } else {
13520         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13521           << DclT << Init->getSourceRange();
13522 
13523         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13524           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13525             << Init->getSourceRange();
13526           VDecl->setInvalidDecl();
13527         }
13528       }
13529 
13530     // Suggest adding 'constexpr' in C++11 for literal types.
13531     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13532       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13533           << DclT << Init->getSourceRange()
13534           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13535       VDecl->setConstexpr(true);
13536 
13537     } else {
13538       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13539         << DclT << Init->getSourceRange();
13540       VDecl->setInvalidDecl();
13541     }
13542   } else if (VDecl->isFileVarDecl()) {
13543     // In C, extern is typically used to avoid tentative definitions when
13544     // declaring variables in headers, but adding an intializer makes it a
13545     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13546     // In C++, extern is often used to give implictly static const variables
13547     // external linkage, so don't warn in that case. If selectany is present,
13548     // this might be header code intended for C and C++ inclusion, so apply the
13549     // C++ rules.
13550     if (VDecl->getStorageClass() == SC_Extern &&
13551         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13552          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13553         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13554         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13555       Diag(VDecl->getLocation(), diag::warn_extern_init);
13556 
13557     // In Microsoft C++ mode, a const variable defined in namespace scope has
13558     // external linkage by default if the variable is declared with
13559     // __declspec(dllexport).
13560     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13561         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13562         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13563       VDecl->setStorageClass(SC_Extern);
13564 
13565     // C99 6.7.8p4. All file scoped initializers need to be constant.
13566     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13567       CheckForConstantInitializer(Init, DclT);
13568   }
13569 
13570   QualType InitType = Init->getType();
13571   if (!InitType.isNull() &&
13572       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13573        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13574     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13575 
13576   // We will represent direct-initialization similarly to copy-initialization:
13577   //    int x(1);  -as-> int x = 1;
13578   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13579   //
13580   // Clients that want to distinguish between the two forms, can check for
13581   // direct initializer using VarDecl::getInitStyle().
13582   // A major benefit is that clients that don't particularly care about which
13583   // exactly form was it (like the CodeGen) can handle both cases without
13584   // special case code.
13585 
13586   // C++ 8.5p11:
13587   // The form of initialization (using parentheses or '=') is generally
13588   // insignificant, but does matter when the entity being initialized has a
13589   // class type.
13590   if (CXXDirectInit) {
13591     assert(DirectInit && "Call-style initializer must be direct init.");
13592     VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13593                                         : VarDecl::CallInit);
13594   } else if (DirectInit) {
13595     // This must be list-initialization. No other way is direct-initialization.
13596     VDecl->setInitStyle(VarDecl::ListInit);
13597   }
13598 
13599   if (LangOpts.OpenMP &&
13600       (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13601       VDecl->isFileVarDecl())
13602     DeclsToCheckForDeferredDiags.insert(VDecl);
13603   CheckCompleteVariableDeclaration(VDecl);
13604 }
13605 
13606 /// ActOnInitializerError - Given that there was an error parsing an
13607 /// initializer for the given declaration, try to at least re-establish
13608 /// invariants such as whether a variable's type is either dependent or
13609 /// complete.
13610 void Sema::ActOnInitializerError(Decl *D) {
13611   // Our main concern here is re-establishing invariants like "a
13612   // variable's type is either dependent or complete".
13613   if (!D || D->isInvalidDecl()) return;
13614 
13615   VarDecl *VD = dyn_cast<VarDecl>(D);
13616   if (!VD) return;
13617 
13618   // Bindings are not usable if we can't make sense of the initializer.
13619   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13620     for (auto *BD : DD->bindings())
13621       BD->setInvalidDecl();
13622 
13623   // Auto types are meaningless if we can't make sense of the initializer.
13624   if (VD->getType()->isUndeducedType()) {
13625     D->setInvalidDecl();
13626     return;
13627   }
13628 
13629   QualType Ty = VD->getType();
13630   if (Ty->isDependentType()) return;
13631 
13632   // Require a complete type.
13633   if (RequireCompleteType(VD->getLocation(),
13634                           Context.getBaseElementType(Ty),
13635                           diag::err_typecheck_decl_incomplete_type)) {
13636     VD->setInvalidDecl();
13637     return;
13638   }
13639 
13640   // Require a non-abstract type.
13641   if (RequireNonAbstractType(VD->getLocation(), Ty,
13642                              diag::err_abstract_type_in_decl,
13643                              AbstractVariableType)) {
13644     VD->setInvalidDecl();
13645     return;
13646   }
13647 
13648   // Don't bother complaining about constructors or destructors,
13649   // though.
13650 }
13651 
13652 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13653   // If there is no declaration, there was an error parsing it. Just ignore it.
13654   if (!RealDecl)
13655     return;
13656 
13657   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13658     QualType Type = Var->getType();
13659 
13660     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13661     if (isa<DecompositionDecl>(RealDecl)) {
13662       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13663       Var->setInvalidDecl();
13664       return;
13665     }
13666 
13667     if (Type->isUndeducedType() &&
13668         DeduceVariableDeclarationType(Var, false, nullptr))
13669       return;
13670 
13671     // C++11 [class.static.data]p3: A static data member can be declared with
13672     // the constexpr specifier; if so, its declaration shall specify
13673     // a brace-or-equal-initializer.
13674     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13675     // the definition of a variable [...] or the declaration of a static data
13676     // member.
13677     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13678         !Var->isThisDeclarationADemotedDefinition()) {
13679       if (Var->isStaticDataMember()) {
13680         // C++1z removes the relevant rule; the in-class declaration is always
13681         // a definition there.
13682         if (!getLangOpts().CPlusPlus17 &&
13683             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13684           Diag(Var->getLocation(),
13685                diag::err_constexpr_static_mem_var_requires_init)
13686               << Var;
13687           Var->setInvalidDecl();
13688           return;
13689         }
13690       } else {
13691         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13692         Var->setInvalidDecl();
13693         return;
13694       }
13695     }
13696 
13697     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13698     // be initialized.
13699     if (!Var->isInvalidDecl() &&
13700         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13701         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13702       bool HasConstExprDefaultConstructor = false;
13703       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13704         for (auto *Ctor : RD->ctors()) {
13705           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13706               Ctor->getMethodQualifiers().getAddressSpace() ==
13707                   LangAS::opencl_constant) {
13708             HasConstExprDefaultConstructor = true;
13709           }
13710         }
13711       }
13712       if (!HasConstExprDefaultConstructor) {
13713         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13714         Var->setInvalidDecl();
13715         return;
13716       }
13717     }
13718 
13719     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13720       if (Var->getStorageClass() == SC_Extern) {
13721         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13722             << Var;
13723         Var->setInvalidDecl();
13724         return;
13725       }
13726       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13727                               diag::err_typecheck_decl_incomplete_type)) {
13728         Var->setInvalidDecl();
13729         return;
13730       }
13731       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13732         if (!RD->hasTrivialDefaultConstructor()) {
13733           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13734           Var->setInvalidDecl();
13735           return;
13736         }
13737       }
13738       // The declaration is unitialized, no need for further checks.
13739       return;
13740     }
13741 
13742     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13743     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13744         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13745       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13746                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13747 
13748 
13749     switch (DefKind) {
13750     case VarDecl::Definition:
13751       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13752         break;
13753 
13754       // We have an out-of-line definition of a static data member
13755       // that has an in-class initializer, so we type-check this like
13756       // a declaration.
13757       //
13758       [[fallthrough]];
13759 
13760     case VarDecl::DeclarationOnly:
13761       // It's only a declaration.
13762 
13763       // Block scope. C99 6.7p7: If an identifier for an object is
13764       // declared with no linkage (C99 6.2.2p6), the type for the
13765       // object shall be complete.
13766       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13767           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13768           RequireCompleteType(Var->getLocation(), Type,
13769                               diag::err_typecheck_decl_incomplete_type))
13770         Var->setInvalidDecl();
13771 
13772       // Make sure that the type is not abstract.
13773       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13774           RequireNonAbstractType(Var->getLocation(), Type,
13775                                  diag::err_abstract_type_in_decl,
13776                                  AbstractVariableType))
13777         Var->setInvalidDecl();
13778       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13779           Var->getStorageClass() == SC_PrivateExtern) {
13780         Diag(Var->getLocation(), diag::warn_private_extern);
13781         Diag(Var->getLocation(), diag::note_private_extern);
13782       }
13783 
13784       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13785           !Var->isInvalidDecl())
13786         ExternalDeclarations.push_back(Var);
13787 
13788       return;
13789 
13790     case VarDecl::TentativeDefinition:
13791       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13792       // object that has file scope without an initializer, and without a
13793       // storage-class specifier or with the storage-class specifier "static",
13794       // constitutes a tentative definition. Note: A tentative definition with
13795       // external linkage is valid (C99 6.2.2p5).
13796       if (!Var->isInvalidDecl()) {
13797         if (const IncompleteArrayType *ArrayT
13798                                     = Context.getAsIncompleteArrayType(Type)) {
13799           if (RequireCompleteSizedType(
13800                   Var->getLocation(), ArrayT->getElementType(),
13801                   diag::err_array_incomplete_or_sizeless_type))
13802             Var->setInvalidDecl();
13803         } else if (Var->getStorageClass() == SC_Static) {
13804           // C99 6.9.2p3: If the declaration of an identifier for an object is
13805           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13806           // declared type shall not be an incomplete type.
13807           // NOTE: code such as the following
13808           //     static struct s;
13809           //     struct s { int a; };
13810           // is accepted by gcc. Hence here we issue a warning instead of
13811           // an error and we do not invalidate the static declaration.
13812           // NOTE: to avoid multiple warnings, only check the first declaration.
13813           if (Var->isFirstDecl())
13814             RequireCompleteType(Var->getLocation(), Type,
13815                                 diag::ext_typecheck_decl_incomplete_type);
13816         }
13817       }
13818 
13819       // Record the tentative definition; we're done.
13820       if (!Var->isInvalidDecl())
13821         TentativeDefinitions.push_back(Var);
13822       return;
13823     }
13824 
13825     // Provide a specific diagnostic for uninitialized variable
13826     // definitions with incomplete array type.
13827     if (Type->isIncompleteArrayType()) {
13828       if (Var->isConstexpr())
13829         Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13830             << Var;
13831       else
13832         Diag(Var->getLocation(),
13833              diag::err_typecheck_incomplete_array_needs_initializer);
13834       Var->setInvalidDecl();
13835       return;
13836     }
13837 
13838     // Provide a specific diagnostic for uninitialized variable
13839     // definitions with reference type.
13840     if (Type->isReferenceType()) {
13841       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13842           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13843       return;
13844     }
13845 
13846     // Do not attempt to type-check the default initializer for a
13847     // variable with dependent type.
13848     if (Type->isDependentType())
13849       return;
13850 
13851     if (Var->isInvalidDecl())
13852       return;
13853 
13854     if (!Var->hasAttr<AliasAttr>()) {
13855       if (RequireCompleteType(Var->getLocation(),
13856                               Context.getBaseElementType(Type),
13857                               diag::err_typecheck_decl_incomplete_type)) {
13858         Var->setInvalidDecl();
13859         return;
13860       }
13861     } else {
13862       return;
13863     }
13864 
13865     // The variable can not have an abstract class type.
13866     if (RequireNonAbstractType(Var->getLocation(), Type,
13867                                diag::err_abstract_type_in_decl,
13868                                AbstractVariableType)) {
13869       Var->setInvalidDecl();
13870       return;
13871     }
13872 
13873     // Check for jumps past the implicit initializer.  C++0x
13874     // clarifies that this applies to a "variable with automatic
13875     // storage duration", not a "local variable".
13876     // C++11 [stmt.dcl]p3
13877     //   A program that jumps from a point where a variable with automatic
13878     //   storage duration is not in scope to a point where it is in scope is
13879     //   ill-formed unless the variable has scalar type, class type with a
13880     //   trivial default constructor and a trivial destructor, a cv-qualified
13881     //   version of one of these types, or an array of one of the preceding
13882     //   types and is declared without an initializer.
13883     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13884       if (const RecordType *Record
13885             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13886         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13887         // Mark the function (if we're in one) for further checking even if the
13888         // looser rules of C++11 do not require such checks, so that we can
13889         // diagnose incompatibilities with C++98.
13890         if (!CXXRecord->isPOD())
13891           setFunctionHasBranchProtectedScope();
13892       }
13893     }
13894     // In OpenCL, we can't initialize objects in the __local address space,
13895     // even implicitly, so don't synthesize an implicit initializer.
13896     if (getLangOpts().OpenCL &&
13897         Var->getType().getAddressSpace() == LangAS::opencl_local)
13898       return;
13899     // C++03 [dcl.init]p9:
13900     //   If no initializer is specified for an object, and the
13901     //   object is of (possibly cv-qualified) non-POD class type (or
13902     //   array thereof), the object shall be default-initialized; if
13903     //   the object is of const-qualified type, the underlying class
13904     //   type shall have a user-declared default
13905     //   constructor. Otherwise, if no initializer is specified for
13906     //   a non- static object, the object and its subobjects, if
13907     //   any, have an indeterminate initial value); if the object
13908     //   or any of its subobjects are of const-qualified type, the
13909     //   program is ill-formed.
13910     // C++0x [dcl.init]p11:
13911     //   If no initializer is specified for an object, the object is
13912     //   default-initialized; [...].
13913     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13914     InitializationKind Kind
13915       = InitializationKind::CreateDefault(Var->getLocation());
13916 
13917     InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
13918     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
13919 
13920     if (Init.get()) {
13921       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13922       // This is important for template substitution.
13923       Var->setInitStyle(VarDecl::CallInit);
13924     } else if (Init.isInvalid()) {
13925       // If default-init fails, attach a recovery-expr initializer to track
13926       // that initialization was attempted and failed.
13927       auto RecoveryExpr =
13928           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13929       if (RecoveryExpr.get())
13930         Var->setInit(RecoveryExpr.get());
13931     }
13932 
13933     CheckCompleteVariableDeclaration(Var);
13934   }
13935 }
13936 
13937 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13938   // If there is no declaration, there was an error parsing it. Ignore it.
13939   if (!D)
13940     return;
13941 
13942   VarDecl *VD = dyn_cast<VarDecl>(D);
13943   if (!VD) {
13944     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13945     D->setInvalidDecl();
13946     return;
13947   }
13948 
13949   VD->setCXXForRangeDecl(true);
13950 
13951   // for-range-declaration cannot be given a storage class specifier.
13952   int Error = -1;
13953   switch (VD->getStorageClass()) {
13954   case SC_None:
13955     break;
13956   case SC_Extern:
13957     Error = 0;
13958     break;
13959   case SC_Static:
13960     Error = 1;
13961     break;
13962   case SC_PrivateExtern:
13963     Error = 2;
13964     break;
13965   case SC_Auto:
13966     Error = 3;
13967     break;
13968   case SC_Register:
13969     Error = 4;
13970     break;
13971   }
13972 
13973   // for-range-declaration cannot be given a storage class specifier con't.
13974   switch (VD->getTSCSpec()) {
13975   case TSCS_thread_local:
13976     Error = 6;
13977     break;
13978   case TSCS___thread:
13979   case TSCS__Thread_local:
13980   case TSCS_unspecified:
13981     break;
13982   }
13983 
13984   if (Error != -1) {
13985     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13986         << VD << Error;
13987     D->setInvalidDecl();
13988   }
13989 }
13990 
13991 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13992                                             IdentifierInfo *Ident,
13993                                             ParsedAttributes &Attrs) {
13994   // C++1y [stmt.iter]p1:
13995   //   A range-based for statement of the form
13996   //      for ( for-range-identifier : for-range-initializer ) statement
13997   //   is equivalent to
13998   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13999   DeclSpec DS(Attrs.getPool().getFactory());
14000 
14001   const char *PrevSpec;
14002   unsigned DiagID;
14003   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14004                      getPrintingPolicy());
14005 
14006   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14007   D.SetIdentifier(Ident, IdentLoc);
14008   D.takeAttributes(Attrs);
14009 
14010   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14011                 IdentLoc);
14012   Decl *Var = ActOnDeclarator(S, D);
14013   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14014   FinalizeDeclaration(Var);
14015   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14016                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14017                                                       : IdentLoc);
14018 }
14019 
14020 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14021   if (var->isInvalidDecl()) return;
14022 
14023   MaybeAddCUDAConstantAttr(var);
14024 
14025   if (getLangOpts().OpenCL) {
14026     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14027     // initialiser
14028     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14029         !var->hasInit()) {
14030       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14031           << 1 /*Init*/;
14032       var->setInvalidDecl();
14033       return;
14034     }
14035   }
14036 
14037   // In Objective-C, don't allow jumps past the implicit initialization of a
14038   // local retaining variable.
14039   if (getLangOpts().ObjC &&
14040       var->hasLocalStorage()) {
14041     switch (var->getType().getObjCLifetime()) {
14042     case Qualifiers::OCL_None:
14043     case Qualifiers::OCL_ExplicitNone:
14044     case Qualifiers::OCL_Autoreleasing:
14045       break;
14046 
14047     case Qualifiers::OCL_Weak:
14048     case Qualifiers::OCL_Strong:
14049       setFunctionHasBranchProtectedScope();
14050       break;
14051     }
14052   }
14053 
14054   if (var->hasLocalStorage() &&
14055       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14056     setFunctionHasBranchProtectedScope();
14057 
14058   // Warn about externally-visible variables being defined without a
14059   // prior declaration.  We only want to do this for global
14060   // declarations, but we also specifically need to avoid doing it for
14061   // class members because the linkage of an anonymous class can
14062   // change if it's later given a typedef name.
14063   if (var->isThisDeclarationADefinition() &&
14064       var->getDeclContext()->getRedeclContext()->isFileContext() &&
14065       var->isExternallyVisible() && var->hasLinkage() &&
14066       !var->isInline() && !var->getDescribedVarTemplate() &&
14067       !isa<VarTemplatePartialSpecializationDecl>(var) &&
14068       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14069       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14070                                   var->getLocation())) {
14071     // Find a previous declaration that's not a definition.
14072     VarDecl *prev = var->getPreviousDecl();
14073     while (prev && prev->isThisDeclarationADefinition())
14074       prev = prev->getPreviousDecl();
14075 
14076     if (!prev) {
14077       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14078       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14079           << /* variable */ 0;
14080     }
14081   }
14082 
14083   // Cache the result of checking for constant initialization.
14084   std::optional<bool> CacheHasConstInit;
14085   const Expr *CacheCulprit = nullptr;
14086   auto checkConstInit = [&]() mutable {
14087     if (!CacheHasConstInit)
14088       CacheHasConstInit = var->getInit()->isConstantInitializer(
14089             Context, var->getType()->isReferenceType(), &CacheCulprit);
14090     return *CacheHasConstInit;
14091   };
14092 
14093   if (var->getTLSKind() == VarDecl::TLS_Static) {
14094     if (var->getType().isDestructedType()) {
14095       // GNU C++98 edits for __thread, [basic.start.term]p3:
14096       //   The type of an object with thread storage duration shall not
14097       //   have a non-trivial destructor.
14098       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14099       if (getLangOpts().CPlusPlus11)
14100         Diag(var->getLocation(), diag::note_use_thread_local);
14101     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14102       if (!checkConstInit()) {
14103         // GNU C++98 edits for __thread, [basic.start.init]p4:
14104         //   An object of thread storage duration shall not require dynamic
14105         //   initialization.
14106         // FIXME: Need strict checking here.
14107         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14108           << CacheCulprit->getSourceRange();
14109         if (getLangOpts().CPlusPlus11)
14110           Diag(var->getLocation(), diag::note_use_thread_local);
14111       }
14112     }
14113   }
14114 
14115 
14116   if (!var->getType()->isStructureType() && var->hasInit() &&
14117       isa<InitListExpr>(var->getInit())) {
14118     const auto *ILE = cast<InitListExpr>(var->getInit());
14119     unsigned NumInits = ILE->getNumInits();
14120     if (NumInits > 2)
14121       for (unsigned I = 0; I < NumInits; ++I) {
14122         const auto *Init = ILE->getInit(I);
14123         if (!Init)
14124           break;
14125         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14126         if (!SL)
14127           break;
14128 
14129         unsigned NumConcat = SL->getNumConcatenated();
14130         // Diagnose missing comma in string array initialization.
14131         // Do not warn when all the elements in the initializer are concatenated
14132         // together. Do not warn for macros too.
14133         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14134           bool OnlyOneMissingComma = true;
14135           for (unsigned J = I + 1; J < NumInits; ++J) {
14136             const auto *Init = ILE->getInit(J);
14137             if (!Init)
14138               break;
14139             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14140             if (!SLJ || SLJ->getNumConcatenated() > 1) {
14141               OnlyOneMissingComma = false;
14142               break;
14143             }
14144           }
14145 
14146           if (OnlyOneMissingComma) {
14147             SmallVector<FixItHint, 1> Hints;
14148             for (unsigned i = 0; i < NumConcat - 1; ++i)
14149               Hints.push_back(FixItHint::CreateInsertion(
14150                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14151 
14152             Diag(SL->getStrTokenLoc(1),
14153                  diag::warn_concatenated_literal_array_init)
14154                 << Hints;
14155             Diag(SL->getBeginLoc(),
14156                  diag::note_concatenated_string_literal_silence);
14157           }
14158           // In any case, stop now.
14159           break;
14160         }
14161       }
14162   }
14163 
14164 
14165   QualType type = var->getType();
14166 
14167   if (var->hasAttr<BlocksAttr>())
14168     getCurFunction()->addByrefBlockVar(var);
14169 
14170   Expr *Init = var->getInit();
14171   bool GlobalStorage = var->hasGlobalStorage();
14172   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14173   QualType baseType = Context.getBaseElementType(type);
14174   bool HasConstInit = true;
14175 
14176   // Check whether the initializer is sufficiently constant.
14177   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14178       !Init->isValueDependent() &&
14179       (GlobalStorage || var->isConstexpr() ||
14180        var->mightBeUsableInConstantExpressions(Context))) {
14181     // If this variable might have a constant initializer or might be usable in
14182     // constant expressions, check whether or not it actually is now.  We can't
14183     // do this lazily, because the result might depend on things that change
14184     // later, such as which constexpr functions happen to be defined.
14185     SmallVector<PartialDiagnosticAt, 8> Notes;
14186     if (!getLangOpts().CPlusPlus11) {
14187       // Prior to C++11, in contexts where a constant initializer is required,
14188       // the set of valid constant initializers is described by syntactic rules
14189       // in [expr.const]p2-6.
14190       // FIXME: Stricter checking for these rules would be useful for constinit /
14191       // -Wglobal-constructors.
14192       HasConstInit = checkConstInit();
14193 
14194       // Compute and cache the constant value, and remember that we have a
14195       // constant initializer.
14196       if (HasConstInit) {
14197         (void)var->checkForConstantInitialization(Notes);
14198         Notes.clear();
14199       } else if (CacheCulprit) {
14200         Notes.emplace_back(CacheCulprit->getExprLoc(),
14201                            PDiag(diag::note_invalid_subexpr_in_const_expr));
14202         Notes.back().second << CacheCulprit->getSourceRange();
14203       }
14204     } else {
14205       // Evaluate the initializer to see if it's a constant initializer.
14206       HasConstInit = var->checkForConstantInitialization(Notes);
14207     }
14208 
14209     if (HasConstInit) {
14210       // FIXME: Consider replacing the initializer with a ConstantExpr.
14211     } else if (var->isConstexpr()) {
14212       SourceLocation DiagLoc = var->getLocation();
14213       // If the note doesn't add any useful information other than a source
14214       // location, fold it into the primary diagnostic.
14215       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14216                                    diag::note_invalid_subexpr_in_const_expr) {
14217         DiagLoc = Notes[0].first;
14218         Notes.clear();
14219       }
14220       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14221           << var << Init->getSourceRange();
14222       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14223         Diag(Notes[I].first, Notes[I].second);
14224     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14225       auto *Attr = var->getAttr<ConstInitAttr>();
14226       Diag(var->getLocation(), diag::err_require_constant_init_failed)
14227           << Init->getSourceRange();
14228       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14229           << Attr->getRange() << Attr->isConstinit();
14230       for (auto &it : Notes)
14231         Diag(it.first, it.second);
14232     } else if (IsGlobal &&
14233                !getDiagnostics().isIgnored(diag::warn_global_constructor,
14234                                            var->getLocation())) {
14235       // Warn about globals which don't have a constant initializer.  Don't
14236       // warn about globals with a non-trivial destructor because we already
14237       // warned about them.
14238       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14239       if (!(RD && !RD->hasTrivialDestructor())) {
14240         // checkConstInit() here permits trivial default initialization even in
14241         // C++11 onwards, where such an initializer is not a constant initializer
14242         // but nonetheless doesn't require a global constructor.
14243         if (!checkConstInit())
14244           Diag(var->getLocation(), diag::warn_global_constructor)
14245               << Init->getSourceRange();
14246       }
14247     }
14248   }
14249 
14250   // Apply section attributes and pragmas to global variables.
14251   if (GlobalStorage && var->isThisDeclarationADefinition() &&
14252       !inTemplateInstantiation()) {
14253     PragmaStack<StringLiteral *> *Stack = nullptr;
14254     int SectionFlags = ASTContext::PSF_Read;
14255     if (var->getType().isConstQualified()) {
14256       if (HasConstInit)
14257         Stack = &ConstSegStack;
14258       else {
14259         Stack = &BSSSegStack;
14260         SectionFlags |= ASTContext::PSF_Write;
14261       }
14262     } else if (var->hasInit() && HasConstInit) {
14263       Stack = &DataSegStack;
14264       SectionFlags |= ASTContext::PSF_Write;
14265     } else {
14266       Stack = &BSSSegStack;
14267       SectionFlags |= ASTContext::PSF_Write;
14268     }
14269     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14270       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14271         SectionFlags |= ASTContext::PSF_Implicit;
14272       UnifySection(SA->getName(), SectionFlags, var);
14273     } else if (Stack->CurrentValue) {
14274       SectionFlags |= ASTContext::PSF_Implicit;
14275       auto SectionName = Stack->CurrentValue->getString();
14276       var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14277                                                Stack->CurrentPragmaLocation,
14278                                                SectionAttr::Declspec_allocate));
14279       if (UnifySection(SectionName, SectionFlags, var))
14280         var->dropAttr<SectionAttr>();
14281     }
14282 
14283     // Apply the init_seg attribute if this has an initializer.  If the
14284     // initializer turns out to not be dynamic, we'll end up ignoring this
14285     // attribute.
14286     if (CurInitSeg && var->getInit())
14287       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14288                                                CurInitSegLoc));
14289   }
14290 
14291   // All the following checks are C++ only.
14292   if (!getLangOpts().CPlusPlus) {
14293     // If this variable must be emitted, add it as an initializer for the
14294     // current module.
14295     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14296       Context.addModuleInitializer(ModuleScopes.back().Module, var);
14297     return;
14298   }
14299 
14300   // Require the destructor.
14301   if (!type->isDependentType())
14302     if (const RecordType *recordType = baseType->getAs<RecordType>())
14303       FinalizeVarWithDestructor(var, recordType);
14304 
14305   // If this variable must be emitted, add it as an initializer for the current
14306   // module.
14307   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14308     Context.addModuleInitializer(ModuleScopes.back().Module, var);
14309 
14310   // Build the bindings if this is a structured binding declaration.
14311   if (auto *DD = dyn_cast<DecompositionDecl>(var))
14312     CheckCompleteDecompositionDeclaration(DD);
14313 }
14314 
14315 /// Check if VD needs to be dllexport/dllimport due to being in a
14316 /// dllexport/import function.
14317 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14318   assert(VD->isStaticLocal());
14319 
14320   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14321 
14322   // Find outermost function when VD is in lambda function.
14323   while (FD && !getDLLAttr(FD) &&
14324          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14325          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14326     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14327   }
14328 
14329   if (!FD)
14330     return;
14331 
14332   // Static locals inherit dll attributes from their function.
14333   if (Attr *A = getDLLAttr(FD)) {
14334     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14335     NewAttr->setInherited(true);
14336     VD->addAttr(NewAttr);
14337   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14338     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14339     NewAttr->setInherited(true);
14340     VD->addAttr(NewAttr);
14341 
14342     // Export this function to enforce exporting this static variable even
14343     // if it is not used in this compilation unit.
14344     if (!FD->hasAttr<DLLExportAttr>())
14345       FD->addAttr(NewAttr);
14346 
14347   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14348     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14349     NewAttr->setInherited(true);
14350     VD->addAttr(NewAttr);
14351   }
14352 }
14353 
14354 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14355   assert(VD->getTLSKind());
14356 
14357   // Perform TLS alignment check here after attributes attached to the variable
14358   // which may affect the alignment have been processed. Only perform the check
14359   // if the target has a maximum TLS alignment (zero means no constraints).
14360   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14361     // Protect the check so that it's not performed on dependent types and
14362     // dependent alignments (we can't determine the alignment in that case).
14363     if (!VD->hasDependentAlignment()) {
14364       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14365       if (Context.getDeclAlign(VD) > MaxAlignChars) {
14366         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14367             << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14368             << (unsigned)MaxAlignChars.getQuantity();
14369       }
14370     }
14371   }
14372 }
14373 
14374 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14375 /// any semantic actions necessary after any initializer has been attached.
14376 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14377   // Note that we are no longer parsing the initializer for this declaration.
14378   ParsingInitForAutoVars.erase(ThisDecl);
14379 
14380   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14381   if (!VD)
14382     return;
14383 
14384   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14385   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14386       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14387     if (PragmaClangBSSSection.Valid)
14388       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14389           Context, PragmaClangBSSSection.SectionName,
14390           PragmaClangBSSSection.PragmaLocation));
14391     if (PragmaClangDataSection.Valid)
14392       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14393           Context, PragmaClangDataSection.SectionName,
14394           PragmaClangDataSection.PragmaLocation));
14395     if (PragmaClangRodataSection.Valid)
14396       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14397           Context, PragmaClangRodataSection.SectionName,
14398           PragmaClangRodataSection.PragmaLocation));
14399     if (PragmaClangRelroSection.Valid)
14400       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14401           Context, PragmaClangRelroSection.SectionName,
14402           PragmaClangRelroSection.PragmaLocation));
14403   }
14404 
14405   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14406     for (auto *BD : DD->bindings()) {
14407       FinalizeDeclaration(BD);
14408     }
14409   }
14410 
14411   checkAttributesAfterMerging(*this, *VD);
14412 
14413   if (VD->isStaticLocal())
14414     CheckStaticLocalForDllExport(VD);
14415 
14416   if (VD->getTLSKind())
14417     CheckThreadLocalForLargeAlignment(VD);
14418 
14419   // Perform check for initializers of device-side global variables.
14420   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14421   // 7.5). We must also apply the same checks to all __shared__
14422   // variables whether they are local or not. CUDA also allows
14423   // constant initializers for __constant__ and __device__ variables.
14424   if (getLangOpts().CUDA)
14425     checkAllowedCUDAInitializer(VD);
14426 
14427   // Grab the dllimport or dllexport attribute off of the VarDecl.
14428   const InheritableAttr *DLLAttr = getDLLAttr(VD);
14429 
14430   // Imported static data members cannot be defined out-of-line.
14431   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14432     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14433         VD->isThisDeclarationADefinition()) {
14434       // We allow definitions of dllimport class template static data members
14435       // with a warning.
14436       CXXRecordDecl *Context =
14437         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14438       bool IsClassTemplateMember =
14439           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14440           Context->getDescribedClassTemplate();
14441 
14442       Diag(VD->getLocation(),
14443            IsClassTemplateMember
14444                ? diag::warn_attribute_dllimport_static_field_definition
14445                : diag::err_attribute_dllimport_static_field_definition);
14446       Diag(IA->getLocation(), diag::note_attribute);
14447       if (!IsClassTemplateMember)
14448         VD->setInvalidDecl();
14449     }
14450   }
14451 
14452   // dllimport/dllexport variables cannot be thread local, their TLS index
14453   // isn't exported with the variable.
14454   if (DLLAttr && VD->getTLSKind()) {
14455     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14456     if (F && getDLLAttr(F)) {
14457       assert(VD->isStaticLocal());
14458       // But if this is a static local in a dlimport/dllexport function, the
14459       // function will never be inlined, which means the var would never be
14460       // imported, so having it marked import/export is safe.
14461     } else {
14462       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14463                                                                     << DLLAttr;
14464       VD->setInvalidDecl();
14465     }
14466   }
14467 
14468   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14469     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14470       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14471           << Attr;
14472       VD->dropAttr<UsedAttr>();
14473     }
14474   }
14475   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14476     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14477       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14478           << Attr;
14479       VD->dropAttr<RetainAttr>();
14480     }
14481   }
14482 
14483   const DeclContext *DC = VD->getDeclContext();
14484   // If there's a #pragma GCC visibility in scope, and this isn't a class
14485   // member, set the visibility of this variable.
14486   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14487     AddPushedVisibilityAttribute(VD);
14488 
14489   // FIXME: Warn on unused var template partial specializations.
14490   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14491     MarkUnusedFileScopedDecl(VD);
14492 
14493   // Now we have parsed the initializer and can update the table of magic
14494   // tag values.
14495   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14496       !VD->getType()->isIntegralOrEnumerationType())
14497     return;
14498 
14499   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14500     const Expr *MagicValueExpr = VD->getInit();
14501     if (!MagicValueExpr) {
14502       continue;
14503     }
14504     std::optional<llvm::APSInt> MagicValueInt;
14505     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14506       Diag(I->getRange().getBegin(),
14507            diag::err_type_tag_for_datatype_not_ice)
14508         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14509       continue;
14510     }
14511     if (MagicValueInt->getActiveBits() > 64) {
14512       Diag(I->getRange().getBegin(),
14513            diag::err_type_tag_for_datatype_too_large)
14514         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14515       continue;
14516     }
14517     uint64_t MagicValue = MagicValueInt->getZExtValue();
14518     RegisterTypeTagForDatatype(I->getArgumentKind(),
14519                                MagicValue,
14520                                I->getMatchingCType(),
14521                                I->getLayoutCompatible(),
14522                                I->getMustBeNull());
14523   }
14524 }
14525 
14526 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14527   auto *VD = dyn_cast<VarDecl>(DD);
14528   return VD && !VD->getType()->hasAutoForTrailingReturnType();
14529 }
14530 
14531 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14532                                                    ArrayRef<Decl *> Group) {
14533   SmallVector<Decl*, 8> Decls;
14534 
14535   if (DS.isTypeSpecOwned())
14536     Decls.push_back(DS.getRepAsDecl());
14537 
14538   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14539   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14540   bool DiagnosedMultipleDecomps = false;
14541   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14542   bool DiagnosedNonDeducedAuto = false;
14543 
14544   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14545     if (Decl *D = Group[i]) {
14546       // Check if the Decl has been declared in '#pragma omp declare target'
14547       // directive and has static storage duration.
14548       if (auto *VD = dyn_cast<VarDecl>(D);
14549           LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14550           VD->hasGlobalStorage())
14551         ActOnOpenMPDeclareTargetInitializer(D);
14552       // For declarators, there are some additional syntactic-ish checks we need
14553       // to perform.
14554       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14555         if (!FirstDeclaratorInGroup)
14556           FirstDeclaratorInGroup = DD;
14557         if (!FirstDecompDeclaratorInGroup)
14558           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14559         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14560             !hasDeducedAuto(DD))
14561           FirstNonDeducedAutoInGroup = DD;
14562 
14563         if (FirstDeclaratorInGroup != DD) {
14564           // A decomposition declaration cannot be combined with any other
14565           // declaration in the same group.
14566           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14567             Diag(FirstDecompDeclaratorInGroup->getLocation(),
14568                  diag::err_decomp_decl_not_alone)
14569                 << FirstDeclaratorInGroup->getSourceRange()
14570                 << DD->getSourceRange();
14571             DiagnosedMultipleDecomps = true;
14572           }
14573 
14574           // A declarator that uses 'auto' in any way other than to declare a
14575           // variable with a deduced type cannot be combined with any other
14576           // declarator in the same group.
14577           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14578             Diag(FirstNonDeducedAutoInGroup->getLocation(),
14579                  diag::err_auto_non_deduced_not_alone)
14580                 << FirstNonDeducedAutoInGroup->getType()
14581                        ->hasAutoForTrailingReturnType()
14582                 << FirstDeclaratorInGroup->getSourceRange()
14583                 << DD->getSourceRange();
14584             DiagnosedNonDeducedAuto = true;
14585           }
14586         }
14587       }
14588 
14589       Decls.push_back(D);
14590     }
14591   }
14592 
14593   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14594     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14595       handleTagNumbering(Tag, S);
14596       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14597           getLangOpts().CPlusPlus)
14598         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14599     }
14600   }
14601 
14602   return BuildDeclaratorGroup(Decls);
14603 }
14604 
14605 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14606 /// group, performing any necessary semantic checking.
14607 Sema::DeclGroupPtrTy
14608 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14609   // C++14 [dcl.spec.auto]p7: (DR1347)
14610   //   If the type that replaces the placeholder type is not the same in each
14611   //   deduction, the program is ill-formed.
14612   if (Group.size() > 1) {
14613     QualType Deduced;
14614     VarDecl *DeducedDecl = nullptr;
14615     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14616       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14617       if (!D || D->isInvalidDecl())
14618         break;
14619       DeducedType *DT = D->getType()->getContainedDeducedType();
14620       if (!DT || DT->getDeducedType().isNull())
14621         continue;
14622       if (Deduced.isNull()) {
14623         Deduced = DT->getDeducedType();
14624         DeducedDecl = D;
14625       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14626         auto *AT = dyn_cast<AutoType>(DT);
14627         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14628                         diag::err_auto_different_deductions)
14629                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14630                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14631                    << D->getDeclName();
14632         if (DeducedDecl->hasInit())
14633           Dia << DeducedDecl->getInit()->getSourceRange();
14634         if (D->getInit())
14635           Dia << D->getInit()->getSourceRange();
14636         D->setInvalidDecl();
14637         break;
14638       }
14639     }
14640   }
14641 
14642   ActOnDocumentableDecls(Group);
14643 
14644   return DeclGroupPtrTy::make(
14645       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14646 }
14647 
14648 void Sema::ActOnDocumentableDecl(Decl *D) {
14649   ActOnDocumentableDecls(D);
14650 }
14651 
14652 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14653   // Don't parse the comment if Doxygen diagnostics are ignored.
14654   if (Group.empty() || !Group[0])
14655     return;
14656 
14657   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14658                       Group[0]->getLocation()) &&
14659       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14660                       Group[0]->getLocation()))
14661     return;
14662 
14663   if (Group.size() >= 2) {
14664     // This is a decl group.  Normally it will contain only declarations
14665     // produced from declarator list.  But in case we have any definitions or
14666     // additional declaration references:
14667     //   'typedef struct S {} S;'
14668     //   'typedef struct S *S;'
14669     //   'struct S *pS;'
14670     // FinalizeDeclaratorGroup adds these as separate declarations.
14671     Decl *MaybeTagDecl = Group[0];
14672     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14673       Group = Group.slice(1);
14674     }
14675   }
14676 
14677   // FIMXE: We assume every Decl in the group is in the same file.
14678   // This is false when preprocessor constructs the group from decls in
14679   // different files (e. g. macros or #include).
14680   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14681 }
14682 
14683 /// Common checks for a parameter-declaration that should apply to both function
14684 /// parameters and non-type template parameters.
14685 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14686   // Check that there are no default arguments inside the type of this
14687   // parameter.
14688   if (getLangOpts().CPlusPlus)
14689     CheckExtraCXXDefaultArguments(D);
14690 
14691   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14692   if (D.getCXXScopeSpec().isSet()) {
14693     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14694       << D.getCXXScopeSpec().getRange();
14695   }
14696 
14697   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14698   // simple identifier except [...irrelevant cases...].
14699   switch (D.getName().getKind()) {
14700   case UnqualifiedIdKind::IK_Identifier:
14701     break;
14702 
14703   case UnqualifiedIdKind::IK_OperatorFunctionId:
14704   case UnqualifiedIdKind::IK_ConversionFunctionId:
14705   case UnqualifiedIdKind::IK_LiteralOperatorId:
14706   case UnqualifiedIdKind::IK_ConstructorName:
14707   case UnqualifiedIdKind::IK_DestructorName:
14708   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14709   case UnqualifiedIdKind::IK_DeductionGuideName:
14710     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14711       << GetNameForDeclarator(D).getName();
14712     break;
14713 
14714   case UnqualifiedIdKind::IK_TemplateId:
14715   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14716     // GetNameForDeclarator would not produce a useful name in this case.
14717     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14718     break;
14719   }
14720 }
14721 
14722 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14723 /// to introduce parameters into function prototype scope.
14724 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14725   const DeclSpec &DS = D.getDeclSpec();
14726 
14727   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14728 
14729   // C++03 [dcl.stc]p2 also permits 'auto'.
14730   StorageClass SC = SC_None;
14731   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14732     SC = SC_Register;
14733     // In C++11, the 'register' storage class specifier is deprecated.
14734     // In C++17, it is not allowed, but we tolerate it as an extension.
14735     if (getLangOpts().CPlusPlus11) {
14736       Diag(DS.getStorageClassSpecLoc(),
14737            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14738                                      : diag::warn_deprecated_register)
14739         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14740     }
14741   } else if (getLangOpts().CPlusPlus &&
14742              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14743     SC = SC_Auto;
14744   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14745     Diag(DS.getStorageClassSpecLoc(),
14746          diag::err_invalid_storage_class_in_func_decl);
14747     D.getMutableDeclSpec().ClearStorageClassSpecs();
14748   }
14749 
14750   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14751     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14752       << DeclSpec::getSpecifierName(TSCS);
14753   if (DS.isInlineSpecified())
14754     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14755         << getLangOpts().CPlusPlus17;
14756   if (DS.hasConstexprSpecifier())
14757     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14758         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14759 
14760   DiagnoseFunctionSpecifiers(DS);
14761 
14762   CheckFunctionOrTemplateParamDeclarator(S, D);
14763 
14764   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14765   QualType parmDeclType = TInfo->getType();
14766 
14767   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14768   IdentifierInfo *II = D.getIdentifier();
14769   if (II) {
14770     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14771                    ForVisibleRedeclaration);
14772     LookupName(R, S);
14773     if (R.isSingleResult()) {
14774       NamedDecl *PrevDecl = R.getFoundDecl();
14775       if (PrevDecl->isTemplateParameter()) {
14776         // Maybe we will complain about the shadowed template parameter.
14777         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14778         // Just pretend that we didn't see the previous declaration.
14779         PrevDecl = nullptr;
14780       } else if (S->isDeclScope(PrevDecl)) {
14781         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14782         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14783 
14784         // Recover by removing the name
14785         II = nullptr;
14786         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14787         D.setInvalidType(true);
14788       }
14789     }
14790   }
14791 
14792   // Temporarily put parameter variables in the translation unit, not
14793   // the enclosing context.  This prevents them from accidentally
14794   // looking like class members in C++.
14795   ParmVarDecl *New =
14796       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14797                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14798 
14799   if (D.isInvalidType())
14800     New->setInvalidDecl();
14801 
14802   assert(S->isFunctionPrototypeScope());
14803   assert(S->getFunctionPrototypeDepth() >= 1);
14804   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14805                     S->getNextFunctionPrototypeIndex());
14806 
14807   // Add the parameter declaration into this scope.
14808   S->AddDecl(New);
14809   if (II)
14810     IdResolver.AddDecl(New);
14811 
14812   ProcessDeclAttributes(S, New, D);
14813 
14814   if (D.getDeclSpec().isModulePrivateSpecified())
14815     Diag(New->getLocation(), diag::err_module_private_local)
14816         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14817         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14818 
14819   if (New->hasAttr<BlocksAttr>()) {
14820     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14821   }
14822 
14823   if (getLangOpts().OpenCL)
14824     deduceOpenCLAddressSpace(New);
14825 
14826   return New;
14827 }
14828 
14829 /// Synthesizes a variable for a parameter arising from a
14830 /// typedef.
14831 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14832                                               SourceLocation Loc,
14833                                               QualType T) {
14834   /* FIXME: setting StartLoc == Loc.
14835      Would it be worth to modify callers so as to provide proper source
14836      location for the unnamed parameters, embedding the parameter's type? */
14837   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14838                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14839                                            SC_None, nullptr);
14840   Param->setImplicit();
14841   return Param;
14842 }
14843 
14844 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14845   // Don't diagnose unused-parameter errors in template instantiations; we
14846   // will already have done so in the template itself.
14847   if (inTemplateInstantiation())
14848     return;
14849 
14850   for (const ParmVarDecl *Parameter : Parameters) {
14851     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14852         !Parameter->hasAttr<UnusedAttr>()) {
14853       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14854         << Parameter->getDeclName();
14855     }
14856   }
14857 }
14858 
14859 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14860     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14861   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14862     return;
14863 
14864   // Warn if the return value is pass-by-value and larger than the specified
14865   // threshold.
14866   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14867     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14868     if (Size > LangOpts.NumLargeByValueCopy)
14869       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14870   }
14871 
14872   // Warn if any parameter is pass-by-value and larger than the specified
14873   // threshold.
14874   for (const ParmVarDecl *Parameter : Parameters) {
14875     QualType T = Parameter->getType();
14876     if (T->isDependentType() || !T.isPODType(Context))
14877       continue;
14878     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14879     if (Size > LangOpts.NumLargeByValueCopy)
14880       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14881           << Parameter << Size;
14882   }
14883 }
14884 
14885 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14886                                   SourceLocation NameLoc, IdentifierInfo *Name,
14887                                   QualType T, TypeSourceInfo *TSInfo,
14888                                   StorageClass SC) {
14889   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14890   if (getLangOpts().ObjCAutoRefCount &&
14891       T.getObjCLifetime() == Qualifiers::OCL_None &&
14892       T->isObjCLifetimeType()) {
14893 
14894     Qualifiers::ObjCLifetime lifetime;
14895 
14896     // Special cases for arrays:
14897     //   - if it's const, use __unsafe_unretained
14898     //   - otherwise, it's an error
14899     if (T->isArrayType()) {
14900       if (!T.isConstQualified()) {
14901         if (DelayedDiagnostics.shouldDelayDiagnostics())
14902           DelayedDiagnostics.add(
14903               sema::DelayedDiagnostic::makeForbiddenType(
14904               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14905         else
14906           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14907               << TSInfo->getTypeLoc().getSourceRange();
14908       }
14909       lifetime = Qualifiers::OCL_ExplicitNone;
14910     } else {
14911       lifetime = T->getObjCARCImplicitLifetime();
14912     }
14913     T = Context.getLifetimeQualifiedType(T, lifetime);
14914   }
14915 
14916   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14917                                          Context.getAdjustedParameterType(T),
14918                                          TSInfo, SC, nullptr);
14919 
14920   // Make a note if we created a new pack in the scope of a lambda, so that
14921   // we know that references to that pack must also be expanded within the
14922   // lambda scope.
14923   if (New->isParameterPack())
14924     if (auto *LSI = getEnclosingLambda())
14925       LSI->LocalPacks.push_back(New);
14926 
14927   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14928       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14929     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14930                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14931 
14932   // Parameter declarators cannot be interface types. All ObjC objects are
14933   // passed by reference.
14934   if (T->isObjCObjectType()) {
14935     SourceLocation TypeEndLoc =
14936         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14937     Diag(NameLoc,
14938          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14939       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14940     T = Context.getObjCObjectPointerType(T);
14941     New->setType(T);
14942   }
14943 
14944   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14945   // duration shall not be qualified by an address-space qualifier."
14946   // Since all parameters have automatic store duration, they can not have
14947   // an address space.
14948   if (T.getAddressSpace() != LangAS::Default &&
14949       // OpenCL allows function arguments declared to be an array of a type
14950       // to be qualified with an address space.
14951       !(getLangOpts().OpenCL &&
14952         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
14953       // WebAssembly allows reference types as parameters. Funcref in particular
14954       // lives in a different address space.
14955       !(T->isFunctionPointerType() &&
14956         T.getAddressSpace() == LangAS::wasm_funcref)) {
14957     Diag(NameLoc, diag::err_arg_with_address_space);
14958     New->setInvalidDecl();
14959   }
14960 
14961   // PPC MMA non-pointer types are not allowed as function argument types.
14962   if (Context.getTargetInfo().getTriple().isPPC64() &&
14963       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14964     New->setInvalidDecl();
14965   }
14966 
14967   return New;
14968 }
14969 
14970 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14971                                            SourceLocation LocAfterDecls) {
14972   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14973 
14974   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14975   // in the declaration list shall have at least one declarator, those
14976   // declarators shall only declare identifiers from the identifier list, and
14977   // every identifier in the identifier list shall be declared.
14978   //
14979   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14980   // identifiers it names shall be declared in the declaration list."
14981   //
14982   // This is why we only diagnose in C99 and later. Note, the other conditions
14983   // listed are checked elsewhere.
14984   if (!FTI.hasPrototype) {
14985     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14986       --i;
14987       if (FTI.Params[i].Param == nullptr) {
14988         if (getLangOpts().C99) {
14989           SmallString<256> Code;
14990           llvm::raw_svector_ostream(Code)
14991               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14992           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14993               << FTI.Params[i].Ident
14994               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14995         }
14996 
14997         // Implicitly declare the argument as type 'int' for lack of a better
14998         // type.
14999         AttributeFactory attrs;
15000         DeclSpec DS(attrs);
15001         const char* PrevSpec; // unused
15002         unsigned DiagID; // unused
15003         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15004                            DiagID, Context.getPrintingPolicy());
15005         // Use the identifier location for the type source range.
15006         DS.SetRangeStart(FTI.Params[i].IdentLoc);
15007         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15008         Declarator ParamD(DS, ParsedAttributesView::none(),
15009                           DeclaratorContext::KNRTypeList);
15010         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15011         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15012       }
15013     }
15014   }
15015 }
15016 
15017 Decl *
15018 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15019                               MultiTemplateParamsArg TemplateParameterLists,
15020                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15021   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15022   assert(D.isFunctionDeclarator() && "Not a function declarator!");
15023   Scope *ParentScope = FnBodyScope->getParent();
15024 
15025   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15026   // we define a non-templated function definition, we will create a declaration
15027   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15028   // The base function declaration will have the equivalent of an `omp declare
15029   // variant` annotation which specifies the mangled definition as a
15030   // specialization function under the OpenMP context defined as part of the
15031   // `omp begin declare variant`.
15032   SmallVector<FunctionDecl *, 4> Bases;
15033   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15034     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15035         ParentScope, D, TemplateParameterLists, Bases);
15036 
15037   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15038   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15039   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15040 
15041   if (!Bases.empty())
15042     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15043 
15044   return Dcl;
15045 }
15046 
15047 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15048   Consumer.HandleInlineFunctionDefinition(D);
15049 }
15050 
15051 static bool FindPossiblePrototype(const FunctionDecl *FD,
15052                                   const FunctionDecl *&PossiblePrototype) {
15053   for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15054        Prev = Prev->getPreviousDecl()) {
15055     // Ignore any declarations that occur in function or method
15056     // scope, because they aren't visible from the header.
15057     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15058       continue;
15059 
15060     PossiblePrototype = Prev;
15061     return Prev->getType()->isFunctionProtoType();
15062   }
15063   return false;
15064 }
15065 
15066 static bool
15067 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15068                                 const FunctionDecl *&PossiblePrototype) {
15069   // Don't warn about invalid declarations.
15070   if (FD->isInvalidDecl())
15071     return false;
15072 
15073   // Or declarations that aren't global.
15074   if (!FD->isGlobal())
15075     return false;
15076 
15077   // Don't warn about C++ member functions.
15078   if (isa<CXXMethodDecl>(FD))
15079     return false;
15080 
15081   // Don't warn about 'main'.
15082   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15083     if (IdentifierInfo *II = FD->getIdentifier())
15084       if (II->isStr("main") || II->isStr("efi_main"))
15085         return false;
15086 
15087   // Don't warn about inline functions.
15088   if (FD->isInlined())
15089     return false;
15090 
15091   // Don't warn about function templates.
15092   if (FD->getDescribedFunctionTemplate())
15093     return false;
15094 
15095   // Don't warn about function template specializations.
15096   if (FD->isFunctionTemplateSpecialization())
15097     return false;
15098 
15099   // Don't warn for OpenCL kernels.
15100   if (FD->hasAttr<OpenCLKernelAttr>())
15101     return false;
15102 
15103   // Don't warn on explicitly deleted functions.
15104   if (FD->isDeleted())
15105     return false;
15106 
15107   // Don't warn on implicitly local functions (such as having local-typed
15108   // parameters).
15109   if (!FD->isExternallyVisible())
15110     return false;
15111 
15112   // If we were able to find a potential prototype, don't warn.
15113   if (FindPossiblePrototype(FD, PossiblePrototype))
15114     return false;
15115 
15116   return true;
15117 }
15118 
15119 void
15120 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15121                                    const FunctionDecl *EffectiveDefinition,
15122                                    SkipBodyInfo *SkipBody) {
15123   const FunctionDecl *Definition = EffectiveDefinition;
15124   if (!Definition &&
15125       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15126     return;
15127 
15128   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15129     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15130       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15131         // A merged copy of the same function, instantiated as a member of
15132         // the same class, is OK.
15133         if (declaresSameEntity(OrigFD, OrigDef) &&
15134             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15135                                cast<Decl>(FD->getLexicalDeclContext())))
15136           return;
15137       }
15138     }
15139   }
15140 
15141   if (canRedefineFunction(Definition, getLangOpts()))
15142     return;
15143 
15144   // Don't emit an error when this is redefinition of a typo-corrected
15145   // definition.
15146   if (TypoCorrectedFunctionDefinitions.count(Definition))
15147     return;
15148 
15149   // If we don't have a visible definition of the function, and it's inline or
15150   // a template, skip the new definition.
15151   if (SkipBody && !hasVisibleDefinition(Definition) &&
15152       (Definition->getFormalLinkage() == InternalLinkage ||
15153        Definition->isInlined() ||
15154        Definition->getDescribedFunctionTemplate() ||
15155        Definition->getNumTemplateParameterLists())) {
15156     SkipBody->ShouldSkip = true;
15157     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15158     if (auto *TD = Definition->getDescribedFunctionTemplate())
15159       makeMergedDefinitionVisible(TD);
15160     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15161     return;
15162   }
15163 
15164   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15165       Definition->getStorageClass() == SC_Extern)
15166     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15167         << FD << getLangOpts().CPlusPlus;
15168   else
15169     Diag(FD->getLocation(), diag::err_redefinition) << FD;
15170 
15171   Diag(Definition->getLocation(), diag::note_previous_definition);
15172   FD->setInvalidDecl();
15173 }
15174 
15175 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15176   CXXRecordDecl *LambdaClass = CallOperator->getParent();
15177 
15178   LambdaScopeInfo *LSI = PushLambdaScope();
15179   LSI->CallOperator = CallOperator;
15180   LSI->Lambda = LambdaClass;
15181   LSI->ReturnType = CallOperator->getReturnType();
15182   // This function in calls in situation where the context of the call operator
15183   // is not entered, so we set AfterParameterList to false, so that
15184   // `tryCaptureVariable` finds explicit captures in the appropriate context.
15185   LSI->AfterParameterList = false;
15186   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15187 
15188   if (LCD == LCD_None)
15189     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15190   else if (LCD == LCD_ByCopy)
15191     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15192   else if (LCD == LCD_ByRef)
15193     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15194   DeclarationNameInfo DNI = CallOperator->getNameInfo();
15195 
15196   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15197   LSI->Mutable = !CallOperator->isConst();
15198 
15199   // Add the captures to the LSI so they can be noted as already
15200   // captured within tryCaptureVar.
15201   auto I = LambdaClass->field_begin();
15202   for (const auto &C : LambdaClass->captures()) {
15203     if (C.capturesVariable()) {
15204       ValueDecl *VD = C.getCapturedVar();
15205       if (VD->isInitCapture())
15206         CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15207       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15208       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15209           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15210           /*EllipsisLoc*/C.isPackExpansion()
15211                          ? C.getEllipsisLoc() : SourceLocation(),
15212           I->getType(), /*Invalid*/false);
15213 
15214     } else if (C.capturesThis()) {
15215       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15216                           C.getCaptureKind() == LCK_StarThis);
15217     } else {
15218       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15219                              I->getType());
15220     }
15221     ++I;
15222   }
15223   return LSI;
15224 }
15225 
15226 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15227                                     SkipBodyInfo *SkipBody,
15228                                     FnBodyKind BodyKind) {
15229   if (!D) {
15230     // Parsing the function declaration failed in some way. Push on a fake scope
15231     // anyway so we can try to parse the function body.
15232     PushFunctionScope();
15233     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15234     return D;
15235   }
15236 
15237   FunctionDecl *FD = nullptr;
15238 
15239   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15240     FD = FunTmpl->getTemplatedDecl();
15241   else
15242     FD = cast<FunctionDecl>(D);
15243 
15244   // Do not push if it is a lambda because one is already pushed when building
15245   // the lambda in ActOnStartOfLambdaDefinition().
15246   if (!isLambdaCallOperator(FD))
15247     // [expr.const]/p14.1
15248     // An expression or conversion is in an immediate function context if it is
15249     // potentially evaluated and either: its innermost enclosing non-block scope
15250     // is a function parameter scope of an immediate function.
15251     PushExpressionEvaluationContext(
15252         FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15253                           : ExprEvalContexts.back().Context);
15254 
15255   // Each ExpressionEvaluationContextRecord also keeps track of whether the
15256   // context is nested in an immediate function context, so smaller contexts
15257   // that appear inside immediate functions (like variable initializers) are
15258   // considered to be inside an immediate function context even though by
15259   // themselves they are not immediate function contexts. But when a new
15260   // function is entered, we need to reset this tracking, since the entered
15261   // function might be not an immediate function.
15262   ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15263   ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15264       getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15265 
15266   // Check for defining attributes before the check for redefinition.
15267   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15268     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15269     FD->dropAttr<AliasAttr>();
15270     FD->setInvalidDecl();
15271   }
15272   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15273     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15274     FD->dropAttr<IFuncAttr>();
15275     FD->setInvalidDecl();
15276   }
15277   if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15278     if (!Context.getTargetInfo().hasFeature("fmv") &&
15279         !Attr->isDefaultVersion()) {
15280       // If function multi versioning disabled skip parsing function body
15281       // defined with non-default target_version attribute
15282       if (SkipBody)
15283         SkipBody->ShouldSkip = true;
15284       return nullptr;
15285     }
15286   }
15287 
15288   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15289     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15290         Ctor->isDefaultConstructor() &&
15291         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15292       // If this is an MS ABI dllexport default constructor, instantiate any
15293       // default arguments.
15294       InstantiateDefaultCtorDefaultArgs(Ctor);
15295     }
15296   }
15297 
15298   // See if this is a redefinition. If 'will have body' (or similar) is already
15299   // set, then these checks were already performed when it was set.
15300   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15301       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15302     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15303 
15304     // If we're skipping the body, we're done. Don't enter the scope.
15305     if (SkipBody && SkipBody->ShouldSkip)
15306       return D;
15307   }
15308 
15309   // Mark this function as "will have a body eventually".  This lets users to
15310   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15311   // this function.
15312   FD->setWillHaveBody();
15313 
15314   // If we are instantiating a generic lambda call operator, push
15315   // a LambdaScopeInfo onto the function stack.  But use the information
15316   // that's already been calculated (ActOnLambdaExpr) to prime the current
15317   // LambdaScopeInfo.
15318   // When the template operator is being specialized, the LambdaScopeInfo,
15319   // has to be properly restored so that tryCaptureVariable doesn't try
15320   // and capture any new variables. In addition when calculating potential
15321   // captures during transformation of nested lambdas, it is necessary to
15322   // have the LSI properly restored.
15323   if (isGenericLambdaCallOperatorSpecialization(FD)) {
15324     assert(inTemplateInstantiation() &&
15325            "There should be an active template instantiation on the stack "
15326            "when instantiating a generic lambda!");
15327     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15328   } else {
15329     // Enter a new function scope
15330     PushFunctionScope();
15331   }
15332 
15333   // Builtin functions cannot be defined.
15334   if (unsigned BuiltinID = FD->getBuiltinID()) {
15335     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15336         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15337       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15338       FD->setInvalidDecl();
15339     }
15340   }
15341 
15342   // The return type of a function definition must be complete (C99 6.9.1p3).
15343   // C++23 [dcl.fct.def.general]/p2
15344   // The type of [...] the return for a function definition
15345   // shall not be a (possibly cv-qualified) class type that is incomplete
15346   // or abstract within the function body unless the function is deleted.
15347   QualType ResultType = FD->getReturnType();
15348   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15349       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15350       (RequireCompleteType(FD->getLocation(), ResultType,
15351                            diag::err_func_def_incomplete_result) ||
15352        RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15353                               diag::err_abstract_type_in_decl,
15354                               AbstractReturnType)))
15355     FD->setInvalidDecl();
15356 
15357   if (FnBodyScope)
15358     PushDeclContext(FnBodyScope, FD);
15359 
15360   // Check the validity of our function parameters
15361   if (BodyKind != FnBodyKind::Delete)
15362     CheckParmsForFunctionDef(FD->parameters(),
15363                              /*CheckParameterNames=*/true);
15364 
15365   // Add non-parameter declarations already in the function to the current
15366   // scope.
15367   if (FnBodyScope) {
15368     for (Decl *NPD : FD->decls()) {
15369       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15370       if (!NonParmDecl)
15371         continue;
15372       assert(!isa<ParmVarDecl>(NonParmDecl) &&
15373              "parameters should not be in newly created FD yet");
15374 
15375       // If the decl has a name, make it accessible in the current scope.
15376       if (NonParmDecl->getDeclName())
15377         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15378 
15379       // Similarly, dive into enums and fish their constants out, making them
15380       // accessible in this scope.
15381       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15382         for (auto *EI : ED->enumerators())
15383           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15384       }
15385     }
15386   }
15387 
15388   // Introduce our parameters into the function scope
15389   for (auto *Param : FD->parameters()) {
15390     Param->setOwningFunction(FD);
15391 
15392     // If this has an identifier, add it to the scope stack.
15393     if (Param->getIdentifier() && FnBodyScope) {
15394       CheckShadow(FnBodyScope, Param);
15395 
15396       PushOnScopeChains(Param, FnBodyScope);
15397     }
15398   }
15399 
15400   // C++ [module.import/6] external definitions are not permitted in header
15401   // units.  Deleted and Defaulted functions are implicitly inline (but the
15402   // inline state is not set at this point, so check the BodyKind explicitly).
15403   // FIXME: Consider an alternate location for the test where the inlined()
15404   // state is complete.
15405   if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15406       !FD->isInvalidDecl() && !FD->isInlined() &&
15407       BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15408       FD->getFormalLinkage() == Linkage::ExternalLinkage &&
15409       !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15410     assert(FD->isThisDeclarationADefinition());
15411     Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15412     FD->setInvalidDecl();
15413   }
15414 
15415   // Ensure that the function's exception specification is instantiated.
15416   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15417     ResolveExceptionSpec(D->getLocation(), FPT);
15418 
15419   // dllimport cannot be applied to non-inline function definitions.
15420   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15421       !FD->isTemplateInstantiation()) {
15422     assert(!FD->hasAttr<DLLExportAttr>());
15423     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15424     FD->setInvalidDecl();
15425     return D;
15426   }
15427   // We want to attach documentation to original Decl (which might be
15428   // a function template).
15429   ActOnDocumentableDecl(D);
15430   if (getCurLexicalContext()->isObjCContainer() &&
15431       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15432       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15433     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15434 
15435   return D;
15436 }
15437 
15438 /// Given the set of return statements within a function body,
15439 /// compute the variables that are subject to the named return value
15440 /// optimization.
15441 ///
15442 /// Each of the variables that is subject to the named return value
15443 /// optimization will be marked as NRVO variables in the AST, and any
15444 /// return statement that has a marked NRVO variable as its NRVO candidate can
15445 /// use the named return value optimization.
15446 ///
15447 /// This function applies a very simplistic algorithm for NRVO: if every return
15448 /// statement in the scope of a variable has the same NRVO candidate, that
15449 /// candidate is an NRVO variable.
15450 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15451   ReturnStmt **Returns = Scope->Returns.data();
15452 
15453   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15454     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15455       if (!NRVOCandidate->isNRVOVariable())
15456         Returns[I]->setNRVOCandidate(nullptr);
15457     }
15458   }
15459 }
15460 
15461 bool Sema::canDelayFunctionBody(const Declarator &D) {
15462   // We can't delay parsing the body of a constexpr function template (yet).
15463   if (D.getDeclSpec().hasConstexprSpecifier())
15464     return false;
15465 
15466   // We can't delay parsing the body of a function template with a deduced
15467   // return type (yet).
15468   if (D.getDeclSpec().hasAutoTypeSpec()) {
15469     // If the placeholder introduces a non-deduced trailing return type,
15470     // we can still delay parsing it.
15471     if (D.getNumTypeObjects()) {
15472       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15473       if (Outer.Kind == DeclaratorChunk::Function &&
15474           Outer.Fun.hasTrailingReturnType()) {
15475         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15476         return Ty.isNull() || !Ty->isUndeducedType();
15477       }
15478     }
15479     return false;
15480   }
15481 
15482   return true;
15483 }
15484 
15485 bool Sema::canSkipFunctionBody(Decl *D) {
15486   // We cannot skip the body of a function (or function template) which is
15487   // constexpr, since we may need to evaluate its body in order to parse the
15488   // rest of the file.
15489   // We cannot skip the body of a function with an undeduced return type,
15490   // because any callers of that function need to know the type.
15491   if (const FunctionDecl *FD = D->getAsFunction()) {
15492     if (FD->isConstexpr())
15493       return false;
15494     // We can't simply call Type::isUndeducedType here, because inside template
15495     // auto can be deduced to a dependent type, which is not considered
15496     // "undeduced".
15497     if (FD->getReturnType()->getContainedDeducedType())
15498       return false;
15499   }
15500   return Consumer.shouldSkipFunctionBody(D);
15501 }
15502 
15503 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15504   if (!Decl)
15505     return nullptr;
15506   if (FunctionDecl *FD = Decl->getAsFunction())
15507     FD->setHasSkippedBody();
15508   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15509     MD->setHasSkippedBody();
15510   return Decl;
15511 }
15512 
15513 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15514   return ActOnFinishFunctionBody(D, BodyArg, false);
15515 }
15516 
15517 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15518 /// body.
15519 class ExitFunctionBodyRAII {
15520 public:
15521   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15522   ~ExitFunctionBodyRAII() {
15523     if (!IsLambda)
15524       S.PopExpressionEvaluationContext();
15525   }
15526 
15527 private:
15528   Sema &S;
15529   bool IsLambda = false;
15530 };
15531 
15532 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15533   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15534 
15535   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15536     if (EscapeInfo.count(BD))
15537       return EscapeInfo[BD];
15538 
15539     bool R = false;
15540     const BlockDecl *CurBD = BD;
15541 
15542     do {
15543       R = !CurBD->doesNotEscape();
15544       if (R)
15545         break;
15546       CurBD = CurBD->getParent()->getInnermostBlockDecl();
15547     } while (CurBD);
15548 
15549     return EscapeInfo[BD] = R;
15550   };
15551 
15552   // If the location where 'self' is implicitly retained is inside a escaping
15553   // block, emit a diagnostic.
15554   for (const std::pair<SourceLocation, const BlockDecl *> &P :
15555        S.ImplicitlyRetainedSelfLocs)
15556     if (IsOrNestedInEscapingBlock(P.second))
15557       S.Diag(P.first, diag::warn_implicitly_retains_self)
15558           << FixItHint::CreateInsertion(P.first, "self->");
15559 }
15560 
15561 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15562                                     bool IsInstantiation) {
15563   FunctionScopeInfo *FSI = getCurFunction();
15564   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15565 
15566   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15567     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15568 
15569   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15570   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15571 
15572   if (getLangOpts().Coroutines && FSI->isCoroutine())
15573     CheckCompletedCoroutineBody(FD, Body);
15574 
15575   {
15576     // Do not call PopExpressionEvaluationContext() if it is a lambda because
15577     // one is already popped when finishing the lambda in BuildLambdaExpr().
15578     // This is meant to pop the context added in ActOnStartOfFunctionDef().
15579     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15580     if (FD) {
15581       FD->setBody(Body);
15582       FD->setWillHaveBody(false);
15583       CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15584 
15585       if (getLangOpts().CPlusPlus14) {
15586         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15587             FD->getReturnType()->isUndeducedType()) {
15588           // For a function with a deduced result type to return void,
15589           // the result type as written must be 'auto' or 'decltype(auto)',
15590           // possibly cv-qualified or constrained, but not ref-qualified.
15591           if (!FD->getReturnType()->getAs<AutoType>()) {
15592             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15593                 << FD->getReturnType();
15594             FD->setInvalidDecl();
15595           } else {
15596             // Falling off the end of the function is the same as 'return;'.
15597             Expr *Dummy = nullptr;
15598             if (DeduceFunctionTypeFromReturnExpr(
15599                     FD, dcl->getLocation(), Dummy,
15600                     FD->getReturnType()->getAs<AutoType>()))
15601               FD->setInvalidDecl();
15602           }
15603         }
15604       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15605         // In C++11, we don't use 'auto' deduction rules for lambda call
15606         // operators because we don't support return type deduction.
15607         auto *LSI = getCurLambda();
15608         if (LSI->HasImplicitReturnType) {
15609           deduceClosureReturnType(*LSI);
15610 
15611           // C++11 [expr.prim.lambda]p4:
15612           //   [...] if there are no return statements in the compound-statement
15613           //   [the deduced type is] the type void
15614           QualType RetType =
15615               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15616 
15617           // Update the return type to the deduced type.
15618           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15619           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15620                                               Proto->getExtProtoInfo()));
15621         }
15622       }
15623 
15624       // If the function implicitly returns zero (like 'main') or is naked,
15625       // don't complain about missing return statements.
15626       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15627         WP.disableCheckFallThrough();
15628 
15629       // MSVC permits the use of pure specifier (=0) on function definition,
15630       // defined at class scope, warn about this non-standard construct.
15631       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15632         Diag(FD->getLocation(), diag::ext_pure_function_definition);
15633 
15634       if (!FD->isInvalidDecl()) {
15635         // Don't diagnose unused parameters of defaulted, deleted or naked
15636         // functions.
15637         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15638             !FD->hasAttr<NakedAttr>())
15639           DiagnoseUnusedParameters(FD->parameters());
15640         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15641                                                FD->getReturnType(), FD);
15642 
15643         // If this is a structor, we need a vtable.
15644         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15645           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15646         else if (CXXDestructorDecl *Destructor =
15647                      dyn_cast<CXXDestructorDecl>(FD))
15648           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15649 
15650         // Try to apply the named return value optimization. We have to check
15651         // if we can do this here because lambdas keep return statements around
15652         // to deduce an implicit return type.
15653         if (FD->getReturnType()->isRecordType() &&
15654             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15655           computeNRVO(Body, FSI);
15656       }
15657 
15658       // GNU warning -Wmissing-prototypes:
15659       //   Warn if a global function is defined without a previous
15660       //   prototype declaration. This warning is issued even if the
15661       //   definition itself provides a prototype. The aim is to detect
15662       //   global functions that fail to be declared in header files.
15663       const FunctionDecl *PossiblePrototype = nullptr;
15664       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15665         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15666 
15667         if (PossiblePrototype) {
15668           // We found a declaration that is not a prototype,
15669           // but that could be a zero-parameter prototype
15670           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15671             TypeLoc TL = TI->getTypeLoc();
15672             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15673               Diag(PossiblePrototype->getLocation(),
15674                    diag::note_declaration_not_a_prototype)
15675                   << (FD->getNumParams() != 0)
15676                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15677                                                     FTL.getRParenLoc(), "void")
15678                                               : FixItHint{});
15679           }
15680         } else {
15681           // Returns true if the token beginning at this Loc is `const`.
15682           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15683                                   const LangOptions &LangOpts) {
15684             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15685             if (LocInfo.first.isInvalid())
15686               return false;
15687 
15688             bool Invalid = false;
15689             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15690             if (Invalid)
15691               return false;
15692 
15693             if (LocInfo.second > Buffer.size())
15694               return false;
15695 
15696             const char *LexStart = Buffer.data() + LocInfo.second;
15697             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15698 
15699             return StartTok.consume_front("const") &&
15700                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15701                     StartTok.startswith("/*") || StartTok.startswith("//"));
15702           };
15703 
15704           auto findBeginLoc = [&]() {
15705             // If the return type has `const` qualifier, we want to insert
15706             // `static` before `const` (and not before the typename).
15707             if ((FD->getReturnType()->isAnyPointerType() &&
15708                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15709                 FD->getReturnType().isConstQualified()) {
15710               // But only do this if we can determine where the `const` is.
15711 
15712               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15713                                getLangOpts()))
15714 
15715                 return FD->getBeginLoc();
15716             }
15717             return FD->getTypeSpecStartLoc();
15718           };
15719           Diag(FD->getTypeSpecStartLoc(),
15720                diag::note_static_for_internal_linkage)
15721               << /* function */ 1
15722               << (FD->getStorageClass() == SC_None
15723                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15724                       : FixItHint{});
15725         }
15726       }
15727 
15728       // We might not have found a prototype because we didn't wish to warn on
15729       // the lack of a missing prototype. Try again without the checks for
15730       // whether we want to warn on the missing prototype.
15731       if (!PossiblePrototype)
15732         (void)FindPossiblePrototype(FD, PossiblePrototype);
15733 
15734       // If the function being defined does not have a prototype, then we may
15735       // need to diagnose it as changing behavior in C2x because we now know
15736       // whether the function accepts arguments or not. This only handles the
15737       // case where the definition has no prototype but does have parameters
15738       // and either there is no previous potential prototype, or the previous
15739       // potential prototype also has no actual prototype. This handles cases
15740       // like:
15741       //   void f(); void f(a) int a; {}
15742       //   void g(a) int a; {}
15743       // See MergeFunctionDecl() for other cases of the behavior change
15744       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15745       // type without a prototype.
15746       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15747           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15748                                   !PossiblePrototype->isImplicit()))) {
15749         // The function definition has parameters, so this will change behavior
15750         // in C2x. If there is a possible prototype, it comes before the
15751         // function definition.
15752         // FIXME: The declaration may have already been diagnosed as being
15753         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15754         // there's no way to test for the "changes behavior" condition in
15755         // SemaType.cpp when forming the declaration's function type. So, we do
15756         // this awkward dance instead.
15757         //
15758         // If we have a possible prototype and it declares a function with a
15759         // prototype, we don't want to diagnose it; if we have a possible
15760         // prototype and it has no prototype, it may have already been
15761         // diagnosed in SemaType.cpp as deprecated depending on whether
15762         // -Wstrict-prototypes is enabled. If we already warned about it being
15763         // deprecated, add a note that it also changes behavior. If we didn't
15764         // warn about it being deprecated (because the diagnostic is not
15765         // enabled), warn now that it is deprecated and changes behavior.
15766 
15767         // This K&R C function definition definitely changes behavior in C2x,
15768         // so diagnose it.
15769         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15770             << /*definition*/ 1 << /* not supported in C2x */ 0;
15771 
15772         // If we have a possible prototype for the function which is a user-
15773         // visible declaration, we already tested that it has no prototype.
15774         // This will change behavior in C2x. This gets a warning rather than a
15775         // note because it's the same behavior-changing problem as with the
15776         // definition.
15777         if (PossiblePrototype)
15778           Diag(PossiblePrototype->getLocation(),
15779                diag::warn_non_prototype_changes_behavior)
15780               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15781               << /*definition*/ 1;
15782       }
15783 
15784       // Warn on CPUDispatch with an actual body.
15785       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15786         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15787           if (!CmpndBody->body_empty())
15788             Diag(CmpndBody->body_front()->getBeginLoc(),
15789                  diag::warn_dispatch_body_ignored);
15790 
15791       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15792         const CXXMethodDecl *KeyFunction;
15793         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15794             MD->isVirtual() &&
15795             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15796             MD == KeyFunction->getCanonicalDecl()) {
15797           // Update the key-function state if necessary for this ABI.
15798           if (FD->isInlined() &&
15799               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15800             Context.setNonKeyFunction(MD);
15801 
15802             // If the newly-chosen key function is already defined, then we
15803             // need to mark the vtable as used retroactively.
15804             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15805             const FunctionDecl *Definition;
15806             if (KeyFunction && KeyFunction->isDefined(Definition))
15807               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15808           } else {
15809             // We just defined they key function; mark the vtable as used.
15810             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15811           }
15812         }
15813       }
15814 
15815       assert(
15816           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15817           "Function parsing confused");
15818     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15819       assert(MD == getCurMethodDecl() && "Method parsing confused");
15820       MD->setBody(Body);
15821       if (!MD->isInvalidDecl()) {
15822         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15823                                                MD->getReturnType(), MD);
15824 
15825         if (Body)
15826           computeNRVO(Body, FSI);
15827       }
15828       if (FSI->ObjCShouldCallSuper) {
15829         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15830             << MD->getSelector().getAsString();
15831         FSI->ObjCShouldCallSuper = false;
15832       }
15833       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15834         const ObjCMethodDecl *InitMethod = nullptr;
15835         bool isDesignated =
15836             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15837         assert(isDesignated && InitMethod);
15838         (void)isDesignated;
15839 
15840         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15841           auto IFace = MD->getClassInterface();
15842           if (!IFace)
15843             return false;
15844           auto SuperD = IFace->getSuperClass();
15845           if (!SuperD)
15846             return false;
15847           return SuperD->getIdentifier() ==
15848                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15849         };
15850         // Don't issue this warning for unavailable inits or direct subclasses
15851         // of NSObject.
15852         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15853           Diag(MD->getLocation(),
15854                diag::warn_objc_designated_init_missing_super_call);
15855           Diag(InitMethod->getLocation(),
15856                diag::note_objc_designated_init_marked_here);
15857         }
15858         FSI->ObjCWarnForNoDesignatedInitChain = false;
15859       }
15860       if (FSI->ObjCWarnForNoInitDelegation) {
15861         // Don't issue this warning for unavaialable inits.
15862         if (!MD->isUnavailable())
15863           Diag(MD->getLocation(),
15864                diag::warn_objc_secondary_init_missing_init_call);
15865         FSI->ObjCWarnForNoInitDelegation = false;
15866       }
15867 
15868       diagnoseImplicitlyRetainedSelf(*this);
15869     } else {
15870       // Parsing the function declaration failed in some way. Pop the fake scope
15871       // we pushed on.
15872       PopFunctionScopeInfo(ActivePolicy, dcl);
15873       return nullptr;
15874     }
15875 
15876     if (Body && FSI->HasPotentialAvailabilityViolations)
15877       DiagnoseUnguardedAvailabilityViolations(dcl);
15878 
15879     assert(!FSI->ObjCShouldCallSuper &&
15880            "This should only be set for ObjC methods, which should have been "
15881            "handled in the block above.");
15882 
15883     // Verify and clean out per-function state.
15884     if (Body && (!FD || !FD->isDefaulted())) {
15885       // C++ constructors that have function-try-blocks can't have return
15886       // statements in the handlers of that block. (C++ [except.handle]p14)
15887       // Verify this.
15888       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15889         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15890 
15891       // Verify that gotos and switch cases don't jump into scopes illegally.
15892       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15893         DiagnoseInvalidJumps(Body);
15894 
15895       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15896         if (!Destructor->getParent()->isDependentType())
15897           CheckDestructor(Destructor);
15898 
15899         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15900                                                Destructor->getParent());
15901       }
15902 
15903       // If any errors have occurred, clear out any temporaries that may have
15904       // been leftover. This ensures that these temporaries won't be picked up
15905       // for deletion in some later function.
15906       if (hasUncompilableErrorOccurred() ||
15907           getDiagnostics().getSuppressAllDiagnostics()) {
15908         DiscardCleanupsInEvaluationContext();
15909       }
15910       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15911         // Since the body is valid, issue any analysis-based warnings that are
15912         // enabled.
15913         ActivePolicy = &WP;
15914       }
15915 
15916       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15917           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15918         FD->setInvalidDecl();
15919 
15920       if (FD && FD->hasAttr<NakedAttr>()) {
15921         for (const Stmt *S : Body->children()) {
15922           // Allow local register variables without initializer as they don't
15923           // require prologue.
15924           bool RegisterVariables = false;
15925           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15926             for (const auto *Decl : DS->decls()) {
15927               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15928                 RegisterVariables =
15929                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15930                 if (!RegisterVariables)
15931                   break;
15932               }
15933             }
15934           }
15935           if (RegisterVariables)
15936             continue;
15937           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15938             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15939             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15940             FD->setInvalidDecl();
15941             break;
15942           }
15943         }
15944       }
15945 
15946       assert(ExprCleanupObjects.size() ==
15947                  ExprEvalContexts.back().NumCleanupObjects &&
15948              "Leftover temporaries in function");
15949       assert(!Cleanup.exprNeedsCleanups() &&
15950              "Unaccounted cleanups in function");
15951       assert(MaybeODRUseExprs.empty() &&
15952              "Leftover expressions for odr-use checking");
15953     }
15954   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15955     // the declaration context below. Otherwise, we're unable to transform
15956     // 'this' expressions when transforming immediate context functions.
15957 
15958   if (!IsInstantiation)
15959     PopDeclContext();
15960 
15961   PopFunctionScopeInfo(ActivePolicy, dcl);
15962   // If any errors have occurred, clear out any temporaries that may have
15963   // been leftover. This ensures that these temporaries won't be picked up for
15964   // deletion in some later function.
15965   if (hasUncompilableErrorOccurred()) {
15966     DiscardCleanupsInEvaluationContext();
15967   }
15968 
15969   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
15970                                   !LangOpts.OMPTargetTriples.empty())) ||
15971              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15972     auto ES = getEmissionStatus(FD);
15973     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15974         ES == Sema::FunctionEmissionStatus::Unknown)
15975       DeclsToCheckForDeferredDiags.insert(FD);
15976   }
15977 
15978   if (FD && !FD->isDeleted())
15979     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15980 
15981   return dcl;
15982 }
15983 
15984 /// When we finish delayed parsing of an attribute, we must attach it to the
15985 /// relevant Decl.
15986 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15987                                        ParsedAttributes &Attrs) {
15988   // Always attach attributes to the underlying decl.
15989   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15990     D = TD->getTemplatedDecl();
15991   ProcessDeclAttributeList(S, D, Attrs);
15992 
15993   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15994     if (Method->isStatic())
15995       checkThisInStaticMemberFunctionAttributes(Method);
15996 }
15997 
15998 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15999 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16000 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16001                                           IdentifierInfo &II, Scope *S) {
16002   // It is not valid to implicitly define a function in C2x.
16003   assert(LangOpts.implicitFunctionsAllowed() &&
16004          "Implicit function declarations aren't allowed in this language mode");
16005 
16006   // Find the scope in which the identifier is injected and the corresponding
16007   // DeclContext.
16008   // FIXME: C89 does not say what happens if there is no enclosing block scope.
16009   // In that case, we inject the declaration into the translation unit scope
16010   // instead.
16011   Scope *BlockScope = S;
16012   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16013     BlockScope = BlockScope->getParent();
16014 
16015   // Loop until we find a DeclContext that is either a function/method or the
16016   // translation unit, which are the only two valid places to implicitly define
16017   // a function. This avoids accidentally defining the function within a tag
16018   // declaration, for example.
16019   Scope *ContextScope = BlockScope;
16020   while (!ContextScope->getEntity() ||
16021          (!ContextScope->getEntity()->isFunctionOrMethod() &&
16022           !ContextScope->getEntity()->isTranslationUnit()))
16023     ContextScope = ContextScope->getParent();
16024   ContextRAII SavedContext(*this, ContextScope->getEntity());
16025 
16026   // Before we produce a declaration for an implicitly defined
16027   // function, see whether there was a locally-scoped declaration of
16028   // this name as a function or variable. If so, use that
16029   // (non-visible) declaration, and complain about it.
16030   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16031   if (ExternCPrev) {
16032     // We still need to inject the function into the enclosing block scope so
16033     // that later (non-call) uses can see it.
16034     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16035 
16036     // C89 footnote 38:
16037     //   If in fact it is not defined as having type "function returning int",
16038     //   the behavior is undefined.
16039     if (!isa<FunctionDecl>(ExternCPrev) ||
16040         !Context.typesAreCompatible(
16041             cast<FunctionDecl>(ExternCPrev)->getType(),
16042             Context.getFunctionNoProtoType(Context.IntTy))) {
16043       Diag(Loc, diag::ext_use_out_of_scope_declaration)
16044           << ExternCPrev << !getLangOpts().C99;
16045       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16046       return ExternCPrev;
16047     }
16048   }
16049 
16050   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16051   unsigned diag_id;
16052   if (II.getName().startswith("__builtin_"))
16053     diag_id = diag::warn_builtin_unknown;
16054   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16055   else if (getLangOpts().C99)
16056     diag_id = diag::ext_implicit_function_decl_c99;
16057   else
16058     diag_id = diag::warn_implicit_function_decl;
16059 
16060   TypoCorrection Corrected;
16061   // Because typo correction is expensive, only do it if the implicit
16062   // function declaration is going to be treated as an error.
16063   //
16064   // Perform the correction before issuing the main diagnostic, as some
16065   // consumers use typo-correction callbacks to enhance the main diagnostic.
16066   if (S && !ExternCPrev &&
16067       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16068     DeclFilterCCC<FunctionDecl> CCC{};
16069     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16070                             S, nullptr, CCC, CTK_NonError);
16071   }
16072 
16073   Diag(Loc, diag_id) << &II;
16074   if (Corrected) {
16075     // If the correction is going to suggest an implicitly defined function,
16076     // skip the correction as not being a particularly good idea.
16077     bool Diagnose = true;
16078     if (const auto *D = Corrected.getCorrectionDecl())
16079       Diagnose = !D->isImplicit();
16080     if (Diagnose)
16081       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16082                    /*ErrorRecovery*/ false);
16083   }
16084 
16085   // If we found a prior declaration of this function, don't bother building
16086   // another one. We've already pushed that one into scope, so there's nothing
16087   // more to do.
16088   if (ExternCPrev)
16089     return ExternCPrev;
16090 
16091   // Set a Declarator for the implicit definition: int foo();
16092   const char *Dummy;
16093   AttributeFactory attrFactory;
16094   DeclSpec DS(attrFactory);
16095   unsigned DiagID;
16096   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16097                                   Context.getPrintingPolicy());
16098   (void)Error; // Silence warning.
16099   assert(!Error && "Error setting up implicit decl!");
16100   SourceLocation NoLoc;
16101   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16102   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16103                                              /*IsAmbiguous=*/false,
16104                                              /*LParenLoc=*/NoLoc,
16105                                              /*Params=*/nullptr,
16106                                              /*NumParams=*/0,
16107                                              /*EllipsisLoc=*/NoLoc,
16108                                              /*RParenLoc=*/NoLoc,
16109                                              /*RefQualifierIsLvalueRef=*/true,
16110                                              /*RefQualifierLoc=*/NoLoc,
16111                                              /*MutableLoc=*/NoLoc, EST_None,
16112                                              /*ESpecRange=*/SourceRange(),
16113                                              /*Exceptions=*/nullptr,
16114                                              /*ExceptionRanges=*/nullptr,
16115                                              /*NumExceptions=*/0,
16116                                              /*NoexceptExpr=*/nullptr,
16117                                              /*ExceptionSpecTokens=*/nullptr,
16118                                              /*DeclsInPrototype=*/std::nullopt,
16119                                              Loc, Loc, D),
16120                 std::move(DS.getAttributes()), SourceLocation());
16121   D.SetIdentifier(&II, Loc);
16122 
16123   // Insert this function into the enclosing block scope.
16124   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16125   FD->setImplicit();
16126 
16127   AddKnownFunctionAttributes(FD);
16128 
16129   return FD;
16130 }
16131 
16132 /// If this function is a C++ replaceable global allocation function
16133 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16134 /// adds any function attributes that we know a priori based on the standard.
16135 ///
16136 /// We need to check for duplicate attributes both here and where user-written
16137 /// attributes are applied to declarations.
16138 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16139     FunctionDecl *FD) {
16140   if (FD->isInvalidDecl())
16141     return;
16142 
16143   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16144       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16145     return;
16146 
16147   std::optional<unsigned> AlignmentParam;
16148   bool IsNothrow = false;
16149   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16150     return;
16151 
16152   // C++2a [basic.stc.dynamic.allocation]p4:
16153   //   An allocation function that has a non-throwing exception specification
16154   //   indicates failure by returning a null pointer value. Any other allocation
16155   //   function never returns a null pointer value and indicates failure only by
16156   //   throwing an exception [...]
16157   //
16158   // However, -fcheck-new invalidates this possible assumption, so don't add
16159   // NonNull when that is enabled.
16160   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16161       !getLangOpts().CheckNew)
16162     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16163 
16164   // C++2a [basic.stc.dynamic.allocation]p2:
16165   //   An allocation function attempts to allocate the requested amount of
16166   //   storage. [...] If the request succeeds, the value returned by a
16167   //   replaceable allocation function is a [...] pointer value p0 different
16168   //   from any previously returned value p1 [...]
16169   //
16170   // However, this particular information is being added in codegen,
16171   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16172 
16173   // C++2a [basic.stc.dynamic.allocation]p2:
16174   //   An allocation function attempts to allocate the requested amount of
16175   //   storage. If it is successful, it returns the address of the start of a
16176   //   block of storage whose length in bytes is at least as large as the
16177   //   requested size.
16178   if (!FD->hasAttr<AllocSizeAttr>()) {
16179     FD->addAttr(AllocSizeAttr::CreateImplicit(
16180         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16181         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16182   }
16183 
16184   // C++2a [basic.stc.dynamic.allocation]p3:
16185   //   For an allocation function [...], the pointer returned on a successful
16186   //   call shall represent the address of storage that is aligned as follows:
16187   //   (3.1) If the allocation function takes an argument of type
16188   //         std​::​align_­val_­t, the storage will have the alignment
16189   //         specified by the value of this argument.
16190   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16191     FD->addAttr(AllocAlignAttr::CreateImplicit(
16192         Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16193   }
16194 
16195   // FIXME:
16196   // C++2a [basic.stc.dynamic.allocation]p3:
16197   //   For an allocation function [...], the pointer returned on a successful
16198   //   call shall represent the address of storage that is aligned as follows:
16199   //   (3.2) Otherwise, if the allocation function is named operator new[],
16200   //         the storage is aligned for any object that does not have
16201   //         new-extended alignment ([basic.align]) and is no larger than the
16202   //         requested size.
16203   //   (3.3) Otherwise, the storage is aligned for any object that does not
16204   //         have new-extended alignment and is of the requested size.
16205 }
16206 
16207 /// Adds any function attributes that we know a priori based on
16208 /// the declaration of this function.
16209 ///
16210 /// These attributes can apply both to implicitly-declared builtins
16211 /// (like __builtin___printf_chk) or to library-declared functions
16212 /// like NSLog or printf.
16213 ///
16214 /// We need to check for duplicate attributes both here and where user-written
16215 /// attributes are applied to declarations.
16216 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16217   if (FD->isInvalidDecl())
16218     return;
16219 
16220   // If this is a built-in function, map its builtin attributes to
16221   // actual attributes.
16222   if (unsigned BuiltinID = FD->getBuiltinID()) {
16223     // Handle printf-formatting attributes.
16224     unsigned FormatIdx;
16225     bool HasVAListArg;
16226     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16227       if (!FD->hasAttr<FormatAttr>()) {
16228         const char *fmt = "printf";
16229         unsigned int NumParams = FD->getNumParams();
16230         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16231             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16232           fmt = "NSString";
16233         FD->addAttr(FormatAttr::CreateImplicit(Context,
16234                                                &Context.Idents.get(fmt),
16235                                                FormatIdx+1,
16236                                                HasVAListArg ? 0 : FormatIdx+2,
16237                                                FD->getLocation()));
16238       }
16239     }
16240     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16241                                              HasVAListArg)) {
16242      if (!FD->hasAttr<FormatAttr>())
16243        FD->addAttr(FormatAttr::CreateImplicit(Context,
16244                                               &Context.Idents.get("scanf"),
16245                                               FormatIdx+1,
16246                                               HasVAListArg ? 0 : FormatIdx+2,
16247                                               FD->getLocation()));
16248     }
16249 
16250     // Handle automatically recognized callbacks.
16251     SmallVector<int, 4> Encoding;
16252     if (!FD->hasAttr<CallbackAttr>() &&
16253         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16254       FD->addAttr(CallbackAttr::CreateImplicit(
16255           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16256 
16257     // Mark const if we don't care about errno and/or floating point exceptions
16258     // that are the only thing preventing the function from being const. This
16259     // allows IRgen to use LLVM intrinsics for such functions.
16260     bool NoExceptions =
16261         getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16262     bool ConstWithoutErrnoAndExceptions =
16263         Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16264     bool ConstWithoutExceptions =
16265         Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16266     if (!FD->hasAttr<ConstAttr>() &&
16267         (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16268         (!ConstWithoutErrnoAndExceptions ||
16269          (!getLangOpts().MathErrno && NoExceptions)) &&
16270         (!ConstWithoutExceptions || NoExceptions))
16271       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16272 
16273     // We make "fma" on GNU or Windows const because we know it does not set
16274     // errno in those environments even though it could set errno based on the
16275     // C standard.
16276     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16277     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16278         !FD->hasAttr<ConstAttr>()) {
16279       switch (BuiltinID) {
16280       case Builtin::BI__builtin_fma:
16281       case Builtin::BI__builtin_fmaf:
16282       case Builtin::BI__builtin_fmal:
16283       case Builtin::BIfma:
16284       case Builtin::BIfmaf:
16285       case Builtin::BIfmal:
16286         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16287         break;
16288       default:
16289         break;
16290       }
16291     }
16292 
16293     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16294         !FD->hasAttr<ReturnsTwiceAttr>())
16295       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16296                                          FD->getLocation()));
16297     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16298       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16299     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16300       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16301     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16302       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16303     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16304         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16305       // Add the appropriate attribute, depending on the CUDA compilation mode
16306       // and which target the builtin belongs to. For example, during host
16307       // compilation, aux builtins are __device__, while the rest are __host__.
16308       if (getLangOpts().CUDAIsDevice !=
16309           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16310         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16311       else
16312         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16313     }
16314 
16315     // Add known guaranteed alignment for allocation functions.
16316     switch (BuiltinID) {
16317     case Builtin::BImemalign:
16318     case Builtin::BIaligned_alloc:
16319       if (!FD->hasAttr<AllocAlignAttr>())
16320         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16321                                                    FD->getLocation()));
16322       break;
16323     default:
16324       break;
16325     }
16326 
16327     // Add allocsize attribute for allocation functions.
16328     switch (BuiltinID) {
16329     case Builtin::BIcalloc:
16330       FD->addAttr(AllocSizeAttr::CreateImplicit(
16331           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16332       break;
16333     case Builtin::BImemalign:
16334     case Builtin::BIaligned_alloc:
16335     case Builtin::BIrealloc:
16336       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16337                                                 ParamIdx(), FD->getLocation()));
16338       break;
16339     case Builtin::BImalloc:
16340       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16341                                                 ParamIdx(), FD->getLocation()));
16342       break;
16343     default:
16344       break;
16345     }
16346 
16347     // Add lifetime attribute to std::move, std::fowrard et al.
16348     switch (BuiltinID) {
16349     case Builtin::BIaddressof:
16350     case Builtin::BI__addressof:
16351     case Builtin::BI__builtin_addressof:
16352     case Builtin::BIas_const:
16353     case Builtin::BIforward:
16354     case Builtin::BIforward_like:
16355     case Builtin::BImove:
16356     case Builtin::BImove_if_noexcept:
16357       if (ParmVarDecl *P = FD->getParamDecl(0u);
16358           !P->hasAttr<LifetimeBoundAttr>())
16359         P->addAttr(
16360             LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16361       break;
16362     default:
16363       break;
16364     }
16365   }
16366 
16367   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16368 
16369   // If C++ exceptions are enabled but we are told extern "C" functions cannot
16370   // throw, add an implicit nothrow attribute to any extern "C" function we come
16371   // across.
16372   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16373       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16374     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16375     if (!FPT || FPT->getExceptionSpecType() == EST_None)
16376       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16377   }
16378 
16379   IdentifierInfo *Name = FD->getIdentifier();
16380   if (!Name)
16381     return;
16382   if ((!getLangOpts().CPlusPlus &&
16383        FD->getDeclContext()->isTranslationUnit()) ||
16384       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16385        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16386        LinkageSpecDecl::lang_c)) {
16387     // Okay: this could be a libc/libm/Objective-C function we know
16388     // about.
16389   } else
16390     return;
16391 
16392   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16393     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16394     // target-specific builtins, perhaps?
16395     if (!FD->hasAttr<FormatAttr>())
16396       FD->addAttr(FormatAttr::CreateImplicit(Context,
16397                                              &Context.Idents.get("printf"), 2,
16398                                              Name->isStr("vasprintf") ? 0 : 3,
16399                                              FD->getLocation()));
16400   }
16401 
16402   if (Name->isStr("__CFStringMakeConstantString")) {
16403     // We already have a __builtin___CFStringMakeConstantString,
16404     // but builds that use -fno-constant-cfstrings don't go through that.
16405     if (!FD->hasAttr<FormatArgAttr>())
16406       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16407                                                 FD->getLocation()));
16408   }
16409 }
16410 
16411 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16412                                     TypeSourceInfo *TInfo) {
16413   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16414   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16415 
16416   if (!TInfo) {
16417     assert(D.isInvalidType() && "no declarator info for valid type");
16418     TInfo = Context.getTrivialTypeSourceInfo(T);
16419   }
16420 
16421   // Scope manipulation handled by caller.
16422   TypedefDecl *NewTD =
16423       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16424                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16425 
16426   // Bail out immediately if we have an invalid declaration.
16427   if (D.isInvalidType()) {
16428     NewTD->setInvalidDecl();
16429     return NewTD;
16430   }
16431 
16432   if (D.getDeclSpec().isModulePrivateSpecified()) {
16433     if (CurContext->isFunctionOrMethod())
16434       Diag(NewTD->getLocation(), diag::err_module_private_local)
16435           << 2 << NewTD
16436           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16437           << FixItHint::CreateRemoval(
16438                  D.getDeclSpec().getModulePrivateSpecLoc());
16439     else
16440       NewTD->setModulePrivate();
16441   }
16442 
16443   // C++ [dcl.typedef]p8:
16444   //   If the typedef declaration defines an unnamed class (or
16445   //   enum), the first typedef-name declared by the declaration
16446   //   to be that class type (or enum type) is used to denote the
16447   //   class type (or enum type) for linkage purposes only.
16448   // We need to check whether the type was declared in the declaration.
16449   switch (D.getDeclSpec().getTypeSpecType()) {
16450   case TST_enum:
16451   case TST_struct:
16452   case TST_interface:
16453   case TST_union:
16454   case TST_class: {
16455     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16456     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16457     break;
16458   }
16459 
16460   default:
16461     break;
16462   }
16463 
16464   return NewTD;
16465 }
16466 
16467 /// Check that this is a valid underlying type for an enum declaration.
16468 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16469   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16470   QualType T = TI->getType();
16471 
16472   if (T->isDependentType())
16473     return false;
16474 
16475   // This doesn't use 'isIntegralType' despite the error message mentioning
16476   // integral type because isIntegralType would also allow enum types in C.
16477   if (const BuiltinType *BT = T->getAs<BuiltinType>())
16478     if (BT->isInteger())
16479       return false;
16480 
16481   if (T->isBitIntType())
16482     return false;
16483 
16484   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16485 }
16486 
16487 /// Check whether this is a valid redeclaration of a previous enumeration.
16488 /// \return true if the redeclaration was invalid.
16489 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16490                                   QualType EnumUnderlyingTy, bool IsFixed,
16491                                   const EnumDecl *Prev) {
16492   if (IsScoped != Prev->isScoped()) {
16493     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16494       << Prev->isScoped();
16495     Diag(Prev->getLocation(), diag::note_previous_declaration);
16496     return true;
16497   }
16498 
16499   if (IsFixed && Prev->isFixed()) {
16500     if (!EnumUnderlyingTy->isDependentType() &&
16501         !Prev->getIntegerType()->isDependentType() &&
16502         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16503                                         Prev->getIntegerType())) {
16504       // TODO: Highlight the underlying type of the redeclaration.
16505       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16506         << EnumUnderlyingTy << Prev->getIntegerType();
16507       Diag(Prev->getLocation(), diag::note_previous_declaration)
16508           << Prev->getIntegerTypeRange();
16509       return true;
16510     }
16511   } else if (IsFixed != Prev->isFixed()) {
16512     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16513       << Prev->isFixed();
16514     Diag(Prev->getLocation(), diag::note_previous_declaration);
16515     return true;
16516   }
16517 
16518   return false;
16519 }
16520 
16521 /// Get diagnostic %select index for tag kind for
16522 /// redeclaration diagnostic message.
16523 /// WARNING: Indexes apply to particular diagnostics only!
16524 ///
16525 /// \returns diagnostic %select index.
16526 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16527   switch (Tag) {
16528   case TTK_Struct: return 0;
16529   case TTK_Interface: return 1;
16530   case TTK_Class:  return 2;
16531   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16532   }
16533 }
16534 
16535 /// Determine if tag kind is a class-key compatible with
16536 /// class for redeclaration (class, struct, or __interface).
16537 ///
16538 /// \returns true iff the tag kind is compatible.
16539 static bool isClassCompatTagKind(TagTypeKind Tag)
16540 {
16541   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16542 }
16543 
16544 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16545                                              TagTypeKind TTK) {
16546   if (isa<TypedefDecl>(PrevDecl))
16547     return NTK_Typedef;
16548   else if (isa<TypeAliasDecl>(PrevDecl))
16549     return NTK_TypeAlias;
16550   else if (isa<ClassTemplateDecl>(PrevDecl))
16551     return NTK_Template;
16552   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16553     return NTK_TypeAliasTemplate;
16554   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16555     return NTK_TemplateTemplateArgument;
16556   switch (TTK) {
16557   case TTK_Struct:
16558   case TTK_Interface:
16559   case TTK_Class:
16560     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16561   case TTK_Union:
16562     return NTK_NonUnion;
16563   case TTK_Enum:
16564     return NTK_NonEnum;
16565   }
16566   llvm_unreachable("invalid TTK");
16567 }
16568 
16569 /// Determine whether a tag with a given kind is acceptable
16570 /// as a redeclaration of the given tag declaration.
16571 ///
16572 /// \returns true if the new tag kind is acceptable, false otherwise.
16573 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16574                                         TagTypeKind NewTag, bool isDefinition,
16575                                         SourceLocation NewTagLoc,
16576                                         const IdentifierInfo *Name) {
16577   // C++ [dcl.type.elab]p3:
16578   //   The class-key or enum keyword present in the
16579   //   elaborated-type-specifier shall agree in kind with the
16580   //   declaration to which the name in the elaborated-type-specifier
16581   //   refers. This rule also applies to the form of
16582   //   elaborated-type-specifier that declares a class-name or
16583   //   friend class since it can be construed as referring to the
16584   //   definition of the class. Thus, in any
16585   //   elaborated-type-specifier, the enum keyword shall be used to
16586   //   refer to an enumeration (7.2), the union class-key shall be
16587   //   used to refer to a union (clause 9), and either the class or
16588   //   struct class-key shall be used to refer to a class (clause 9)
16589   //   declared using the class or struct class-key.
16590   TagTypeKind OldTag = Previous->getTagKind();
16591   if (OldTag != NewTag &&
16592       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16593     return false;
16594 
16595   // Tags are compatible, but we might still want to warn on mismatched tags.
16596   // Non-class tags can't be mismatched at this point.
16597   if (!isClassCompatTagKind(NewTag))
16598     return true;
16599 
16600   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16601   // by our warning analysis. We don't want to warn about mismatches with (eg)
16602   // declarations in system headers that are designed to be specialized, but if
16603   // a user asks us to warn, we should warn if their code contains mismatched
16604   // declarations.
16605   auto IsIgnoredLoc = [&](SourceLocation Loc) {
16606     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16607                                       Loc);
16608   };
16609   if (IsIgnoredLoc(NewTagLoc))
16610     return true;
16611 
16612   auto IsIgnored = [&](const TagDecl *Tag) {
16613     return IsIgnoredLoc(Tag->getLocation());
16614   };
16615   while (IsIgnored(Previous)) {
16616     Previous = Previous->getPreviousDecl();
16617     if (!Previous)
16618       return true;
16619     OldTag = Previous->getTagKind();
16620   }
16621 
16622   bool isTemplate = false;
16623   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16624     isTemplate = Record->getDescribedClassTemplate();
16625 
16626   if (inTemplateInstantiation()) {
16627     if (OldTag != NewTag) {
16628       // In a template instantiation, do not offer fix-its for tag mismatches
16629       // since they usually mess up the template instead of fixing the problem.
16630       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16631         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16632         << getRedeclDiagFromTagKind(OldTag);
16633       // FIXME: Note previous location?
16634     }
16635     return true;
16636   }
16637 
16638   if (isDefinition) {
16639     // On definitions, check all previous tags and issue a fix-it for each
16640     // one that doesn't match the current tag.
16641     if (Previous->getDefinition()) {
16642       // Don't suggest fix-its for redefinitions.
16643       return true;
16644     }
16645 
16646     bool previousMismatch = false;
16647     for (const TagDecl *I : Previous->redecls()) {
16648       if (I->getTagKind() != NewTag) {
16649         // Ignore previous declarations for which the warning was disabled.
16650         if (IsIgnored(I))
16651           continue;
16652 
16653         if (!previousMismatch) {
16654           previousMismatch = true;
16655           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16656             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16657             << getRedeclDiagFromTagKind(I->getTagKind());
16658         }
16659         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16660           << getRedeclDiagFromTagKind(NewTag)
16661           << FixItHint::CreateReplacement(I->getInnerLocStart(),
16662                TypeWithKeyword::getTagTypeKindName(NewTag));
16663       }
16664     }
16665     return true;
16666   }
16667 
16668   // Identify the prevailing tag kind: this is the kind of the definition (if
16669   // there is a non-ignored definition), or otherwise the kind of the prior
16670   // (non-ignored) declaration.
16671   const TagDecl *PrevDef = Previous->getDefinition();
16672   if (PrevDef && IsIgnored(PrevDef))
16673     PrevDef = nullptr;
16674   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16675   if (Redecl->getTagKind() != NewTag) {
16676     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16677       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16678       << getRedeclDiagFromTagKind(OldTag);
16679     Diag(Redecl->getLocation(), diag::note_previous_use);
16680 
16681     // If there is a previous definition, suggest a fix-it.
16682     if (PrevDef) {
16683       Diag(NewTagLoc, diag::note_struct_class_suggestion)
16684         << getRedeclDiagFromTagKind(Redecl->getTagKind())
16685         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16686              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16687     }
16688   }
16689 
16690   return true;
16691 }
16692 
16693 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16694 /// from an outer enclosing namespace or file scope inside a friend declaration.
16695 /// This should provide the commented out code in the following snippet:
16696 ///   namespace N {
16697 ///     struct X;
16698 ///     namespace M {
16699 ///       struct Y { friend struct /*N::*/ X; };
16700 ///     }
16701 ///   }
16702 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16703                                          SourceLocation NameLoc) {
16704   // While the decl is in a namespace, do repeated lookup of that name and see
16705   // if we get the same namespace back.  If we do not, continue until
16706   // translation unit scope, at which point we have a fully qualified NNS.
16707   SmallVector<IdentifierInfo *, 4> Namespaces;
16708   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16709   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16710     // This tag should be declared in a namespace, which can only be enclosed by
16711     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16712     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16713     if (!Namespace || Namespace->isAnonymousNamespace())
16714       return FixItHint();
16715     IdentifierInfo *II = Namespace->getIdentifier();
16716     Namespaces.push_back(II);
16717     NamedDecl *Lookup = SemaRef.LookupSingleName(
16718         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16719     if (Lookup == Namespace)
16720       break;
16721   }
16722 
16723   // Once we have all the namespaces, reverse them to go outermost first, and
16724   // build an NNS.
16725   SmallString<64> Insertion;
16726   llvm::raw_svector_ostream OS(Insertion);
16727   if (DC->isTranslationUnit())
16728     OS << "::";
16729   std::reverse(Namespaces.begin(), Namespaces.end());
16730   for (auto *II : Namespaces)
16731     OS << II->getName() << "::";
16732   return FixItHint::CreateInsertion(NameLoc, Insertion);
16733 }
16734 
16735 /// Determine whether a tag originally declared in context \p OldDC can
16736 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16737 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16738 /// using-declaration).
16739 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16740                                          DeclContext *NewDC) {
16741   OldDC = OldDC->getRedeclContext();
16742   NewDC = NewDC->getRedeclContext();
16743 
16744   if (OldDC->Equals(NewDC))
16745     return true;
16746 
16747   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16748   // encloses the other).
16749   if (S.getLangOpts().MSVCCompat &&
16750       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16751     return true;
16752 
16753   return false;
16754 }
16755 
16756 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16757 /// former case, Name will be non-null.  In the later case, Name will be null.
16758 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16759 /// reference/declaration/definition of a tag.
16760 ///
16761 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16762 /// trailing-type-specifier) other than one in an alias-declaration.
16763 ///
16764 /// \param SkipBody If non-null, will be set to indicate if the caller should
16765 /// skip the definition of this tag and treat it as if it were a declaration.
16766 DeclResult
16767 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16768                CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16769                const ParsedAttributesView &Attrs, AccessSpecifier AS,
16770                SourceLocation ModulePrivateLoc,
16771                MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16772                bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16773                bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16774                bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16775                OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16776   // If this is not a definition, it must have a name.
16777   IdentifierInfo *OrigName = Name;
16778   assert((Name != nullptr || TUK == TUK_Definition) &&
16779          "Nameless record must be a definition!");
16780   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16781 
16782   OwnedDecl = false;
16783   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16784   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16785 
16786   // FIXME: Check member specializations more carefully.
16787   bool isMemberSpecialization = false;
16788   bool Invalid = false;
16789 
16790   // We only need to do this matching if we have template parameters
16791   // or a scope specifier, which also conveniently avoids this work
16792   // for non-C++ cases.
16793   if (TemplateParameterLists.size() > 0 ||
16794       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16795     if (TemplateParameterList *TemplateParams =
16796             MatchTemplateParametersToScopeSpecifier(
16797                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16798                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16799       if (Kind == TTK_Enum) {
16800         Diag(KWLoc, diag::err_enum_template);
16801         return true;
16802       }
16803 
16804       if (TemplateParams->size() > 0) {
16805         // This is a declaration or definition of a class template (which may
16806         // be a member of another template).
16807 
16808         if (Invalid)
16809           return true;
16810 
16811         OwnedDecl = false;
16812         DeclResult Result = CheckClassTemplate(
16813             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16814             AS, ModulePrivateLoc,
16815             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16816             TemplateParameterLists.data(), SkipBody);
16817         return Result.get();
16818       } else {
16819         // The "template<>" header is extraneous.
16820         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16821           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16822         isMemberSpecialization = true;
16823       }
16824     }
16825 
16826     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16827         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16828       return true;
16829   }
16830 
16831   // Figure out the underlying type if this a enum declaration. We need to do
16832   // this early, because it's needed to detect if this is an incompatible
16833   // redeclaration.
16834   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16835   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16836 
16837   if (Kind == TTK_Enum) {
16838     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16839       // No underlying type explicitly specified, or we failed to parse the
16840       // type, default to int.
16841       EnumUnderlying = Context.IntTy.getTypePtr();
16842     } else if (UnderlyingType.get()) {
16843       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16844       // integral type; any cv-qualification is ignored.
16845       TypeSourceInfo *TI = nullptr;
16846       GetTypeFromParser(UnderlyingType.get(), &TI);
16847       EnumUnderlying = TI;
16848 
16849       if (CheckEnumUnderlyingType(TI))
16850         // Recover by falling back to int.
16851         EnumUnderlying = Context.IntTy.getTypePtr();
16852 
16853       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16854                                           UPPC_FixedUnderlyingType))
16855         EnumUnderlying = Context.IntTy.getTypePtr();
16856 
16857     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16858       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16859       // of 'int'. However, if this is an unfixed forward declaration, don't set
16860       // the underlying type unless the user enables -fms-compatibility. This
16861       // makes unfixed forward declared enums incomplete and is more conforming.
16862       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16863         EnumUnderlying = Context.IntTy.getTypePtr();
16864     }
16865   }
16866 
16867   DeclContext *SearchDC = CurContext;
16868   DeclContext *DC = CurContext;
16869   bool isStdBadAlloc = false;
16870   bool isStdAlignValT = false;
16871 
16872   RedeclarationKind Redecl = forRedeclarationInCurContext();
16873   if (TUK == TUK_Friend || TUK == TUK_Reference)
16874     Redecl = NotForRedeclaration;
16875 
16876   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16877   /// implemented asks for structural equivalence checking, the returned decl
16878   /// here is passed back to the parser, allowing the tag body to be parsed.
16879   auto createTagFromNewDecl = [&]() -> TagDecl * {
16880     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16881     // If there is an identifier, use the location of the identifier as the
16882     // location of the decl, otherwise use the location of the struct/union
16883     // keyword.
16884     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16885     TagDecl *New = nullptr;
16886 
16887     if (Kind == TTK_Enum) {
16888       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16889                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16890       // If this is an undefined enum, bail.
16891       if (TUK != TUK_Definition && !Invalid)
16892         return nullptr;
16893       if (EnumUnderlying) {
16894         EnumDecl *ED = cast<EnumDecl>(New);
16895         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16896           ED->setIntegerTypeSourceInfo(TI);
16897         else
16898           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16899         QualType EnumTy = ED->getIntegerType();
16900         ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
16901                                  ? Context.getPromotedIntegerType(EnumTy)
16902                                  : EnumTy);
16903       }
16904     } else { // struct/union
16905       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16906                                nullptr);
16907     }
16908 
16909     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16910       // Add alignment attributes if necessary; these attributes are checked
16911       // when the ASTContext lays out the structure.
16912       //
16913       // It is important for implementing the correct semantics that this
16914       // happen here (in ActOnTag). The #pragma pack stack is
16915       // maintained as a result of parser callbacks which can occur at
16916       // many points during the parsing of a struct declaration (because
16917       // the #pragma tokens are effectively skipped over during the
16918       // parsing of the struct).
16919       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16920         AddAlignmentAttributesForRecord(RD);
16921         AddMsStructLayoutForRecord(RD);
16922       }
16923     }
16924     New->setLexicalDeclContext(CurContext);
16925     return New;
16926   };
16927 
16928   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16929   if (Name && SS.isNotEmpty()) {
16930     // We have a nested-name tag ('struct foo::bar').
16931 
16932     // Check for invalid 'foo::'.
16933     if (SS.isInvalid()) {
16934       Name = nullptr;
16935       goto CreateNewDecl;
16936     }
16937 
16938     // If this is a friend or a reference to a class in a dependent
16939     // context, don't try to make a decl for it.
16940     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16941       DC = computeDeclContext(SS, false);
16942       if (!DC) {
16943         IsDependent = true;
16944         return true;
16945       }
16946     } else {
16947       DC = computeDeclContext(SS, true);
16948       if (!DC) {
16949         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16950           << SS.getRange();
16951         return true;
16952       }
16953     }
16954 
16955     if (RequireCompleteDeclContext(SS, DC))
16956       return true;
16957 
16958     SearchDC = DC;
16959     // Look-up name inside 'foo::'.
16960     LookupQualifiedName(Previous, DC);
16961 
16962     if (Previous.isAmbiguous())
16963       return true;
16964 
16965     if (Previous.empty()) {
16966       // Name lookup did not find anything. However, if the
16967       // nested-name-specifier refers to the current instantiation,
16968       // and that current instantiation has any dependent base
16969       // classes, we might find something at instantiation time: treat
16970       // this as a dependent elaborated-type-specifier.
16971       // But this only makes any sense for reference-like lookups.
16972       if (Previous.wasNotFoundInCurrentInstantiation() &&
16973           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16974         IsDependent = true;
16975         return true;
16976       }
16977 
16978       // A tag 'foo::bar' must already exist.
16979       Diag(NameLoc, diag::err_not_tag_in_scope)
16980         << Kind << Name << DC << SS.getRange();
16981       Name = nullptr;
16982       Invalid = true;
16983       goto CreateNewDecl;
16984     }
16985   } else if (Name) {
16986     // C++14 [class.mem]p14:
16987     //   If T is the name of a class, then each of the following shall have a
16988     //   name different from T:
16989     //    -- every member of class T that is itself a type
16990     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16991         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16992       return true;
16993 
16994     // If this is a named struct, check to see if there was a previous forward
16995     // declaration or definition.
16996     // FIXME: We're looking into outer scopes here, even when we
16997     // shouldn't be. Doing so can result in ambiguities that we
16998     // shouldn't be diagnosing.
16999     LookupName(Previous, S);
17000 
17001     // When declaring or defining a tag, ignore ambiguities introduced
17002     // by types using'ed into this scope.
17003     if (Previous.isAmbiguous() &&
17004         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17005       LookupResult::Filter F = Previous.makeFilter();
17006       while (F.hasNext()) {
17007         NamedDecl *ND = F.next();
17008         if (!ND->getDeclContext()->getRedeclContext()->Equals(
17009                 SearchDC->getRedeclContext()))
17010           F.erase();
17011       }
17012       F.done();
17013     }
17014 
17015     // C++11 [namespace.memdef]p3:
17016     //   If the name in a friend declaration is neither qualified nor
17017     //   a template-id and the declaration is a function or an
17018     //   elaborated-type-specifier, the lookup to determine whether
17019     //   the entity has been previously declared shall not consider
17020     //   any scopes outside the innermost enclosing namespace.
17021     //
17022     // MSVC doesn't implement the above rule for types, so a friend tag
17023     // declaration may be a redeclaration of a type declared in an enclosing
17024     // scope.  They do implement this rule for friend functions.
17025     //
17026     // Does it matter that this should be by scope instead of by
17027     // semantic context?
17028     if (!Previous.empty() && TUK == TUK_Friend) {
17029       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17030       LookupResult::Filter F = Previous.makeFilter();
17031       bool FriendSawTagOutsideEnclosingNamespace = false;
17032       while (F.hasNext()) {
17033         NamedDecl *ND = F.next();
17034         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17035         if (DC->isFileContext() &&
17036             !EnclosingNS->Encloses(ND->getDeclContext())) {
17037           if (getLangOpts().MSVCCompat)
17038             FriendSawTagOutsideEnclosingNamespace = true;
17039           else
17040             F.erase();
17041         }
17042       }
17043       F.done();
17044 
17045       // Diagnose this MSVC extension in the easy case where lookup would have
17046       // unambiguously found something outside the enclosing namespace.
17047       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17048         NamedDecl *ND = Previous.getFoundDecl();
17049         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17050             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17051       }
17052     }
17053 
17054     // Note:  there used to be some attempt at recovery here.
17055     if (Previous.isAmbiguous())
17056       return true;
17057 
17058     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17059       // FIXME: This makes sure that we ignore the contexts associated
17060       // with C structs, unions, and enums when looking for a matching
17061       // tag declaration or definition. See the similar lookup tweak
17062       // in Sema::LookupName; is there a better way to deal with this?
17063       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17064         SearchDC = SearchDC->getParent();
17065     } else if (getLangOpts().CPlusPlus) {
17066       // Inside ObjCContainer want to keep it as a lexical decl context but go
17067       // past it (most often to TranslationUnit) to find the semantic decl
17068       // context.
17069       while (isa<ObjCContainerDecl>(SearchDC))
17070         SearchDC = SearchDC->getParent();
17071     }
17072   } else if (getLangOpts().CPlusPlus) {
17073     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17074     // TagDecl the same way as we skip it for named TagDecl.
17075     while (isa<ObjCContainerDecl>(SearchDC))
17076       SearchDC = SearchDC->getParent();
17077   }
17078 
17079   if (Previous.isSingleResult() &&
17080       Previous.getFoundDecl()->isTemplateParameter()) {
17081     // Maybe we will complain about the shadowed template parameter.
17082     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17083     // Just pretend that we didn't see the previous declaration.
17084     Previous.clear();
17085   }
17086 
17087   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17088       DC->Equals(getStdNamespace())) {
17089     if (Name->isStr("bad_alloc")) {
17090       // This is a declaration of or a reference to "std::bad_alloc".
17091       isStdBadAlloc = true;
17092 
17093       // If std::bad_alloc has been implicitly declared (but made invisible to
17094       // name lookup), fill in this implicit declaration as the previous
17095       // declaration, so that the declarations get chained appropriately.
17096       if (Previous.empty() && StdBadAlloc)
17097         Previous.addDecl(getStdBadAlloc());
17098     } else if (Name->isStr("align_val_t")) {
17099       isStdAlignValT = true;
17100       if (Previous.empty() && StdAlignValT)
17101         Previous.addDecl(getStdAlignValT());
17102     }
17103   }
17104 
17105   // If we didn't find a previous declaration, and this is a reference
17106   // (or friend reference), move to the correct scope.  In C++, we
17107   // also need to do a redeclaration lookup there, just in case
17108   // there's a shadow friend decl.
17109   if (Name && Previous.empty() &&
17110       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17111     if (Invalid) goto CreateNewDecl;
17112     assert(SS.isEmpty());
17113 
17114     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17115       // C++ [basic.scope.pdecl]p5:
17116       //   -- for an elaborated-type-specifier of the form
17117       //
17118       //          class-key identifier
17119       //
17120       //      if the elaborated-type-specifier is used in the
17121       //      decl-specifier-seq or parameter-declaration-clause of a
17122       //      function defined in namespace scope, the identifier is
17123       //      declared as a class-name in the namespace that contains
17124       //      the declaration; otherwise, except as a friend
17125       //      declaration, the identifier is declared in the smallest
17126       //      non-class, non-function-prototype scope that contains the
17127       //      declaration.
17128       //
17129       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17130       // C structs and unions.
17131       //
17132       // It is an error in C++ to declare (rather than define) an enum
17133       // type, including via an elaborated type specifier.  We'll
17134       // diagnose that later; for now, declare the enum in the same
17135       // scope as we would have picked for any other tag type.
17136       //
17137       // GNU C also supports this behavior as part of its incomplete
17138       // enum types extension, while GNU C++ does not.
17139       //
17140       // Find the context where we'll be declaring the tag.
17141       // FIXME: We would like to maintain the current DeclContext as the
17142       // lexical context,
17143       SearchDC = getTagInjectionContext(SearchDC);
17144 
17145       // Find the scope where we'll be declaring the tag.
17146       S = getTagInjectionScope(S, getLangOpts());
17147     } else {
17148       assert(TUK == TUK_Friend);
17149       CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17150 
17151       // C++ [namespace.memdef]p3:
17152       //   If a friend declaration in a non-local class first declares a
17153       //   class or function, the friend class or function is a member of
17154       //   the innermost enclosing namespace.
17155       SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17156                                     : SearchDC->getEnclosingNamespaceContext();
17157     }
17158 
17159     // In C++, we need to do a redeclaration lookup to properly
17160     // diagnose some problems.
17161     // FIXME: redeclaration lookup is also used (with and without C++) to find a
17162     // hidden declaration so that we don't get ambiguity errors when using a
17163     // type declared by an elaborated-type-specifier.  In C that is not correct
17164     // and we should instead merge compatible types found by lookup.
17165     if (getLangOpts().CPlusPlus) {
17166       // FIXME: This can perform qualified lookups into function contexts,
17167       // which are meaningless.
17168       Previous.setRedeclarationKind(forRedeclarationInCurContext());
17169       LookupQualifiedName(Previous, SearchDC);
17170     } else {
17171       Previous.setRedeclarationKind(forRedeclarationInCurContext());
17172       LookupName(Previous, S);
17173     }
17174   }
17175 
17176   // If we have a known previous declaration to use, then use it.
17177   if (Previous.empty() && SkipBody && SkipBody->Previous)
17178     Previous.addDecl(SkipBody->Previous);
17179 
17180   if (!Previous.empty()) {
17181     NamedDecl *PrevDecl = Previous.getFoundDecl();
17182     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17183 
17184     // It's okay to have a tag decl in the same scope as a typedef
17185     // which hides a tag decl in the same scope.  Finding this
17186     // with a redeclaration lookup can only actually happen in C++.
17187     //
17188     // This is also okay for elaborated-type-specifiers, which is
17189     // technically forbidden by the current standard but which is
17190     // okay according to the likely resolution of an open issue;
17191     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17192     if (getLangOpts().CPlusPlus) {
17193       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17194         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17195           TagDecl *Tag = TT->getDecl();
17196           if (Tag->getDeclName() == Name &&
17197               Tag->getDeclContext()->getRedeclContext()
17198                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
17199             PrevDecl = Tag;
17200             Previous.clear();
17201             Previous.addDecl(Tag);
17202             Previous.resolveKind();
17203           }
17204         }
17205       }
17206     }
17207 
17208     // If this is a redeclaration of a using shadow declaration, it must
17209     // declare a tag in the same context. In MSVC mode, we allow a
17210     // redefinition if either context is within the other.
17211     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17212       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17213       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17214           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17215           !(OldTag && isAcceptableTagRedeclContext(
17216                           *this, OldTag->getDeclContext(), SearchDC))) {
17217         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17218         Diag(Shadow->getTargetDecl()->getLocation(),
17219              diag::note_using_decl_target);
17220         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17221             << 0;
17222         // Recover by ignoring the old declaration.
17223         Previous.clear();
17224         goto CreateNewDecl;
17225       }
17226     }
17227 
17228     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17229       // If this is a use of a previous tag, or if the tag is already declared
17230       // in the same scope (so that the definition/declaration completes or
17231       // rementions the tag), reuse the decl.
17232       if (TUK == TUK_Reference || TUK == TUK_Friend ||
17233           isDeclInScope(DirectPrevDecl, SearchDC, S,
17234                         SS.isNotEmpty() || isMemberSpecialization)) {
17235         // Make sure that this wasn't declared as an enum and now used as a
17236         // struct or something similar.
17237         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17238                                           TUK == TUK_Definition, KWLoc,
17239                                           Name)) {
17240           bool SafeToContinue
17241             = (PrevTagDecl->getTagKind() != TTK_Enum &&
17242                Kind != TTK_Enum);
17243           if (SafeToContinue)
17244             Diag(KWLoc, diag::err_use_with_wrong_tag)
17245               << Name
17246               << FixItHint::CreateReplacement(SourceRange(KWLoc),
17247                                               PrevTagDecl->getKindName());
17248           else
17249             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17250           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17251 
17252           if (SafeToContinue)
17253             Kind = PrevTagDecl->getTagKind();
17254           else {
17255             // Recover by making this an anonymous redefinition.
17256             Name = nullptr;
17257             Previous.clear();
17258             Invalid = true;
17259           }
17260         }
17261 
17262         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17263           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17264           if (TUK == TUK_Reference || TUK == TUK_Friend)
17265             return PrevTagDecl;
17266 
17267           QualType EnumUnderlyingTy;
17268           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17269             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17270           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17271             EnumUnderlyingTy = QualType(T, 0);
17272 
17273           // All conflicts with previous declarations are recovered by
17274           // returning the previous declaration, unless this is a definition,
17275           // in which case we want the caller to bail out.
17276           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17277                                      ScopedEnum, EnumUnderlyingTy,
17278                                      IsFixed, PrevEnum))
17279             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17280         }
17281 
17282         // C++11 [class.mem]p1:
17283         //   A member shall not be declared twice in the member-specification,
17284         //   except that a nested class or member class template can be declared
17285         //   and then later defined.
17286         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17287             S->isDeclScope(PrevDecl)) {
17288           Diag(NameLoc, diag::ext_member_redeclared);
17289           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17290         }
17291 
17292         if (!Invalid) {
17293           // If this is a use, just return the declaration we found, unless
17294           // we have attributes.
17295           if (TUK == TUK_Reference || TUK == TUK_Friend) {
17296             if (!Attrs.empty()) {
17297               // FIXME: Diagnose these attributes. For now, we create a new
17298               // declaration to hold them.
17299             } else if (TUK == TUK_Reference &&
17300                        (PrevTagDecl->getFriendObjectKind() ==
17301                             Decl::FOK_Undeclared ||
17302                         PrevDecl->getOwningModule() != getCurrentModule()) &&
17303                        SS.isEmpty()) {
17304               // This declaration is a reference to an existing entity, but
17305               // has different visibility from that entity: it either makes
17306               // a friend visible or it makes a type visible in a new module.
17307               // In either case, create a new declaration. We only do this if
17308               // the declaration would have meant the same thing if no prior
17309               // declaration were found, that is, if it was found in the same
17310               // scope where we would have injected a declaration.
17311               if (!getTagInjectionContext(CurContext)->getRedeclContext()
17312                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17313                 return PrevTagDecl;
17314               // This is in the injected scope, create a new declaration in
17315               // that scope.
17316               S = getTagInjectionScope(S, getLangOpts());
17317             } else {
17318               return PrevTagDecl;
17319             }
17320           }
17321 
17322           // Diagnose attempts to redefine a tag.
17323           if (TUK == TUK_Definition) {
17324             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17325               // If we're defining a specialization and the previous definition
17326               // is from an implicit instantiation, don't emit an error
17327               // here; we'll catch this in the general case below.
17328               bool IsExplicitSpecializationAfterInstantiation = false;
17329               if (isMemberSpecialization) {
17330                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17331                   IsExplicitSpecializationAfterInstantiation =
17332                     RD->getTemplateSpecializationKind() !=
17333                     TSK_ExplicitSpecialization;
17334                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17335                   IsExplicitSpecializationAfterInstantiation =
17336                     ED->getTemplateSpecializationKind() !=
17337                     TSK_ExplicitSpecialization;
17338               }
17339 
17340               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17341               // not keep more that one definition around (merge them). However,
17342               // ensure the decl passes the structural compatibility check in
17343               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17344               NamedDecl *Hidden = nullptr;
17345               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17346                 // There is a definition of this tag, but it is not visible. We
17347                 // explicitly make use of C++'s one definition rule here, and
17348                 // assume that this definition is identical to the hidden one
17349                 // we already have. Make the existing definition visible and
17350                 // use it in place of this one.
17351                 if (!getLangOpts().CPlusPlus) {
17352                   // Postpone making the old definition visible until after we
17353                   // complete parsing the new one and do the structural
17354                   // comparison.
17355                   SkipBody->CheckSameAsPrevious = true;
17356                   SkipBody->New = createTagFromNewDecl();
17357                   SkipBody->Previous = Def;
17358                   return Def;
17359                 } else {
17360                   SkipBody->ShouldSkip = true;
17361                   SkipBody->Previous = Def;
17362                   makeMergedDefinitionVisible(Hidden);
17363                   // Carry on and handle it like a normal definition. We'll
17364                   // skip starting the definitiion later.
17365                 }
17366               } else if (!IsExplicitSpecializationAfterInstantiation) {
17367                 // A redeclaration in function prototype scope in C isn't
17368                 // visible elsewhere, so merely issue a warning.
17369                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17370                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17371                 else
17372                   Diag(NameLoc, diag::err_redefinition) << Name;
17373                 notePreviousDefinition(Def,
17374                                        NameLoc.isValid() ? NameLoc : KWLoc);
17375                 // If this is a redefinition, recover by making this
17376                 // struct be anonymous, which will make any later
17377                 // references get the previous definition.
17378                 Name = nullptr;
17379                 Previous.clear();
17380                 Invalid = true;
17381               }
17382             } else {
17383               // If the type is currently being defined, complain
17384               // about a nested redefinition.
17385               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17386               if (TD->isBeingDefined()) {
17387                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17388                 Diag(PrevTagDecl->getLocation(),
17389                      diag::note_previous_definition);
17390                 Name = nullptr;
17391                 Previous.clear();
17392                 Invalid = true;
17393               }
17394             }
17395 
17396             // Okay, this is definition of a previously declared or referenced
17397             // tag. We're going to create a new Decl for it.
17398           }
17399 
17400           // Okay, we're going to make a redeclaration.  If this is some kind
17401           // of reference, make sure we build the redeclaration in the same DC
17402           // as the original, and ignore the current access specifier.
17403           if (TUK == TUK_Friend || TUK == TUK_Reference) {
17404             SearchDC = PrevTagDecl->getDeclContext();
17405             AS = AS_none;
17406           }
17407         }
17408         // If we get here we have (another) forward declaration or we
17409         // have a definition.  Just create a new decl.
17410 
17411       } else {
17412         // If we get here, this is a definition of a new tag type in a nested
17413         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17414         // new decl/type.  We set PrevDecl to NULL so that the entities
17415         // have distinct types.
17416         Previous.clear();
17417       }
17418       // If we get here, we're going to create a new Decl. If PrevDecl
17419       // is non-NULL, it's a definition of the tag declared by
17420       // PrevDecl. If it's NULL, we have a new definition.
17421 
17422     // Otherwise, PrevDecl is not a tag, but was found with tag
17423     // lookup.  This is only actually possible in C++, where a few
17424     // things like templates still live in the tag namespace.
17425     } else {
17426       // Use a better diagnostic if an elaborated-type-specifier
17427       // found the wrong kind of type on the first
17428       // (non-redeclaration) lookup.
17429       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17430           !Previous.isForRedeclaration()) {
17431         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17432         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17433                                                        << Kind;
17434         Diag(PrevDecl->getLocation(), diag::note_declared_at);
17435         Invalid = true;
17436 
17437       // Otherwise, only diagnose if the declaration is in scope.
17438       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17439                                 SS.isNotEmpty() || isMemberSpecialization)) {
17440         // do nothing
17441 
17442       // Diagnose implicit declarations introduced by elaborated types.
17443       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17444         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17445         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17446         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17447         Invalid = true;
17448 
17449       // Otherwise it's a declaration.  Call out a particularly common
17450       // case here.
17451       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17452         unsigned Kind = 0;
17453         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17454         Diag(NameLoc, diag::err_tag_definition_of_typedef)
17455           << Name << Kind << TND->getUnderlyingType();
17456         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17457         Invalid = true;
17458 
17459       // Otherwise, diagnose.
17460       } else {
17461         // The tag name clashes with something else in the target scope,
17462         // issue an error and recover by making this tag be anonymous.
17463         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17464         notePreviousDefinition(PrevDecl, NameLoc);
17465         Name = nullptr;
17466         Invalid = true;
17467       }
17468 
17469       // The existing declaration isn't relevant to us; we're in a
17470       // new scope, so clear out the previous declaration.
17471       Previous.clear();
17472     }
17473   }
17474 
17475 CreateNewDecl:
17476 
17477   TagDecl *PrevDecl = nullptr;
17478   if (Previous.isSingleResult())
17479     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17480 
17481   // If there is an identifier, use the location of the identifier as the
17482   // location of the decl, otherwise use the location of the struct/union
17483   // keyword.
17484   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17485 
17486   // Otherwise, create a new declaration. If there is a previous
17487   // declaration of the same entity, the two will be linked via
17488   // PrevDecl.
17489   TagDecl *New;
17490 
17491   if (Kind == TTK_Enum) {
17492     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17493     // enum X { A, B, C } D;    D should chain to X.
17494     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17495                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17496                            ScopedEnumUsesClassTag, IsFixed);
17497 
17498     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17499       StdAlignValT = cast<EnumDecl>(New);
17500 
17501     // If this is an undefined enum, warn.
17502     if (TUK != TUK_Definition && !Invalid) {
17503       TagDecl *Def;
17504       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17505         // C++0x: 7.2p2: opaque-enum-declaration.
17506         // Conflicts are diagnosed above. Do nothing.
17507       }
17508       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17509         Diag(Loc, diag::ext_forward_ref_enum_def)
17510           << New;
17511         Diag(Def->getLocation(), diag::note_previous_definition);
17512       } else {
17513         unsigned DiagID = diag::ext_forward_ref_enum;
17514         if (getLangOpts().MSVCCompat)
17515           DiagID = diag::ext_ms_forward_ref_enum;
17516         else if (getLangOpts().CPlusPlus)
17517           DiagID = diag::err_forward_ref_enum;
17518         Diag(Loc, DiagID);
17519       }
17520     }
17521 
17522     if (EnumUnderlying) {
17523       EnumDecl *ED = cast<EnumDecl>(New);
17524       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17525         ED->setIntegerTypeSourceInfo(TI);
17526       else
17527         ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17528       QualType EnumTy = ED->getIntegerType();
17529       ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17530                                ? Context.getPromotedIntegerType(EnumTy)
17531                                : EnumTy);
17532       assert(ED->isComplete() && "enum with type should be complete");
17533     }
17534   } else {
17535     // struct/union/class
17536 
17537     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17538     // struct X { int A; } D;    D should chain to X.
17539     if (getLangOpts().CPlusPlus) {
17540       // FIXME: Look for a way to use RecordDecl for simple structs.
17541       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17542                                   cast_or_null<CXXRecordDecl>(PrevDecl));
17543 
17544       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17545         StdBadAlloc = cast<CXXRecordDecl>(New);
17546     } else
17547       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17548                                cast_or_null<RecordDecl>(PrevDecl));
17549   }
17550 
17551   if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17552     Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17553         << (OOK == OOK_Macro) << New->getSourceRange();
17554 
17555   // C++11 [dcl.type]p3:
17556   //   A type-specifier-seq shall not define a class or enumeration [...].
17557   if (!Invalid && getLangOpts().CPlusPlus &&
17558       (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17559     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17560       << Context.getTagDeclType(New);
17561     Invalid = true;
17562   }
17563 
17564   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17565       DC->getDeclKind() == Decl::Enum) {
17566     Diag(New->getLocation(), diag::err_type_defined_in_enum)
17567       << Context.getTagDeclType(New);
17568     Invalid = true;
17569   }
17570 
17571   // Maybe add qualifier info.
17572   if (SS.isNotEmpty()) {
17573     if (SS.isSet()) {
17574       // If this is either a declaration or a definition, check the
17575       // nested-name-specifier against the current context.
17576       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17577           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17578                                        isMemberSpecialization))
17579         Invalid = true;
17580 
17581       New->setQualifierInfo(SS.getWithLocInContext(Context));
17582       if (TemplateParameterLists.size() > 0) {
17583         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17584       }
17585     }
17586     else
17587       Invalid = true;
17588   }
17589 
17590   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17591     // Add alignment attributes if necessary; these attributes are checked when
17592     // the ASTContext lays out the structure.
17593     //
17594     // It is important for implementing the correct semantics that this
17595     // happen here (in ActOnTag). The #pragma pack stack is
17596     // maintained as a result of parser callbacks which can occur at
17597     // many points during the parsing of a struct declaration (because
17598     // the #pragma tokens are effectively skipped over during the
17599     // parsing of the struct).
17600     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17601       AddAlignmentAttributesForRecord(RD);
17602       AddMsStructLayoutForRecord(RD);
17603     }
17604   }
17605 
17606   if (ModulePrivateLoc.isValid()) {
17607     if (isMemberSpecialization)
17608       Diag(New->getLocation(), diag::err_module_private_specialization)
17609         << 2
17610         << FixItHint::CreateRemoval(ModulePrivateLoc);
17611     // __module_private__ does not apply to local classes. However, we only
17612     // diagnose this as an error when the declaration specifiers are
17613     // freestanding. Here, we just ignore the __module_private__.
17614     else if (!SearchDC->isFunctionOrMethod())
17615       New->setModulePrivate();
17616   }
17617 
17618   // If this is a specialization of a member class (of a class template),
17619   // check the specialization.
17620   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17621     Invalid = true;
17622 
17623   // If we're declaring or defining a tag in function prototype scope in C,
17624   // note that this type can only be used within the function and add it to
17625   // the list of decls to inject into the function definition scope.
17626   if ((Name || Kind == TTK_Enum) &&
17627       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17628     if (getLangOpts().CPlusPlus) {
17629       // C++ [dcl.fct]p6:
17630       //   Types shall not be defined in return or parameter types.
17631       if (TUK == TUK_Definition && !IsTypeSpecifier) {
17632         Diag(Loc, diag::err_type_defined_in_param_type)
17633             << Name;
17634         Invalid = true;
17635       }
17636     } else if (!PrevDecl) {
17637       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17638     }
17639   }
17640 
17641   if (Invalid)
17642     New->setInvalidDecl();
17643 
17644   // Set the lexical context. If the tag has a C++ scope specifier, the
17645   // lexical context will be different from the semantic context.
17646   New->setLexicalDeclContext(CurContext);
17647 
17648   // Mark this as a friend decl if applicable.
17649   // In Microsoft mode, a friend declaration also acts as a forward
17650   // declaration so we always pass true to setObjectOfFriendDecl to make
17651   // the tag name visible.
17652   if (TUK == TUK_Friend)
17653     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17654 
17655   // Set the access specifier.
17656   if (!Invalid && SearchDC->isRecord())
17657     SetMemberAccessSpecifier(New, PrevDecl, AS);
17658 
17659   if (PrevDecl)
17660     CheckRedeclarationInModule(New, PrevDecl);
17661 
17662   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17663     New->startDefinition();
17664 
17665   ProcessDeclAttributeList(S, New, Attrs);
17666   AddPragmaAttributes(S, New);
17667 
17668   // If this has an identifier, add it to the scope stack.
17669   if (TUK == TUK_Friend) {
17670     // We might be replacing an existing declaration in the lookup tables;
17671     // if so, borrow its access specifier.
17672     if (PrevDecl)
17673       New->setAccess(PrevDecl->getAccess());
17674 
17675     DeclContext *DC = New->getDeclContext()->getRedeclContext();
17676     DC->makeDeclVisibleInContext(New);
17677     if (Name) // can be null along some error paths
17678       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17679         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17680   } else if (Name) {
17681     S = getNonFieldDeclScope(S);
17682     PushOnScopeChains(New, S, true);
17683   } else {
17684     CurContext->addDecl(New);
17685   }
17686 
17687   // If this is the C FILE type, notify the AST context.
17688   if (IdentifierInfo *II = New->getIdentifier())
17689     if (!New->isInvalidDecl() &&
17690         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17691         II->isStr("FILE"))
17692       Context.setFILEDecl(New);
17693 
17694   if (PrevDecl)
17695     mergeDeclAttributes(New, PrevDecl);
17696 
17697   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17698     inferGslOwnerPointerAttribute(CXXRD);
17699 
17700   // If there's a #pragma GCC visibility in scope, set the visibility of this
17701   // record.
17702   AddPushedVisibilityAttribute(New);
17703 
17704   if (isMemberSpecialization && !New->isInvalidDecl())
17705     CompleteMemberSpecialization(New, Previous);
17706 
17707   OwnedDecl = true;
17708   // In C++, don't return an invalid declaration. We can't recover well from
17709   // the cases where we make the type anonymous.
17710   if (Invalid && getLangOpts().CPlusPlus) {
17711     if (New->isBeingDefined())
17712       if (auto RD = dyn_cast<RecordDecl>(New))
17713         RD->completeDefinition();
17714     return true;
17715   } else if (SkipBody && SkipBody->ShouldSkip) {
17716     return SkipBody->Previous;
17717   } else {
17718     return New;
17719   }
17720 }
17721 
17722 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17723   AdjustDeclIfTemplate(TagD);
17724   TagDecl *Tag = cast<TagDecl>(TagD);
17725 
17726   // Enter the tag context.
17727   PushDeclContext(S, Tag);
17728 
17729   ActOnDocumentableDecl(TagD);
17730 
17731   // If there's a #pragma GCC visibility in scope, set the visibility of this
17732   // record.
17733   AddPushedVisibilityAttribute(Tag);
17734 }
17735 
17736 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17737   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17738     return false;
17739 
17740   // Make the previous decl visible.
17741   makeMergedDefinitionVisible(SkipBody.Previous);
17742   return true;
17743 }
17744 
17745 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17746   assert(IDecl->getLexicalParent() == CurContext &&
17747       "The next DeclContext should be lexically contained in the current one.");
17748   CurContext = IDecl;
17749 }
17750 
17751 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17752                                            SourceLocation FinalLoc,
17753                                            bool IsFinalSpelledSealed,
17754                                            bool IsAbstract,
17755                                            SourceLocation LBraceLoc) {
17756   AdjustDeclIfTemplate(TagD);
17757   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17758 
17759   FieldCollector->StartClass();
17760 
17761   if (!Record->getIdentifier())
17762     return;
17763 
17764   if (IsAbstract)
17765     Record->markAbstract();
17766 
17767   if (FinalLoc.isValid()) {
17768     Record->addAttr(FinalAttr::Create(Context, FinalLoc,
17769                                       IsFinalSpelledSealed
17770                                           ? FinalAttr::Keyword_sealed
17771                                           : FinalAttr::Keyword_final));
17772   }
17773   // C++ [class]p2:
17774   //   [...] The class-name is also inserted into the scope of the
17775   //   class itself; this is known as the injected-class-name. For
17776   //   purposes of access checking, the injected-class-name is treated
17777   //   as if it were a public member name.
17778   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17779       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17780       Record->getLocation(), Record->getIdentifier(),
17781       /*PrevDecl=*/nullptr,
17782       /*DelayTypeCreation=*/true);
17783   Context.getTypeDeclType(InjectedClassName, Record);
17784   InjectedClassName->setImplicit();
17785   InjectedClassName->setAccess(AS_public);
17786   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17787       InjectedClassName->setDescribedClassTemplate(Template);
17788   PushOnScopeChains(InjectedClassName, S);
17789   assert(InjectedClassName->isInjectedClassName() &&
17790          "Broken injected-class-name");
17791 }
17792 
17793 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17794                                     SourceRange BraceRange) {
17795   AdjustDeclIfTemplate(TagD);
17796   TagDecl *Tag = cast<TagDecl>(TagD);
17797   Tag->setBraceRange(BraceRange);
17798 
17799   // Make sure we "complete" the definition even it is invalid.
17800   if (Tag->isBeingDefined()) {
17801     assert(Tag->isInvalidDecl() && "We should already have completed it");
17802     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17803       RD->completeDefinition();
17804   }
17805 
17806   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17807     FieldCollector->FinishClass();
17808     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17809       auto *Def = RD->getDefinition();
17810       assert(Def && "The record is expected to have a completed definition");
17811       unsigned NumInitMethods = 0;
17812       for (auto *Method : Def->methods()) {
17813         if (!Method->getIdentifier())
17814             continue;
17815         if (Method->getName() == "__init")
17816           NumInitMethods++;
17817       }
17818       if (NumInitMethods > 1 || !Def->hasInitMethod())
17819         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17820     }
17821   }
17822 
17823   // Exit this scope of this tag's definition.
17824   PopDeclContext();
17825 
17826   if (getCurLexicalContext()->isObjCContainer() &&
17827       Tag->getDeclContext()->isFileContext())
17828     Tag->setTopLevelDeclInObjCContainer();
17829 
17830   // Notify the consumer that we've defined a tag.
17831   if (!Tag->isInvalidDecl())
17832     Consumer.HandleTagDeclDefinition(Tag);
17833 
17834   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17835   // from XLs and instead matches the XL #pragma pack(1) behavior.
17836   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17837       AlignPackStack.hasValue()) {
17838     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17839     // Only diagnose #pragma align(packed).
17840     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17841       return;
17842     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17843     if (!RD)
17844       return;
17845     // Only warn if there is at least 1 bitfield member.
17846     if (llvm::any_of(RD->fields(),
17847                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17848       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17849   }
17850 }
17851 
17852 void Sema::ActOnObjCContainerFinishDefinition() {
17853   // Exit this scope of this interface definition.
17854   PopDeclContext();
17855 }
17856 
17857 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17858   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17859   OriginalLexicalContext = ObjCCtx;
17860   ActOnObjCContainerFinishDefinition();
17861 }
17862 
17863 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17864   ActOnObjCContainerStartDefinition(ObjCCtx);
17865   OriginalLexicalContext = nullptr;
17866 }
17867 
17868 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17869   AdjustDeclIfTemplate(TagD);
17870   TagDecl *Tag = cast<TagDecl>(TagD);
17871   Tag->setInvalidDecl();
17872 
17873   // Make sure we "complete" the definition even it is invalid.
17874   if (Tag->isBeingDefined()) {
17875     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17876       RD->completeDefinition();
17877   }
17878 
17879   // We're undoing ActOnTagStartDefinition here, not
17880   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17881   // the FieldCollector.
17882 
17883   PopDeclContext();
17884 }
17885 
17886 // Note that FieldName may be null for anonymous bitfields.
17887 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17888                                 IdentifierInfo *FieldName, QualType FieldTy,
17889                                 bool IsMsStruct, Expr *BitWidth) {
17890   assert(BitWidth);
17891   if (BitWidth->containsErrors())
17892     return ExprError();
17893 
17894   // C99 6.7.2.1p4 - verify the field type.
17895   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17896   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17897     // Handle incomplete and sizeless types with a specific error.
17898     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17899                                  diag::err_field_incomplete_or_sizeless))
17900       return ExprError();
17901     if (FieldName)
17902       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17903         << FieldName << FieldTy << BitWidth->getSourceRange();
17904     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17905       << FieldTy << BitWidth->getSourceRange();
17906   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17907                                              UPPC_BitFieldWidth))
17908     return ExprError();
17909 
17910   // If the bit-width is type- or value-dependent, don't try to check
17911   // it now.
17912   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17913     return BitWidth;
17914 
17915   llvm::APSInt Value;
17916   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17917   if (ICE.isInvalid())
17918     return ICE;
17919   BitWidth = ICE.get();
17920 
17921   // Zero-width bitfield is ok for anonymous field.
17922   if (Value == 0 && FieldName)
17923     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17924 
17925   if (Value.isSigned() && Value.isNegative()) {
17926     if (FieldName)
17927       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17928                << FieldName << toString(Value, 10);
17929     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17930       << toString(Value, 10);
17931   }
17932 
17933   // The size of the bit-field must not exceed our maximum permitted object
17934   // size.
17935   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17936     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17937            << !FieldName << FieldName << toString(Value, 10);
17938   }
17939 
17940   if (!FieldTy->isDependentType()) {
17941     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17942     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17943     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17944 
17945     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17946     // ABI.
17947     bool CStdConstraintViolation =
17948         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17949     bool MSBitfieldViolation =
17950         Value.ugt(TypeStorageSize) &&
17951         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17952     if (CStdConstraintViolation || MSBitfieldViolation) {
17953       unsigned DiagWidth =
17954           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17955       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17956              << (bool)FieldName << FieldName << toString(Value, 10)
17957              << !CStdConstraintViolation << DiagWidth;
17958     }
17959 
17960     // Warn on types where the user might conceivably expect to get all
17961     // specified bits as value bits: that's all integral types other than
17962     // 'bool'.
17963     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17964       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17965           << FieldName << toString(Value, 10)
17966           << (unsigned)TypeWidth;
17967     }
17968   }
17969 
17970   return BitWidth;
17971 }
17972 
17973 /// ActOnField - Each field of a C struct/union is passed into this in order
17974 /// to create a FieldDecl object for it.
17975 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17976                        Declarator &D, Expr *BitfieldWidth) {
17977   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17978                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17979                                /*InitStyle=*/ICIS_NoInit, AS_public);
17980   return Res;
17981 }
17982 
17983 /// HandleField - Analyze a field of a C struct or a C++ data member.
17984 ///
17985 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17986                              SourceLocation DeclStart,
17987                              Declarator &D, Expr *BitWidth,
17988                              InClassInitStyle InitStyle,
17989                              AccessSpecifier AS) {
17990   if (D.isDecompositionDeclarator()) {
17991     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17992     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17993       << Decomp.getSourceRange();
17994     return nullptr;
17995   }
17996 
17997   IdentifierInfo *II = D.getIdentifier();
17998   SourceLocation Loc = DeclStart;
17999   if (II) Loc = D.getIdentifierLoc();
18000 
18001   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18002   QualType T = TInfo->getType();
18003   if (getLangOpts().CPlusPlus) {
18004     CheckExtraCXXDefaultArguments(D);
18005 
18006     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18007                                         UPPC_DataMemberType)) {
18008       D.setInvalidType();
18009       T = Context.IntTy;
18010       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18011     }
18012   }
18013 
18014   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18015 
18016   if (D.getDeclSpec().isInlineSpecified())
18017     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18018         << getLangOpts().CPlusPlus17;
18019   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18020     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18021          diag::err_invalid_thread)
18022       << DeclSpec::getSpecifierName(TSCS);
18023 
18024   // Check to see if this name was declared as a member previously
18025   NamedDecl *PrevDecl = nullptr;
18026   LookupResult Previous(*this, II, Loc, LookupMemberName,
18027                         ForVisibleRedeclaration);
18028   LookupName(Previous, S);
18029   switch (Previous.getResultKind()) {
18030     case LookupResult::Found:
18031     case LookupResult::FoundUnresolvedValue:
18032       PrevDecl = Previous.getAsSingle<NamedDecl>();
18033       break;
18034 
18035     case LookupResult::FoundOverloaded:
18036       PrevDecl = Previous.getRepresentativeDecl();
18037       break;
18038 
18039     case LookupResult::NotFound:
18040     case LookupResult::NotFoundInCurrentInstantiation:
18041     case LookupResult::Ambiguous:
18042       break;
18043   }
18044   Previous.suppressDiagnostics();
18045 
18046   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18047     // Maybe we will complain about the shadowed template parameter.
18048     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18049     // Just pretend that we didn't see the previous declaration.
18050     PrevDecl = nullptr;
18051   }
18052 
18053   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18054     PrevDecl = nullptr;
18055 
18056   bool Mutable
18057     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18058   SourceLocation TSSL = D.getBeginLoc();
18059   FieldDecl *NewFD
18060     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18061                      TSSL, AS, PrevDecl, &D);
18062 
18063   if (NewFD->isInvalidDecl())
18064     Record->setInvalidDecl();
18065 
18066   if (D.getDeclSpec().isModulePrivateSpecified())
18067     NewFD->setModulePrivate();
18068 
18069   if (NewFD->isInvalidDecl() && PrevDecl) {
18070     // Don't introduce NewFD into scope; there's already something
18071     // with the same name in the same scope.
18072   } else if (II) {
18073     PushOnScopeChains(NewFD, S);
18074   } else
18075     Record->addDecl(NewFD);
18076 
18077   return NewFD;
18078 }
18079 
18080 /// Build a new FieldDecl and check its well-formedness.
18081 ///
18082 /// This routine builds a new FieldDecl given the fields name, type,
18083 /// record, etc. \p PrevDecl should refer to any previous declaration
18084 /// with the same name and in the same scope as the field to be
18085 /// created.
18086 ///
18087 /// \returns a new FieldDecl.
18088 ///
18089 /// \todo The Declarator argument is a hack. It will be removed once
18090 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18091                                 TypeSourceInfo *TInfo,
18092                                 RecordDecl *Record, SourceLocation Loc,
18093                                 bool Mutable, Expr *BitWidth,
18094                                 InClassInitStyle InitStyle,
18095                                 SourceLocation TSSL,
18096                                 AccessSpecifier AS, NamedDecl *PrevDecl,
18097                                 Declarator *D) {
18098   IdentifierInfo *II = Name.getAsIdentifierInfo();
18099   bool InvalidDecl = false;
18100   if (D) InvalidDecl = D->isInvalidType();
18101 
18102   // If we receive a broken type, recover by assuming 'int' and
18103   // marking this declaration as invalid.
18104   if (T.isNull() || T->containsErrors()) {
18105     InvalidDecl = true;
18106     T = Context.IntTy;
18107   }
18108 
18109   QualType EltTy = Context.getBaseElementType(T);
18110   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18111     if (RequireCompleteSizedType(Loc, EltTy,
18112                                  diag::err_field_incomplete_or_sizeless)) {
18113       // Fields of incomplete type force their record to be invalid.
18114       Record->setInvalidDecl();
18115       InvalidDecl = true;
18116     } else {
18117       NamedDecl *Def;
18118       EltTy->isIncompleteType(&Def);
18119       if (Def && Def->isInvalidDecl()) {
18120         Record->setInvalidDecl();
18121         InvalidDecl = true;
18122       }
18123     }
18124   }
18125 
18126   // TR 18037 does not allow fields to be declared with address space
18127   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18128       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18129     Diag(Loc, diag::err_field_with_address_space);
18130     Record->setInvalidDecl();
18131     InvalidDecl = true;
18132   }
18133 
18134   if (LangOpts.OpenCL) {
18135     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18136     // used as structure or union field: image, sampler, event or block types.
18137     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18138         T->isBlockPointerType()) {
18139       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18140       Record->setInvalidDecl();
18141       InvalidDecl = true;
18142     }
18143     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18144     // is enabled.
18145     if (BitWidth && !getOpenCLOptions().isAvailableOption(
18146                         "__cl_clang_bitfields", LangOpts)) {
18147       Diag(Loc, diag::err_opencl_bitfields);
18148       InvalidDecl = true;
18149     }
18150   }
18151 
18152   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18153   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18154       T.hasQualifiers()) {
18155     InvalidDecl = true;
18156     Diag(Loc, diag::err_anon_bitfield_qualifiers);
18157   }
18158 
18159   // C99 6.7.2.1p8: A member of a structure or union may have any type other
18160   // than a variably modified type.
18161   if (!InvalidDecl && T->isVariablyModifiedType()) {
18162     if (!tryToFixVariablyModifiedVarType(
18163             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18164       InvalidDecl = true;
18165   }
18166 
18167   // Fields can not have abstract class types
18168   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18169                                              diag::err_abstract_type_in_decl,
18170                                              AbstractFieldType))
18171     InvalidDecl = true;
18172 
18173   if (InvalidDecl)
18174     BitWidth = nullptr;
18175   // If this is declared as a bit-field, check the bit-field.
18176   if (BitWidth) {
18177     BitWidth =
18178         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18179     if (!BitWidth) {
18180       InvalidDecl = true;
18181       BitWidth = nullptr;
18182     }
18183   }
18184 
18185   // Check that 'mutable' is consistent with the type of the declaration.
18186   if (!InvalidDecl && Mutable) {
18187     unsigned DiagID = 0;
18188     if (T->isReferenceType())
18189       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18190                                         : diag::err_mutable_reference;
18191     else if (T.isConstQualified())
18192       DiagID = diag::err_mutable_const;
18193 
18194     if (DiagID) {
18195       SourceLocation ErrLoc = Loc;
18196       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18197         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18198       Diag(ErrLoc, DiagID);
18199       if (DiagID != diag::ext_mutable_reference) {
18200         Mutable = false;
18201         InvalidDecl = true;
18202       }
18203     }
18204   }
18205 
18206   // C++11 [class.union]p8 (DR1460):
18207   //   At most one variant member of a union may have a
18208   //   brace-or-equal-initializer.
18209   if (InitStyle != ICIS_NoInit)
18210     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18211 
18212   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18213                                        BitWidth, Mutable, InitStyle);
18214   if (InvalidDecl)
18215     NewFD->setInvalidDecl();
18216 
18217   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
18218     Diag(Loc, diag::err_duplicate_member) << II;
18219     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18220     NewFD->setInvalidDecl();
18221   }
18222 
18223   if (!InvalidDecl && getLangOpts().CPlusPlus) {
18224     if (Record->isUnion()) {
18225       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18226         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18227         if (RDecl->getDefinition()) {
18228           // C++ [class.union]p1: An object of a class with a non-trivial
18229           // constructor, a non-trivial copy constructor, a non-trivial
18230           // destructor, or a non-trivial copy assignment operator
18231           // cannot be a member of a union, nor can an array of such
18232           // objects.
18233           if (CheckNontrivialField(NewFD))
18234             NewFD->setInvalidDecl();
18235         }
18236       }
18237 
18238       // C++ [class.union]p1: If a union contains a member of reference type,
18239       // the program is ill-formed, except when compiling with MSVC extensions
18240       // enabled.
18241       if (EltTy->isReferenceType()) {
18242         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18243                                     diag::ext_union_member_of_reference_type :
18244                                     diag::err_union_member_of_reference_type)
18245           << NewFD->getDeclName() << EltTy;
18246         if (!getLangOpts().MicrosoftExt)
18247           NewFD->setInvalidDecl();
18248       }
18249     }
18250   }
18251 
18252   // FIXME: We need to pass in the attributes given an AST
18253   // representation, not a parser representation.
18254   if (D) {
18255     // FIXME: The current scope is almost... but not entirely... correct here.
18256     ProcessDeclAttributes(getCurScope(), NewFD, *D);
18257 
18258     if (NewFD->hasAttrs())
18259       CheckAlignasUnderalignment(NewFD);
18260   }
18261 
18262   // In auto-retain/release, infer strong retension for fields of
18263   // retainable type.
18264   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18265     NewFD->setInvalidDecl();
18266 
18267   if (T.isObjCGCWeak())
18268     Diag(Loc, diag::warn_attribute_weak_on_field);
18269 
18270   // PPC MMA non-pointer types are not allowed as field types.
18271   if (Context.getTargetInfo().getTriple().isPPC64() &&
18272       CheckPPCMMAType(T, NewFD->getLocation()))
18273     NewFD->setInvalidDecl();
18274 
18275   NewFD->setAccess(AS);
18276   return NewFD;
18277 }
18278 
18279 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18280   assert(FD);
18281   assert(getLangOpts().CPlusPlus && "valid check only for C++");
18282 
18283   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18284     return false;
18285 
18286   QualType EltTy = Context.getBaseElementType(FD->getType());
18287   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18288     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18289     if (RDecl->getDefinition()) {
18290       // We check for copy constructors before constructors
18291       // because otherwise we'll never get complaints about
18292       // copy constructors.
18293 
18294       CXXSpecialMember member = CXXInvalid;
18295       // We're required to check for any non-trivial constructors. Since the
18296       // implicit default constructor is suppressed if there are any
18297       // user-declared constructors, we just need to check that there is a
18298       // trivial default constructor and a trivial copy constructor. (We don't
18299       // worry about move constructors here, since this is a C++98 check.)
18300       if (RDecl->hasNonTrivialCopyConstructor())
18301         member = CXXCopyConstructor;
18302       else if (!RDecl->hasTrivialDefaultConstructor())
18303         member = CXXDefaultConstructor;
18304       else if (RDecl->hasNonTrivialCopyAssignment())
18305         member = CXXCopyAssignment;
18306       else if (RDecl->hasNonTrivialDestructor())
18307         member = CXXDestructor;
18308 
18309       if (member != CXXInvalid) {
18310         if (!getLangOpts().CPlusPlus11 &&
18311             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18312           // Objective-C++ ARC: it is an error to have a non-trivial field of
18313           // a union. However, system headers in Objective-C programs
18314           // occasionally have Objective-C lifetime objects within unions,
18315           // and rather than cause the program to fail, we make those
18316           // members unavailable.
18317           SourceLocation Loc = FD->getLocation();
18318           if (getSourceManager().isInSystemHeader(Loc)) {
18319             if (!FD->hasAttr<UnavailableAttr>())
18320               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18321                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18322             return false;
18323           }
18324         }
18325 
18326         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18327                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18328                diag::err_illegal_union_or_anon_struct_member)
18329           << FD->getParent()->isUnion() << FD->getDeclName() << member;
18330         DiagnoseNontrivial(RDecl, member);
18331         return !getLangOpts().CPlusPlus11;
18332       }
18333     }
18334   }
18335 
18336   return false;
18337 }
18338 
18339 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18340 ///  AST enum value.
18341 static ObjCIvarDecl::AccessControl
18342 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18343   switch (ivarVisibility) {
18344   default: llvm_unreachable("Unknown visitibility kind");
18345   case tok::objc_private: return ObjCIvarDecl::Private;
18346   case tok::objc_public: return ObjCIvarDecl::Public;
18347   case tok::objc_protected: return ObjCIvarDecl::Protected;
18348   case tok::objc_package: return ObjCIvarDecl::Package;
18349   }
18350 }
18351 
18352 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18353 /// in order to create an IvarDecl object for it.
18354 Decl *Sema::ActOnIvar(Scope *S,
18355                                 SourceLocation DeclStart,
18356                                 Declarator &D, Expr *BitfieldWidth,
18357                                 tok::ObjCKeywordKind Visibility) {
18358 
18359   IdentifierInfo *II = D.getIdentifier();
18360   Expr *BitWidth = (Expr*)BitfieldWidth;
18361   SourceLocation Loc = DeclStart;
18362   if (II) Loc = D.getIdentifierLoc();
18363 
18364   // FIXME: Unnamed fields can be handled in various different ways, for
18365   // example, unnamed unions inject all members into the struct namespace!
18366 
18367   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18368   QualType T = TInfo->getType();
18369 
18370   if (BitWidth) {
18371     // 6.7.2.1p3, 6.7.2.1p4
18372     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18373     if (!BitWidth)
18374       D.setInvalidType();
18375   } else {
18376     // Not a bitfield.
18377 
18378     // validate II.
18379 
18380   }
18381   if (T->isReferenceType()) {
18382     Diag(Loc, diag::err_ivar_reference_type);
18383     D.setInvalidType();
18384   }
18385   // C99 6.7.2.1p8: A member of a structure or union may have any type other
18386   // than a variably modified type.
18387   else if (T->isVariablyModifiedType()) {
18388     if (!tryToFixVariablyModifiedVarType(
18389             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18390       D.setInvalidType();
18391   }
18392 
18393   // Get the visibility (access control) for this ivar.
18394   ObjCIvarDecl::AccessControl ac =
18395     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18396                                         : ObjCIvarDecl::None;
18397   // Must set ivar's DeclContext to its enclosing interface.
18398   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18399   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18400     return nullptr;
18401   ObjCContainerDecl *EnclosingContext;
18402   if (ObjCImplementationDecl *IMPDecl =
18403       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18404     if (LangOpts.ObjCRuntime.isFragile()) {
18405     // Case of ivar declared in an implementation. Context is that of its class.
18406       EnclosingContext = IMPDecl->getClassInterface();
18407       assert(EnclosingContext && "Implementation has no class interface!");
18408     }
18409     else
18410       EnclosingContext = EnclosingDecl;
18411   } else {
18412     if (ObjCCategoryDecl *CDecl =
18413         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18414       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18415         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18416         return nullptr;
18417       }
18418     }
18419     EnclosingContext = EnclosingDecl;
18420   }
18421 
18422   // Construct the decl.
18423   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18424                                              DeclStart, Loc, II, T,
18425                                              TInfo, ac, (Expr *)BitfieldWidth);
18426 
18427   if (II) {
18428     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18429                                            ForVisibleRedeclaration);
18430     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18431         && !isa<TagDecl>(PrevDecl)) {
18432       Diag(Loc, diag::err_duplicate_member) << II;
18433       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18434       NewID->setInvalidDecl();
18435     }
18436   }
18437 
18438   // Process attributes attached to the ivar.
18439   ProcessDeclAttributes(S, NewID, D);
18440 
18441   if (D.isInvalidType())
18442     NewID->setInvalidDecl();
18443 
18444   // In ARC, infer 'retaining' for ivars of retainable type.
18445   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18446     NewID->setInvalidDecl();
18447 
18448   if (D.getDeclSpec().isModulePrivateSpecified())
18449     NewID->setModulePrivate();
18450 
18451   if (II) {
18452     // FIXME: When interfaces are DeclContexts, we'll need to add
18453     // these to the interface.
18454     S->AddDecl(NewID);
18455     IdResolver.AddDecl(NewID);
18456   }
18457 
18458   if (LangOpts.ObjCRuntime.isNonFragile() &&
18459       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18460     Diag(Loc, diag::warn_ivars_in_interface);
18461 
18462   return NewID;
18463 }
18464 
18465 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18466 /// class and class extensions. For every class \@interface and class
18467 /// extension \@interface, if the last ivar is a bitfield of any type,
18468 /// then add an implicit `char :0` ivar to the end of that interface.
18469 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18470                              SmallVectorImpl<Decl *> &AllIvarDecls) {
18471   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18472     return;
18473 
18474   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18475   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18476 
18477   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18478     return;
18479   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18480   if (!ID) {
18481     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18482       if (!CD->IsClassExtension())
18483         return;
18484     }
18485     // No need to add this to end of @implementation.
18486     else
18487       return;
18488   }
18489   // All conditions are met. Add a new bitfield to the tail end of ivars.
18490   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18491   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18492 
18493   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18494                               DeclLoc, DeclLoc, nullptr,
18495                               Context.CharTy,
18496                               Context.getTrivialTypeSourceInfo(Context.CharTy,
18497                                                                DeclLoc),
18498                               ObjCIvarDecl::Private, BW,
18499                               true);
18500   AllIvarDecls.push_back(Ivar);
18501 }
18502 
18503 /// [class.dtor]p4:
18504 ///   At the end of the definition of a class, overload resolution is
18505 ///   performed among the prospective destructors declared in that class with
18506 ///   an empty argument list to select the destructor for the class, also
18507 ///   known as the selected destructor.
18508 ///
18509 /// We do the overload resolution here, then mark the selected constructor in the AST.
18510 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18511 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18512   if (!Record->hasUserDeclaredDestructor()) {
18513     return;
18514   }
18515 
18516   SourceLocation Loc = Record->getLocation();
18517   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18518 
18519   for (auto *Decl : Record->decls()) {
18520     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18521       if (DD->isInvalidDecl())
18522         continue;
18523       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18524                              OCS);
18525       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18526     }
18527   }
18528 
18529   if (OCS.empty()) {
18530     return;
18531   }
18532   OverloadCandidateSet::iterator Best;
18533   unsigned Msg = 0;
18534   OverloadCandidateDisplayKind DisplayKind;
18535 
18536   switch (OCS.BestViableFunction(S, Loc, Best)) {
18537   case OR_Success:
18538   case OR_Deleted:
18539     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18540     break;
18541 
18542   case OR_Ambiguous:
18543     Msg = diag::err_ambiguous_destructor;
18544     DisplayKind = OCD_AmbiguousCandidates;
18545     break;
18546 
18547   case OR_No_Viable_Function:
18548     Msg = diag::err_no_viable_destructor;
18549     DisplayKind = OCD_AllCandidates;
18550     break;
18551   }
18552 
18553   if (Msg) {
18554     // OpenCL have got their own thing going with destructors. It's slightly broken,
18555     // but we allow it.
18556     if (!S.LangOpts.OpenCL) {
18557       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18558       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18559       Record->setInvalidDecl();
18560     }
18561     // It's a bit hacky: At this point we've raised an error but we want the
18562     // rest of the compiler to continue somehow working. However almost
18563     // everything we'll try to do with the class will depend on there being a
18564     // destructor. So let's pretend the first one is selected and hope for the
18565     // best.
18566     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18567   }
18568 }
18569 
18570 /// [class.mem.special]p5
18571 /// Two special member functions are of the same kind if:
18572 /// - they are both default constructors,
18573 /// - they are both copy or move constructors with the same first parameter
18574 ///   type, or
18575 /// - they are both copy or move assignment operators with the same first
18576 ///   parameter type and the same cv-qualifiers and ref-qualifier, if any.
18577 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18578                                               CXXMethodDecl *M1,
18579                                               CXXMethodDecl *M2,
18580                                               Sema::CXXSpecialMember CSM) {
18581   // We don't want to compare templates to non-templates: See
18582   // https://github.com/llvm/llvm-project/issues/59206
18583   if (CSM == Sema::CXXDefaultConstructor)
18584     return bool(M1->getDescribedFunctionTemplate()) ==
18585            bool(M2->getDescribedFunctionTemplate());
18586   if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18587                            M2->getParamDecl(0)->getType()))
18588     return false;
18589   if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18590     return false;
18591 
18592   return true;
18593 }
18594 
18595 /// [class.mem.special]p6:
18596 /// An eligible special member function is a special member function for which:
18597 /// - the function is not deleted,
18598 /// - the associated constraints, if any, are satisfied, and
18599 /// - no special member function of the same kind whose associated constraints
18600 ///   [CWG2595], if any, are satisfied is more constrained.
18601 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18602                                ArrayRef<CXXMethodDecl *> Methods,
18603                                Sema::CXXSpecialMember CSM) {
18604   SmallVector<bool, 4> SatisfactionStatus;
18605 
18606   for (CXXMethodDecl *Method : Methods) {
18607     const Expr *Constraints = Method->getTrailingRequiresClause();
18608     if (!Constraints)
18609       SatisfactionStatus.push_back(true);
18610     else {
18611       ConstraintSatisfaction Satisfaction;
18612       if (S.CheckFunctionConstraints(Method, Satisfaction))
18613         SatisfactionStatus.push_back(false);
18614       else
18615         SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18616     }
18617   }
18618 
18619   for (size_t i = 0; i < Methods.size(); i++) {
18620     if (!SatisfactionStatus[i])
18621       continue;
18622     CXXMethodDecl *Method = Methods[i];
18623     CXXMethodDecl *OrigMethod = Method;
18624     if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18625       OrigMethod = cast<CXXMethodDecl>(MF);
18626 
18627     const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18628     bool AnotherMethodIsMoreConstrained = false;
18629     for (size_t j = 0; j < Methods.size(); j++) {
18630       if (i == j || !SatisfactionStatus[j])
18631         continue;
18632       CXXMethodDecl *OtherMethod = Methods[j];
18633       if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18634         OtherMethod = cast<CXXMethodDecl>(MF);
18635 
18636       if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18637                                              CSM))
18638         continue;
18639 
18640       const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18641       if (!OtherConstraints)
18642         continue;
18643       if (!Constraints) {
18644         AnotherMethodIsMoreConstrained = true;
18645         break;
18646       }
18647       if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18648                                    {Constraints},
18649                                    AnotherMethodIsMoreConstrained)) {
18650         // There was an error with the constraints comparison. Exit the loop
18651         // and don't consider this function eligible.
18652         AnotherMethodIsMoreConstrained = true;
18653       }
18654       if (AnotherMethodIsMoreConstrained)
18655         break;
18656     }
18657     // FIXME: Do not consider deleted methods as eligible after implementing
18658     // DR1734 and DR1496.
18659     if (!AnotherMethodIsMoreConstrained) {
18660       Method->setIneligibleOrNotSelected(false);
18661       Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18662     }
18663   }
18664 }
18665 
18666 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18667                                                     CXXRecordDecl *Record) {
18668   SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18669   SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18670   SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18671   SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18672   SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18673 
18674   for (auto *Decl : Record->decls()) {
18675     auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18676     if (!MD) {
18677       auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18678       if (FTD)
18679         MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18680     }
18681     if (!MD)
18682       continue;
18683     if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18684       if (CD->isInvalidDecl())
18685         continue;
18686       if (CD->isDefaultConstructor())
18687         DefaultConstructors.push_back(MD);
18688       else if (CD->isCopyConstructor())
18689         CopyConstructors.push_back(MD);
18690       else if (CD->isMoveConstructor())
18691         MoveConstructors.push_back(MD);
18692     } else if (MD->isCopyAssignmentOperator()) {
18693       CopyAssignmentOperators.push_back(MD);
18694     } else if (MD->isMoveAssignmentOperator()) {
18695       MoveAssignmentOperators.push_back(MD);
18696     }
18697   }
18698 
18699   SetEligibleMethods(S, Record, DefaultConstructors,
18700                      Sema::CXXDefaultConstructor);
18701   SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18702   SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18703   SetEligibleMethods(S, Record, CopyAssignmentOperators,
18704                      Sema::CXXCopyAssignment);
18705   SetEligibleMethods(S, Record, MoveAssignmentOperators,
18706                      Sema::CXXMoveAssignment);
18707 }
18708 
18709 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18710                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
18711                        SourceLocation RBrac,
18712                        const ParsedAttributesView &Attrs) {
18713   assert(EnclosingDecl && "missing record or interface decl");
18714 
18715   // If this is an Objective-C @implementation or category and we have
18716   // new fields here we should reset the layout of the interface since
18717   // it will now change.
18718   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18719     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18720     switch (DC->getKind()) {
18721     default: break;
18722     case Decl::ObjCCategory:
18723       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18724       break;
18725     case Decl::ObjCImplementation:
18726       Context.
18727         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18728       break;
18729     }
18730   }
18731 
18732   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18733   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18734 
18735   // Start counting up the number of named members; make sure to include
18736   // members of anonymous structs and unions in the total.
18737   unsigned NumNamedMembers = 0;
18738   if (Record) {
18739     for (const auto *I : Record->decls()) {
18740       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18741         if (IFD->getDeclName())
18742           ++NumNamedMembers;
18743     }
18744   }
18745 
18746   // Verify that all the fields are okay.
18747   SmallVector<FieldDecl*, 32> RecFields;
18748 
18749   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18750        i != end; ++i) {
18751     FieldDecl *FD = cast<FieldDecl>(*i);
18752 
18753     // Get the type for the field.
18754     const Type *FDTy = FD->getType().getTypePtr();
18755 
18756     if (!FD->isAnonymousStructOrUnion()) {
18757       // Remember all fields written by the user.
18758       RecFields.push_back(FD);
18759     }
18760 
18761     // If the field is already invalid for some reason, don't emit more
18762     // diagnostics about it.
18763     if (FD->isInvalidDecl()) {
18764       EnclosingDecl->setInvalidDecl();
18765       continue;
18766     }
18767 
18768     // C99 6.7.2.1p2:
18769     //   A structure or union shall not contain a member with
18770     //   incomplete or function type (hence, a structure shall not
18771     //   contain an instance of itself, but may contain a pointer to
18772     //   an instance of itself), except that the last member of a
18773     //   structure with more than one named member may have incomplete
18774     //   array type; such a structure (and any union containing,
18775     //   possibly recursively, a member that is such a structure)
18776     //   shall not be a member of a structure or an element of an
18777     //   array.
18778     bool IsLastField = (i + 1 == Fields.end());
18779     if (FDTy->isFunctionType()) {
18780       // Field declared as a function.
18781       Diag(FD->getLocation(), diag::err_field_declared_as_function)
18782         << FD->getDeclName();
18783       FD->setInvalidDecl();
18784       EnclosingDecl->setInvalidDecl();
18785       continue;
18786     } else if (FDTy->isIncompleteArrayType() &&
18787                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18788       if (Record) {
18789         // Flexible array member.
18790         // Microsoft and g++ is more permissive regarding flexible array.
18791         // It will accept flexible array in union and also
18792         // as the sole element of a struct/class.
18793         unsigned DiagID = 0;
18794         if (!Record->isUnion() && !IsLastField) {
18795           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18796             << FD->getDeclName() << FD->getType() << Record->getTagKind();
18797           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18798           FD->setInvalidDecl();
18799           EnclosingDecl->setInvalidDecl();
18800           continue;
18801         } else if (Record->isUnion())
18802           DiagID = getLangOpts().MicrosoftExt
18803                        ? diag::ext_flexible_array_union_ms
18804                        : getLangOpts().CPlusPlus
18805                              ? diag::ext_flexible_array_union_gnu
18806                              : diag::err_flexible_array_union;
18807         else if (NumNamedMembers < 1)
18808           DiagID = getLangOpts().MicrosoftExt
18809                        ? diag::ext_flexible_array_empty_aggregate_ms
18810                        : getLangOpts().CPlusPlus
18811                              ? diag::ext_flexible_array_empty_aggregate_gnu
18812                              : diag::err_flexible_array_empty_aggregate;
18813 
18814         if (DiagID)
18815           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18816                                           << Record->getTagKind();
18817         // While the layout of types that contain virtual bases is not specified
18818         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18819         // virtual bases after the derived members.  This would make a flexible
18820         // array member declared at the end of an object not adjacent to the end
18821         // of the type.
18822         if (CXXRecord && CXXRecord->getNumVBases() != 0)
18823           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18824               << FD->getDeclName() << Record->getTagKind();
18825         if (!getLangOpts().C99)
18826           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18827             << FD->getDeclName() << Record->getTagKind();
18828 
18829         // If the element type has a non-trivial destructor, we would not
18830         // implicitly destroy the elements, so disallow it for now.
18831         //
18832         // FIXME: GCC allows this. We should probably either implicitly delete
18833         // the destructor of the containing class, or just allow this.
18834         QualType BaseElem = Context.getBaseElementType(FD->getType());
18835         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18836           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18837             << FD->getDeclName() << FD->getType();
18838           FD->setInvalidDecl();
18839           EnclosingDecl->setInvalidDecl();
18840           continue;
18841         }
18842         // Okay, we have a legal flexible array member at the end of the struct.
18843         Record->setHasFlexibleArrayMember(true);
18844       } else {
18845         // In ObjCContainerDecl ivars with incomplete array type are accepted,
18846         // unless they are followed by another ivar. That check is done
18847         // elsewhere, after synthesized ivars are known.
18848       }
18849     } else if (!FDTy->isDependentType() &&
18850                RequireCompleteSizedType(
18851                    FD->getLocation(), FD->getType(),
18852                    diag::err_field_incomplete_or_sizeless)) {
18853       // Incomplete type
18854       FD->setInvalidDecl();
18855       EnclosingDecl->setInvalidDecl();
18856       continue;
18857     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18858       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18859         // A type which contains a flexible array member is considered to be a
18860         // flexible array member.
18861         Record->setHasFlexibleArrayMember(true);
18862         if (!Record->isUnion()) {
18863           // If this is a struct/class and this is not the last element, reject
18864           // it.  Note that GCC supports variable sized arrays in the middle of
18865           // structures.
18866           if (!IsLastField)
18867             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18868               << FD->getDeclName() << FD->getType();
18869           else {
18870             // We support flexible arrays at the end of structs in
18871             // other structs as an extension.
18872             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18873               << FD->getDeclName();
18874           }
18875         }
18876       }
18877       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18878           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18879                                  diag::err_abstract_type_in_decl,
18880                                  AbstractIvarType)) {
18881         // Ivars can not have abstract class types
18882         FD->setInvalidDecl();
18883       }
18884       if (Record && FDTTy->getDecl()->hasObjectMember())
18885         Record->setHasObjectMember(true);
18886       if (Record && FDTTy->getDecl()->hasVolatileMember())
18887         Record->setHasVolatileMember(true);
18888     } else if (FDTy->isObjCObjectType()) {
18889       /// A field cannot be an Objective-c object
18890       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18891         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18892       QualType T = Context.getObjCObjectPointerType(FD->getType());
18893       FD->setType(T);
18894     } else if (Record && Record->isUnion() &&
18895                FD->getType().hasNonTrivialObjCLifetime() &&
18896                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18897                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18898                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18899                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18900       // For backward compatibility, fields of C unions declared in system
18901       // headers that have non-trivial ObjC ownership qualifications are marked
18902       // as unavailable unless the qualifier is explicit and __strong. This can
18903       // break ABI compatibility between programs compiled with ARC and MRR, but
18904       // is a better option than rejecting programs using those unions under
18905       // ARC.
18906       FD->addAttr(UnavailableAttr::CreateImplicit(
18907           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18908           FD->getLocation()));
18909     } else if (getLangOpts().ObjC &&
18910                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18911                !Record->hasObjectMember()) {
18912       if (FD->getType()->isObjCObjectPointerType() ||
18913           FD->getType().isObjCGCStrong())
18914         Record->setHasObjectMember(true);
18915       else if (Context.getAsArrayType(FD->getType())) {
18916         QualType BaseType = Context.getBaseElementType(FD->getType());
18917         if (BaseType->isRecordType() &&
18918             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18919           Record->setHasObjectMember(true);
18920         else if (BaseType->isObjCObjectPointerType() ||
18921                  BaseType.isObjCGCStrong())
18922                Record->setHasObjectMember(true);
18923       }
18924     }
18925 
18926     if (Record && !getLangOpts().CPlusPlus &&
18927         !shouldIgnoreForRecordTriviality(FD)) {
18928       QualType FT = FD->getType();
18929       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18930         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18931         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18932             Record->isUnion())
18933           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18934       }
18935       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18936       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18937         Record->setNonTrivialToPrimitiveCopy(true);
18938         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18939           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18940       }
18941       if (FT.isDestructedType()) {
18942         Record->setNonTrivialToPrimitiveDestroy(true);
18943         Record->setParamDestroyedInCallee(true);
18944         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18945           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18946       }
18947 
18948       if (const auto *RT = FT->getAs<RecordType>()) {
18949         if (RT->getDecl()->getArgPassingRestrictions() ==
18950             RecordDecl::APK_CanNeverPassInRegs)
18951           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18952       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18953         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18954     }
18955 
18956     if (Record && FD->getType().isVolatileQualified())
18957       Record->setHasVolatileMember(true);
18958     // Keep track of the number of named members.
18959     if (FD->getIdentifier())
18960       ++NumNamedMembers;
18961   }
18962 
18963   // Okay, we successfully defined 'Record'.
18964   if (Record) {
18965     bool Completed = false;
18966     if (CXXRecord) {
18967       if (!CXXRecord->isInvalidDecl()) {
18968         // Set access bits correctly on the directly-declared conversions.
18969         for (CXXRecordDecl::conversion_iterator
18970                I = CXXRecord->conversion_begin(),
18971                E = CXXRecord->conversion_end(); I != E; ++I)
18972           I.setAccess((*I)->getAccess());
18973       }
18974 
18975       // Add any implicitly-declared members to this class.
18976       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18977 
18978       if (!CXXRecord->isDependentType()) {
18979         if (!CXXRecord->isInvalidDecl()) {
18980           // If we have virtual base classes, we may end up finding multiple
18981           // final overriders for a given virtual function. Check for this
18982           // problem now.
18983           if (CXXRecord->getNumVBases()) {
18984             CXXFinalOverriderMap FinalOverriders;
18985             CXXRecord->getFinalOverriders(FinalOverriders);
18986 
18987             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18988                                              MEnd = FinalOverriders.end();
18989                  M != MEnd; ++M) {
18990               for (OverridingMethods::iterator SO = M->second.begin(),
18991                                             SOEnd = M->second.end();
18992                    SO != SOEnd; ++SO) {
18993                 assert(SO->second.size() > 0 &&
18994                        "Virtual function without overriding functions?");
18995                 if (SO->second.size() == 1)
18996                   continue;
18997 
18998                 // C++ [class.virtual]p2:
18999                 //   In a derived class, if a virtual member function of a base
19000                 //   class subobject has more than one final overrider the
19001                 //   program is ill-formed.
19002                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19003                   << (const NamedDecl *)M->first << Record;
19004                 Diag(M->first->getLocation(),
19005                      diag::note_overridden_virtual_function);
19006                 for (OverridingMethods::overriding_iterator
19007                           OM = SO->second.begin(),
19008                        OMEnd = SO->second.end();
19009                      OM != OMEnd; ++OM)
19010                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
19011                     << (const NamedDecl *)M->first << OM->Method->getParent();
19012 
19013                 Record->setInvalidDecl();
19014               }
19015             }
19016             CXXRecord->completeDefinition(&FinalOverriders);
19017             Completed = true;
19018           }
19019         }
19020         ComputeSelectedDestructor(*this, CXXRecord);
19021         ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19022       }
19023     }
19024 
19025     if (!Completed)
19026       Record->completeDefinition();
19027 
19028     // Handle attributes before checking the layout.
19029     ProcessDeclAttributeList(S, Record, Attrs);
19030 
19031     // Check to see if a FieldDecl is a pointer to a function.
19032     auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19033       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19034       if (!FD) {
19035         // Check whether this is a forward declaration that was inserted by
19036         // Clang. This happens when a non-forward declared / defined type is
19037         // used, e.g.:
19038         //
19039         //   struct foo {
19040         //     struct bar *(*f)();
19041         //     struct bar *(*g)();
19042         //   };
19043         //
19044         // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19045         // incomplete definition.
19046         if (const auto *TD = dyn_cast<TagDecl>(D))
19047           return !TD->isCompleteDefinition();
19048         return false;
19049       }
19050       QualType FieldType = FD->getType().getDesugaredType(Context);
19051       if (isa<PointerType>(FieldType)) {
19052         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19053         return PointeeType.getDesugaredType(Context)->isFunctionType();
19054       }
19055       return false;
19056     };
19057 
19058     // Maybe randomize the record's decls. We automatically randomize a record
19059     // of function pointers, unless it has the "no_randomize_layout" attribute.
19060     if (!getLangOpts().CPlusPlus &&
19061         (Record->hasAttr<RandomizeLayoutAttr>() ||
19062          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19063           llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19064         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19065         !Record->isRandomized()) {
19066       SmallVector<Decl *, 32> NewDeclOrdering;
19067       if (randstruct::randomizeStructureLayout(Context, Record,
19068                                                NewDeclOrdering))
19069         Record->reorderDecls(NewDeclOrdering);
19070     }
19071 
19072     // We may have deferred checking for a deleted destructor. Check now.
19073     if (CXXRecord) {
19074       auto *Dtor = CXXRecord->getDestructor();
19075       if (Dtor && Dtor->isImplicit() &&
19076           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19077         CXXRecord->setImplicitDestructorIsDeleted();
19078         SetDeclDeleted(Dtor, CXXRecord->getLocation());
19079       }
19080     }
19081 
19082     if (Record->hasAttrs()) {
19083       CheckAlignasUnderalignment(Record);
19084 
19085       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19086         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19087                                            IA->getRange(), IA->getBestCase(),
19088                                            IA->getInheritanceModel());
19089     }
19090 
19091     // Check if the structure/union declaration is a type that can have zero
19092     // size in C. For C this is a language extension, for C++ it may cause
19093     // compatibility problems.
19094     bool CheckForZeroSize;
19095     if (!getLangOpts().CPlusPlus) {
19096       CheckForZeroSize = true;
19097     } else {
19098       // For C++ filter out types that cannot be referenced in C code.
19099       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19100       CheckForZeroSize =
19101           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19102           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19103           CXXRecord->isCLike();
19104     }
19105     if (CheckForZeroSize) {
19106       bool ZeroSize = true;
19107       bool IsEmpty = true;
19108       unsigned NonBitFields = 0;
19109       for (RecordDecl::field_iterator I = Record->field_begin(),
19110                                       E = Record->field_end();
19111            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19112         IsEmpty = false;
19113         if (I->isUnnamedBitfield()) {
19114           if (!I->isZeroLengthBitField(Context))
19115             ZeroSize = false;
19116         } else {
19117           ++NonBitFields;
19118           QualType FieldType = I->getType();
19119           if (FieldType->isIncompleteType() ||
19120               !Context.getTypeSizeInChars(FieldType).isZero())
19121             ZeroSize = false;
19122         }
19123       }
19124 
19125       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19126       // allowed in C++, but warn if its declaration is inside
19127       // extern "C" block.
19128       if (ZeroSize) {
19129         Diag(RecLoc, getLangOpts().CPlusPlus ?
19130                          diag::warn_zero_size_struct_union_in_extern_c :
19131                          diag::warn_zero_size_struct_union_compat)
19132           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19133       }
19134 
19135       // Structs without named members are extension in C (C99 6.7.2.1p7),
19136       // but are accepted by GCC.
19137       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19138         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19139                                diag::ext_no_named_members_in_struct_union)
19140           << Record->isUnion();
19141       }
19142     }
19143   } else {
19144     ObjCIvarDecl **ClsFields =
19145       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19146     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19147       ID->setEndOfDefinitionLoc(RBrac);
19148       // Add ivar's to class's DeclContext.
19149       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19150         ClsFields[i]->setLexicalDeclContext(ID);
19151         ID->addDecl(ClsFields[i]);
19152       }
19153       // Must enforce the rule that ivars in the base classes may not be
19154       // duplicates.
19155       if (ID->getSuperClass())
19156         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19157     } else if (ObjCImplementationDecl *IMPDecl =
19158                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19159       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19160       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19161         // Ivar declared in @implementation never belongs to the implementation.
19162         // Only it is in implementation's lexical context.
19163         ClsFields[I]->setLexicalDeclContext(IMPDecl);
19164       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19165       IMPDecl->setIvarLBraceLoc(LBrac);
19166       IMPDecl->setIvarRBraceLoc(RBrac);
19167     } else if (ObjCCategoryDecl *CDecl =
19168                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19169       // case of ivars in class extension; all other cases have been
19170       // reported as errors elsewhere.
19171       // FIXME. Class extension does not have a LocEnd field.
19172       // CDecl->setLocEnd(RBrac);
19173       // Add ivar's to class extension's DeclContext.
19174       // Diagnose redeclaration of private ivars.
19175       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19176       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19177         if (IDecl) {
19178           if (const ObjCIvarDecl *ClsIvar =
19179               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19180             Diag(ClsFields[i]->getLocation(),
19181                  diag::err_duplicate_ivar_declaration);
19182             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19183             continue;
19184           }
19185           for (const auto *Ext : IDecl->known_extensions()) {
19186             if (const ObjCIvarDecl *ClsExtIvar
19187                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19188               Diag(ClsFields[i]->getLocation(),
19189                    diag::err_duplicate_ivar_declaration);
19190               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19191               continue;
19192             }
19193           }
19194         }
19195         ClsFields[i]->setLexicalDeclContext(CDecl);
19196         CDecl->addDecl(ClsFields[i]);
19197       }
19198       CDecl->setIvarLBraceLoc(LBrac);
19199       CDecl->setIvarRBraceLoc(RBrac);
19200     }
19201   }
19202 }
19203 
19204 /// Determine whether the given integral value is representable within
19205 /// the given type T.
19206 static bool isRepresentableIntegerValue(ASTContext &Context,
19207                                         llvm::APSInt &Value,
19208                                         QualType T) {
19209   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19210          "Integral type required!");
19211   unsigned BitWidth = Context.getIntWidth(T);
19212 
19213   if (Value.isUnsigned() || Value.isNonNegative()) {
19214     if (T->isSignedIntegerOrEnumerationType())
19215       --BitWidth;
19216     return Value.getActiveBits() <= BitWidth;
19217   }
19218   return Value.getSignificantBits() <= BitWidth;
19219 }
19220 
19221 // Given an integral type, return the next larger integral type
19222 // (or a NULL type of no such type exists).
19223 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19224   // FIXME: Int128/UInt128 support, which also needs to be introduced into
19225   // enum checking below.
19226   assert((T->isIntegralType(Context) ||
19227          T->isEnumeralType()) && "Integral type required!");
19228   const unsigned NumTypes = 4;
19229   QualType SignedIntegralTypes[NumTypes] = {
19230     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19231   };
19232   QualType UnsignedIntegralTypes[NumTypes] = {
19233     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19234     Context.UnsignedLongLongTy
19235   };
19236 
19237   unsigned BitWidth = Context.getTypeSize(T);
19238   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19239                                                         : UnsignedIntegralTypes;
19240   for (unsigned I = 0; I != NumTypes; ++I)
19241     if (Context.getTypeSize(Types[I]) > BitWidth)
19242       return Types[I];
19243 
19244   return QualType();
19245 }
19246 
19247 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19248                                           EnumConstantDecl *LastEnumConst,
19249                                           SourceLocation IdLoc,
19250                                           IdentifierInfo *Id,
19251                                           Expr *Val) {
19252   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19253   llvm::APSInt EnumVal(IntWidth);
19254   QualType EltTy;
19255 
19256   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19257     Val = nullptr;
19258 
19259   if (Val)
19260     Val = DefaultLvalueConversion(Val).get();
19261 
19262   if (Val) {
19263     if (Enum->isDependentType() || Val->isTypeDependent() ||
19264         Val->containsErrors())
19265       EltTy = Context.DependentTy;
19266     else {
19267       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19268       // underlying type, but do allow it in all other contexts.
19269       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19270         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19271         // constant-expression in the enumerator-definition shall be a converted
19272         // constant expression of the underlying type.
19273         EltTy = Enum->getIntegerType();
19274         ExprResult Converted =
19275           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19276                                            CCEK_Enumerator);
19277         if (Converted.isInvalid())
19278           Val = nullptr;
19279         else
19280           Val = Converted.get();
19281       } else if (!Val->isValueDependent() &&
19282                  !(Val =
19283                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19284                            .get())) {
19285         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19286       } else {
19287         if (Enum->isComplete()) {
19288           EltTy = Enum->getIntegerType();
19289 
19290           // In Obj-C and Microsoft mode, require the enumeration value to be
19291           // representable in the underlying type of the enumeration. In C++11,
19292           // we perform a non-narrowing conversion as part of converted constant
19293           // expression checking.
19294           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19295             if (Context.getTargetInfo()
19296                     .getTriple()
19297                     .isWindowsMSVCEnvironment()) {
19298               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19299             } else {
19300               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19301             }
19302           }
19303 
19304           // Cast to the underlying type.
19305           Val = ImpCastExprToType(Val, EltTy,
19306                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
19307                                                          : CK_IntegralCast)
19308                     .get();
19309         } else if (getLangOpts().CPlusPlus) {
19310           // C++11 [dcl.enum]p5:
19311           //   If the underlying type is not fixed, the type of each enumerator
19312           //   is the type of its initializing value:
19313           //     - If an initializer is specified for an enumerator, the
19314           //       initializing value has the same type as the expression.
19315           EltTy = Val->getType();
19316         } else {
19317           // C99 6.7.2.2p2:
19318           //   The expression that defines the value of an enumeration constant
19319           //   shall be an integer constant expression that has a value
19320           //   representable as an int.
19321 
19322           // Complain if the value is not representable in an int.
19323           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19324             Diag(IdLoc, diag::ext_enum_value_not_int)
19325               << toString(EnumVal, 10) << Val->getSourceRange()
19326               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19327           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19328             // Force the type of the expression to 'int'.
19329             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19330           }
19331           EltTy = Val->getType();
19332         }
19333       }
19334     }
19335   }
19336 
19337   if (!Val) {
19338     if (Enum->isDependentType())
19339       EltTy = Context.DependentTy;
19340     else if (!LastEnumConst) {
19341       // C++0x [dcl.enum]p5:
19342       //   If the underlying type is not fixed, the type of each enumerator
19343       //   is the type of its initializing value:
19344       //     - If no initializer is specified for the first enumerator, the
19345       //       initializing value has an unspecified integral type.
19346       //
19347       // GCC uses 'int' for its unspecified integral type, as does
19348       // C99 6.7.2.2p3.
19349       if (Enum->isFixed()) {
19350         EltTy = Enum->getIntegerType();
19351       }
19352       else {
19353         EltTy = Context.IntTy;
19354       }
19355     } else {
19356       // Assign the last value + 1.
19357       EnumVal = LastEnumConst->getInitVal();
19358       ++EnumVal;
19359       EltTy = LastEnumConst->getType();
19360 
19361       // Check for overflow on increment.
19362       if (EnumVal < LastEnumConst->getInitVal()) {
19363         // C++0x [dcl.enum]p5:
19364         //   If the underlying type is not fixed, the type of each enumerator
19365         //   is the type of its initializing value:
19366         //
19367         //     - Otherwise the type of the initializing value is the same as
19368         //       the type of the initializing value of the preceding enumerator
19369         //       unless the incremented value is not representable in that type,
19370         //       in which case the type is an unspecified integral type
19371         //       sufficient to contain the incremented value. If no such type
19372         //       exists, the program is ill-formed.
19373         QualType T = getNextLargerIntegralType(Context, EltTy);
19374         if (T.isNull() || Enum->isFixed()) {
19375           // There is no integral type larger enough to represent this
19376           // value. Complain, then allow the value to wrap around.
19377           EnumVal = LastEnumConst->getInitVal();
19378           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19379           ++EnumVal;
19380           if (Enum->isFixed())
19381             // When the underlying type is fixed, this is ill-formed.
19382             Diag(IdLoc, diag::err_enumerator_wrapped)
19383               << toString(EnumVal, 10)
19384               << EltTy;
19385           else
19386             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19387               << toString(EnumVal, 10);
19388         } else {
19389           EltTy = T;
19390         }
19391 
19392         // Retrieve the last enumerator's value, extent that type to the
19393         // type that is supposed to be large enough to represent the incremented
19394         // value, then increment.
19395         EnumVal = LastEnumConst->getInitVal();
19396         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19397         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19398         ++EnumVal;
19399 
19400         // If we're not in C++, diagnose the overflow of enumerator values,
19401         // which in C99 means that the enumerator value is not representable in
19402         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19403         // permits enumerator values that are representable in some larger
19404         // integral type.
19405         if (!getLangOpts().CPlusPlus && !T.isNull())
19406           Diag(IdLoc, diag::warn_enum_value_overflow);
19407       } else if (!getLangOpts().CPlusPlus &&
19408                  !EltTy->isDependentType() &&
19409                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19410         // Enforce C99 6.7.2.2p2 even when we compute the next value.
19411         Diag(IdLoc, diag::ext_enum_value_not_int)
19412           << toString(EnumVal, 10) << 1;
19413       }
19414     }
19415   }
19416 
19417   if (!EltTy->isDependentType()) {
19418     // Make the enumerator value match the signedness and size of the
19419     // enumerator's type.
19420     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19421     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19422   }
19423 
19424   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19425                                   Val, EnumVal);
19426 }
19427 
19428 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19429                                                 SourceLocation IILoc) {
19430   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19431       !getLangOpts().CPlusPlus)
19432     return SkipBodyInfo();
19433 
19434   // We have an anonymous enum definition. Look up the first enumerator to
19435   // determine if we should merge the definition with an existing one and
19436   // skip the body.
19437   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19438                                          forRedeclarationInCurContext());
19439   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19440   if (!PrevECD)
19441     return SkipBodyInfo();
19442 
19443   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19444   NamedDecl *Hidden;
19445   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19446     SkipBodyInfo Skip;
19447     Skip.Previous = Hidden;
19448     return Skip;
19449   }
19450 
19451   return SkipBodyInfo();
19452 }
19453 
19454 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19455                               SourceLocation IdLoc, IdentifierInfo *Id,
19456                               const ParsedAttributesView &Attrs,
19457                               SourceLocation EqualLoc, Expr *Val) {
19458   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19459   EnumConstantDecl *LastEnumConst =
19460     cast_or_null<EnumConstantDecl>(lastEnumConst);
19461 
19462   // The scope passed in may not be a decl scope.  Zip up the scope tree until
19463   // we find one that is.
19464   S = getNonFieldDeclScope(S);
19465 
19466   // Verify that there isn't already something declared with this name in this
19467   // scope.
19468   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19469   LookupName(R, S);
19470   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19471 
19472   if (PrevDecl && PrevDecl->isTemplateParameter()) {
19473     // Maybe we will complain about the shadowed template parameter.
19474     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19475     // Just pretend that we didn't see the previous declaration.
19476     PrevDecl = nullptr;
19477   }
19478 
19479   // C++ [class.mem]p15:
19480   // If T is the name of a class, then each of the following shall have a name
19481   // different from T:
19482   // - every enumerator of every member of class T that is an unscoped
19483   // enumerated type
19484   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19485     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19486                             DeclarationNameInfo(Id, IdLoc));
19487 
19488   EnumConstantDecl *New =
19489     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19490   if (!New)
19491     return nullptr;
19492 
19493   if (PrevDecl) {
19494     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19495       // Check for other kinds of shadowing not already handled.
19496       CheckShadow(New, PrevDecl, R);
19497     }
19498 
19499     // When in C++, we may get a TagDecl with the same name; in this case the
19500     // enum constant will 'hide' the tag.
19501     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19502            "Received TagDecl when not in C++!");
19503     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19504       if (isa<EnumConstantDecl>(PrevDecl))
19505         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19506       else
19507         Diag(IdLoc, diag::err_redefinition) << Id;
19508       notePreviousDefinition(PrevDecl, IdLoc);
19509       return nullptr;
19510     }
19511   }
19512 
19513   // Process attributes.
19514   ProcessDeclAttributeList(S, New, Attrs);
19515   AddPragmaAttributes(S, New);
19516 
19517   // Register this decl in the current scope stack.
19518   New->setAccess(TheEnumDecl->getAccess());
19519   PushOnScopeChains(New, S);
19520 
19521   ActOnDocumentableDecl(New);
19522 
19523   return New;
19524 }
19525 
19526 // Returns true when the enum initial expression does not trigger the
19527 // duplicate enum warning.  A few common cases are exempted as follows:
19528 // Element2 = Element1
19529 // Element2 = Element1 + 1
19530 // Element2 = Element1 - 1
19531 // Where Element2 and Element1 are from the same enum.
19532 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19533   Expr *InitExpr = ECD->getInitExpr();
19534   if (!InitExpr)
19535     return true;
19536   InitExpr = InitExpr->IgnoreImpCasts();
19537 
19538   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19539     if (!BO->isAdditiveOp())
19540       return true;
19541     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19542     if (!IL)
19543       return true;
19544     if (IL->getValue() != 1)
19545       return true;
19546 
19547     InitExpr = BO->getLHS();
19548   }
19549 
19550   // This checks if the elements are from the same enum.
19551   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19552   if (!DRE)
19553     return true;
19554 
19555   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19556   if (!EnumConstant)
19557     return true;
19558 
19559   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19560       Enum)
19561     return true;
19562 
19563   return false;
19564 }
19565 
19566 // Emits a warning when an element is implicitly set a value that
19567 // a previous element has already been set to.
19568 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19569                                         EnumDecl *Enum, QualType EnumType) {
19570   // Avoid anonymous enums
19571   if (!Enum->getIdentifier())
19572     return;
19573 
19574   // Only check for small enums.
19575   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19576     return;
19577 
19578   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19579     return;
19580 
19581   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19582   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19583 
19584   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19585 
19586   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19587   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19588 
19589   // Use int64_t as a key to avoid needing special handling for map keys.
19590   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19591     llvm::APSInt Val = D->getInitVal();
19592     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19593   };
19594 
19595   DuplicatesVector DupVector;
19596   ValueToVectorMap EnumMap;
19597 
19598   // Populate the EnumMap with all values represented by enum constants without
19599   // an initializer.
19600   for (auto *Element : Elements) {
19601     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19602 
19603     // Null EnumConstantDecl means a previous diagnostic has been emitted for
19604     // this constant.  Skip this enum since it may be ill-formed.
19605     if (!ECD) {
19606       return;
19607     }
19608 
19609     // Constants with initializers are handled in the next loop.
19610     if (ECD->getInitExpr())
19611       continue;
19612 
19613     // Duplicate values are handled in the next loop.
19614     EnumMap.insert({EnumConstantToKey(ECD), ECD});
19615   }
19616 
19617   if (EnumMap.size() == 0)
19618     return;
19619 
19620   // Create vectors for any values that has duplicates.
19621   for (auto *Element : Elements) {
19622     // The last loop returned if any constant was null.
19623     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19624     if (!ValidDuplicateEnum(ECD, Enum))
19625       continue;
19626 
19627     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19628     if (Iter == EnumMap.end())
19629       continue;
19630 
19631     DeclOrVector& Entry = Iter->second;
19632     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19633       // Ensure constants are different.
19634       if (D == ECD)
19635         continue;
19636 
19637       // Create new vector and push values onto it.
19638       auto Vec = std::make_unique<ECDVector>();
19639       Vec->push_back(D);
19640       Vec->push_back(ECD);
19641 
19642       // Update entry to point to the duplicates vector.
19643       Entry = Vec.get();
19644 
19645       // Store the vector somewhere we can consult later for quick emission of
19646       // diagnostics.
19647       DupVector.emplace_back(std::move(Vec));
19648       continue;
19649     }
19650 
19651     ECDVector *Vec = Entry.get<ECDVector*>();
19652     // Make sure constants are not added more than once.
19653     if (*Vec->begin() == ECD)
19654       continue;
19655 
19656     Vec->push_back(ECD);
19657   }
19658 
19659   // Emit diagnostics.
19660   for (const auto &Vec : DupVector) {
19661     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19662 
19663     // Emit warning for one enum constant.
19664     auto *FirstECD = Vec->front();
19665     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19666       << FirstECD << toString(FirstECD->getInitVal(), 10)
19667       << FirstECD->getSourceRange();
19668 
19669     // Emit one note for each of the remaining enum constants with
19670     // the same value.
19671     for (auto *ECD : llvm::drop_begin(*Vec))
19672       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19673         << ECD << toString(ECD->getInitVal(), 10)
19674         << ECD->getSourceRange();
19675   }
19676 }
19677 
19678 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19679                              bool AllowMask) const {
19680   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19681   assert(ED->isCompleteDefinition() && "expected enum definition");
19682 
19683   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19684   llvm::APInt &FlagBits = R.first->second;
19685 
19686   if (R.second) {
19687     for (auto *E : ED->enumerators()) {
19688       const auto &EVal = E->getInitVal();
19689       // Only single-bit enumerators introduce new flag values.
19690       if (EVal.isPowerOf2())
19691         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19692     }
19693   }
19694 
19695   // A value is in a flag enum if either its bits are a subset of the enum's
19696   // flag bits (the first condition) or we are allowing masks and the same is
19697   // true of its complement (the second condition). When masks are allowed, we
19698   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19699   //
19700   // While it's true that any value could be used as a mask, the assumption is
19701   // that a mask will have all of the insignificant bits set. Anything else is
19702   // likely a logic error.
19703   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19704   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19705 }
19706 
19707 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
19708                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19709                          const ParsedAttributesView &Attrs) {
19710   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19711   QualType EnumType = Context.getTypeDeclType(Enum);
19712 
19713   ProcessDeclAttributeList(S, Enum, Attrs);
19714 
19715   if (Enum->isDependentType()) {
19716     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19717       EnumConstantDecl *ECD =
19718         cast_or_null<EnumConstantDecl>(Elements[i]);
19719       if (!ECD) continue;
19720 
19721       ECD->setType(EnumType);
19722     }
19723 
19724     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19725     return;
19726   }
19727 
19728   // TODO: If the result value doesn't fit in an int, it must be a long or long
19729   // long value.  ISO C does not support this, but GCC does as an extension,
19730   // emit a warning.
19731   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19732   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19733   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19734 
19735   // Verify that all the values are okay, compute the size of the values, and
19736   // reverse the list.
19737   unsigned NumNegativeBits = 0;
19738   unsigned NumPositiveBits = 0;
19739 
19740   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19741     EnumConstantDecl *ECD =
19742       cast_or_null<EnumConstantDecl>(Elements[i]);
19743     if (!ECD) continue;  // Already issued a diagnostic.
19744 
19745     const llvm::APSInt &InitVal = ECD->getInitVal();
19746 
19747     // Keep track of the size of positive and negative values.
19748     if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19749       // If the enumerator is zero that should still be counted as a positive
19750       // bit since we need a bit to store the value zero.
19751       unsigned ActiveBits = InitVal.getActiveBits();
19752       NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19753     } else {
19754       NumNegativeBits =
19755           std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19756     }
19757   }
19758 
19759   // If we have an empty set of enumerators we still need one bit.
19760   // From [dcl.enum]p8
19761   // If the enumerator-list is empty, the values of the enumeration are as if
19762   // the enumeration had a single enumerator with value 0
19763   if (!NumPositiveBits && !NumNegativeBits)
19764     NumPositiveBits = 1;
19765 
19766   // Figure out the type that should be used for this enum.
19767   QualType BestType;
19768   unsigned BestWidth;
19769 
19770   // C++0x N3000 [conv.prom]p3:
19771   //   An rvalue of an unscoped enumeration type whose underlying
19772   //   type is not fixed can be converted to an rvalue of the first
19773   //   of the following types that can represent all the values of
19774   //   the enumeration: int, unsigned int, long int, unsigned long
19775   //   int, long long int, or unsigned long long int.
19776   // C99 6.4.4.3p2:
19777   //   An identifier declared as an enumeration constant has type int.
19778   // The C99 rule is modified by a gcc extension
19779   QualType BestPromotionType;
19780 
19781   bool Packed = Enum->hasAttr<PackedAttr>();
19782   // -fshort-enums is the equivalent to specifying the packed attribute on all
19783   // enum definitions.
19784   if (LangOpts.ShortEnums)
19785     Packed = true;
19786 
19787   // If the enum already has a type because it is fixed or dictated by the
19788   // target, promote that type instead of analyzing the enumerators.
19789   if (Enum->isComplete()) {
19790     BestType = Enum->getIntegerType();
19791     if (Context.isPromotableIntegerType(BestType))
19792       BestPromotionType = Context.getPromotedIntegerType(BestType);
19793     else
19794       BestPromotionType = BestType;
19795 
19796     BestWidth = Context.getIntWidth(BestType);
19797   }
19798   else if (NumNegativeBits) {
19799     // If there is a negative value, figure out the smallest integer type (of
19800     // int/long/longlong) that fits.
19801     // If it's packed, check also if it fits a char or a short.
19802     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19803       BestType = Context.SignedCharTy;
19804       BestWidth = CharWidth;
19805     } else if (Packed && NumNegativeBits <= ShortWidth &&
19806                NumPositiveBits < ShortWidth) {
19807       BestType = Context.ShortTy;
19808       BestWidth = ShortWidth;
19809     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19810       BestType = Context.IntTy;
19811       BestWidth = IntWidth;
19812     } else {
19813       BestWidth = Context.getTargetInfo().getLongWidth();
19814 
19815       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19816         BestType = Context.LongTy;
19817       } else {
19818         BestWidth = Context.getTargetInfo().getLongLongWidth();
19819 
19820         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19821           Diag(Enum->getLocation(), diag::ext_enum_too_large);
19822         BestType = Context.LongLongTy;
19823       }
19824     }
19825     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19826   } else {
19827     // If there is no negative value, figure out the smallest type that fits
19828     // all of the enumerator values.
19829     // If it's packed, check also if it fits a char or a short.
19830     if (Packed && NumPositiveBits <= CharWidth) {
19831       BestType = Context.UnsignedCharTy;
19832       BestPromotionType = Context.IntTy;
19833       BestWidth = CharWidth;
19834     } else if (Packed && NumPositiveBits <= ShortWidth) {
19835       BestType = Context.UnsignedShortTy;
19836       BestPromotionType = Context.IntTy;
19837       BestWidth = ShortWidth;
19838     } else if (NumPositiveBits <= IntWidth) {
19839       BestType = Context.UnsignedIntTy;
19840       BestWidth = IntWidth;
19841       BestPromotionType
19842         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19843                            ? Context.UnsignedIntTy : Context.IntTy;
19844     } else if (NumPositiveBits <=
19845                (BestWidth = Context.getTargetInfo().getLongWidth())) {
19846       BestType = Context.UnsignedLongTy;
19847       BestPromotionType
19848         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19849                            ? Context.UnsignedLongTy : Context.LongTy;
19850     } else {
19851       BestWidth = Context.getTargetInfo().getLongLongWidth();
19852       assert(NumPositiveBits <= BestWidth &&
19853              "How could an initializer get larger than ULL?");
19854       BestType = Context.UnsignedLongLongTy;
19855       BestPromotionType
19856         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19857                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
19858     }
19859   }
19860 
19861   // Loop over all of the enumerator constants, changing their types to match
19862   // the type of the enum if needed.
19863   for (auto *D : Elements) {
19864     auto *ECD = cast_or_null<EnumConstantDecl>(D);
19865     if (!ECD) continue;  // Already issued a diagnostic.
19866 
19867     // Standard C says the enumerators have int type, but we allow, as an
19868     // extension, the enumerators to be larger than int size.  If each
19869     // enumerator value fits in an int, type it as an int, otherwise type it the
19870     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
19871     // that X has type 'int', not 'unsigned'.
19872 
19873     // Determine whether the value fits into an int.
19874     llvm::APSInt InitVal = ECD->getInitVal();
19875 
19876     // If it fits into an integer type, force it.  Otherwise force it to match
19877     // the enum decl type.
19878     QualType NewTy;
19879     unsigned NewWidth;
19880     bool NewSign;
19881     if (!getLangOpts().CPlusPlus &&
19882         !Enum->isFixed() &&
19883         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19884       NewTy = Context.IntTy;
19885       NewWidth = IntWidth;
19886       NewSign = true;
19887     } else if (ECD->getType() == BestType) {
19888       // Already the right type!
19889       if (getLangOpts().CPlusPlus)
19890         // C++ [dcl.enum]p4: Following the closing brace of an
19891         // enum-specifier, each enumerator has the type of its
19892         // enumeration.
19893         ECD->setType(EnumType);
19894       continue;
19895     } else {
19896       NewTy = BestType;
19897       NewWidth = BestWidth;
19898       NewSign = BestType->isSignedIntegerOrEnumerationType();
19899     }
19900 
19901     // Adjust the APSInt value.
19902     InitVal = InitVal.extOrTrunc(NewWidth);
19903     InitVal.setIsSigned(NewSign);
19904     ECD->setInitVal(InitVal);
19905 
19906     // Adjust the Expr initializer and type.
19907     if (ECD->getInitExpr() &&
19908         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19909       ECD->setInitExpr(ImplicitCastExpr::Create(
19910           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19911           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19912     if (getLangOpts().CPlusPlus)
19913       // C++ [dcl.enum]p4: Following the closing brace of an
19914       // enum-specifier, each enumerator has the type of its
19915       // enumeration.
19916       ECD->setType(EnumType);
19917     else
19918       ECD->setType(NewTy);
19919   }
19920 
19921   Enum->completeDefinition(BestType, BestPromotionType,
19922                            NumPositiveBits, NumNegativeBits);
19923 
19924   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19925 
19926   if (Enum->isClosedFlag()) {
19927     for (Decl *D : Elements) {
19928       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19929       if (!ECD) continue;  // Already issued a diagnostic.
19930 
19931       llvm::APSInt InitVal = ECD->getInitVal();
19932       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19933           !IsValueInFlagEnum(Enum, InitVal, true))
19934         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19935           << ECD << Enum;
19936     }
19937   }
19938 
19939   // Now that the enum type is defined, ensure it's not been underaligned.
19940   if (Enum->hasAttrs())
19941     CheckAlignasUnderalignment(Enum);
19942 }
19943 
19944 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19945                                   SourceLocation StartLoc,
19946                                   SourceLocation EndLoc) {
19947   StringLiteral *AsmString = cast<StringLiteral>(expr);
19948 
19949   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19950                                                    AsmString, StartLoc,
19951                                                    EndLoc);
19952   CurContext->addDecl(New);
19953   return New;
19954 }
19955 
19956 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
19957   auto *New = TopLevelStmtDecl::Create(Context, Statement);
19958   Context.getTranslationUnitDecl()->addDecl(New);
19959   return New;
19960 }
19961 
19962 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19963                                       IdentifierInfo* AliasName,
19964                                       SourceLocation PragmaLoc,
19965                                       SourceLocation NameLoc,
19966                                       SourceLocation AliasNameLoc) {
19967   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19968                                          LookupOrdinaryName);
19969   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19970                            AttributeCommonInfo::Form::Pragma());
19971   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19972       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19973 
19974   // If a declaration that:
19975   // 1) declares a function or a variable
19976   // 2) has external linkage
19977   // already exists, add a label attribute to it.
19978   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19979     if (isDeclExternC(PrevDecl))
19980       PrevDecl->addAttr(Attr);
19981     else
19982       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19983           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19984     // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19985   } else
19986     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19987 }
19988 
19989 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19990                              SourceLocation PragmaLoc,
19991                              SourceLocation NameLoc) {
19992   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19993 
19994   if (PrevDecl) {
19995     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
19996   } else {
19997     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19998   }
19999 }
20000 
20001 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20002                                 IdentifierInfo* AliasName,
20003                                 SourceLocation PragmaLoc,
20004                                 SourceLocation NameLoc,
20005                                 SourceLocation AliasNameLoc) {
20006   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20007                                     LookupOrdinaryName);
20008   WeakInfo W = WeakInfo(Name, NameLoc);
20009 
20010   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20011     if (!PrevDecl->hasAttr<AliasAttr>())
20012       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20013         DeclApplyPragmaWeak(TUScope, ND, W);
20014   } else {
20015     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20016   }
20017 }
20018 
20019 ObjCContainerDecl *Sema::getObjCDeclContext() const {
20020   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20021 }
20022 
20023 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20024                                                      bool Final) {
20025   assert(FD && "Expected non-null FunctionDecl");
20026 
20027   // SYCL functions can be template, so we check if they have appropriate
20028   // attribute prior to checking if it is a template.
20029   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20030     return FunctionEmissionStatus::Emitted;
20031 
20032   // Templates are emitted when they're instantiated.
20033   if (FD->isDependentContext())
20034     return FunctionEmissionStatus::TemplateDiscarded;
20035 
20036   // Check whether this function is an externally visible definition.
20037   auto IsEmittedForExternalSymbol = [this, FD]() {
20038     // We have to check the GVA linkage of the function's *definition* -- if we
20039     // only have a declaration, we don't know whether or not the function will
20040     // be emitted, because (say) the definition could include "inline".
20041     const FunctionDecl *Def = FD->getDefinition();
20042 
20043     return Def && !isDiscardableGVALinkage(
20044                       getASTContext().GetGVALinkageForFunction(Def));
20045   };
20046 
20047   if (LangOpts.OpenMPIsTargetDevice) {
20048     // In OpenMP device mode we will not emit host only functions, or functions
20049     // we don't need due to their linkage.
20050     std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20051         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20052     // DevTy may be changed later by
20053     //  #pragma omp declare target to(*) device_type(*).
20054     // Therefore DevTy having no value does not imply host. The emission status
20055     // will be checked again at the end of compilation unit with Final = true.
20056     if (DevTy)
20057       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20058         return FunctionEmissionStatus::OMPDiscarded;
20059     // If we have an explicit value for the device type, or we are in a target
20060     // declare context, we need to emit all extern and used symbols.
20061     if (isInOpenMPDeclareTargetContext() || DevTy)
20062       if (IsEmittedForExternalSymbol())
20063         return FunctionEmissionStatus::Emitted;
20064     // Device mode only emits what it must, if it wasn't tagged yet and needed,
20065     // we'll omit it.
20066     if (Final)
20067       return FunctionEmissionStatus::OMPDiscarded;
20068   } else if (LangOpts.OpenMP > 45) {
20069     // In OpenMP host compilation prior to 5.0 everything was an emitted host
20070     // function. In 5.0, no_host was introduced which might cause a function to
20071     // be ommitted.
20072     std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20073         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20074     if (DevTy)
20075       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20076         return FunctionEmissionStatus::OMPDiscarded;
20077   }
20078 
20079   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20080     return FunctionEmissionStatus::Emitted;
20081 
20082   if (LangOpts.CUDA) {
20083     // When compiling for device, host functions are never emitted.  Similarly,
20084     // when compiling for host, device and global functions are never emitted.
20085     // (Technically, we do emit a host-side stub for global functions, but this
20086     // doesn't count for our purposes here.)
20087     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20088     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20089       return FunctionEmissionStatus::CUDADiscarded;
20090     if (!LangOpts.CUDAIsDevice &&
20091         (T == Sema::CFT_Device || T == Sema::CFT_Global))
20092       return FunctionEmissionStatus::CUDADiscarded;
20093 
20094     if (IsEmittedForExternalSymbol())
20095       return FunctionEmissionStatus::Emitted;
20096   }
20097 
20098   // Otherwise, the function is known-emitted if it's in our set of
20099   // known-emitted functions.
20100   return FunctionEmissionStatus::Unknown;
20101 }
20102 
20103 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20104   // Host-side references to a __global__ function refer to the stub, so the
20105   // function itself is never emitted and therefore should not be marked.
20106   // If we have host fn calls kernel fn calls host+device, the HD function
20107   // does not get instantiated on the host. We model this by omitting at the
20108   // call to the kernel from the callgraph. This ensures that, when compiling
20109   // for host, only HD functions actually called from the host get marked as
20110   // known-emitted.
20111   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20112          IdentifyCUDATarget(Callee) == CFT_Global;
20113 }
20114