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/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/CXXFieldCollector.h"
38 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/DelayedDiagnostic.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/Triple.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <functional>
52 #include <unordered_map>
53 
54 using namespace clang;
55 using namespace sema;
56 
57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
58   if (OwnedType) {
59     Decl *Group[2] = { OwnedType, Ptr };
60     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
61   }
62 
63   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 }
65 
66 namespace {
67 
68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
69  public:
70    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
71                         bool AllowTemplates = false,
72                         bool AllowNonTemplates = true)
73        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
74          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
75      WantExpressionKeywords = false;
76      WantCXXNamedCasts = false;
77      WantRemainingKeywords = false;
78   }
79 
80   bool ValidateCandidate(const TypoCorrection &candidate) override {
81     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
82       if (!AllowInvalidDecl && ND->isInvalidDecl())
83         return false;
84 
85       if (getAsTypeTemplateDecl(ND))
86         return AllowTemplates;
87 
88       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89       if (!IsType)
90         return false;
91 
92       if (AllowNonTemplates)
93         return true;
94 
95       // An injected-class-name of a class template (specialization) is valid
96       // as a template or as a non-template.
97       if (AllowTemplates) {
98         auto *RD = dyn_cast<CXXRecordDecl>(ND);
99         if (!RD || !RD->isInjectedClassName())
100           return false;
101         RD = cast<CXXRecordDecl>(RD->getDeclContext());
102         return RD->getDescribedClassTemplate() ||
103                isa<ClassTemplateSpecializationDecl>(RD);
104       }
105 
106       return false;
107     }
108 
109     return !WantClassName && candidate.isKeyword();
110   }
111 
112   std::unique_ptr<CorrectionCandidateCallback> clone() override {
113     return std::make_unique<TypeNameValidatorCCC>(*this);
114   }
115 
116  private:
117   bool AllowInvalidDecl;
118   bool WantClassName;
119   bool AllowTemplates;
120   bool AllowNonTemplates;
121 };
122 
123 } // end anonymous namespace
124 
125 /// Determine whether the token kind starts a simple-type-specifier.
126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
127   switch (Kind) {
128   // FIXME: Take into account the current language when deciding whether a
129   // token kind is a valid type specifier
130   case tok::kw_short:
131   case tok::kw_long:
132   case tok::kw___int64:
133   case tok::kw___int128:
134   case tok::kw_signed:
135   case tok::kw_unsigned:
136   case tok::kw_void:
137   case tok::kw_char:
138   case tok::kw_int:
139   case tok::kw_half:
140   case tok::kw_float:
141   case tok::kw_double:
142   case tok::kw___bf16:
143   case tok::kw__Float16:
144   case tok::kw___float128:
145   case tok::kw___ibm128:
146   case tok::kw_wchar_t:
147   case tok::kw_bool:
148   case tok::kw___underlying_type:
149   case tok::kw___auto_type:
150     return true;
151 
152   case tok::annot_typename:
153   case tok::kw_char16_t:
154   case tok::kw_char32_t:
155   case tok::kw_typeof:
156   case tok::annot_decltype:
157   case tok::kw_decltype:
158     return getLangOpts().CPlusPlus;
159 
160   case tok::kw_char8_t:
161     return getLangOpts().Char8;
162 
163   default:
164     break;
165   }
166 
167   return false;
168 }
169 
170 namespace {
171 enum class UnqualifiedTypeNameLookupResult {
172   NotFound,
173   FoundNonType,
174   FoundType
175 };
176 } // end anonymous namespace
177 
178 /// Tries to perform unqualified lookup of the type decls in bases for
179 /// dependent class.
180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
181 /// type decl, \a FoundType if only type decls are found.
182 static UnqualifiedTypeNameLookupResult
183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
184                                 SourceLocation NameLoc,
185                                 const CXXRecordDecl *RD) {
186   if (!RD->hasDefinition())
187     return UnqualifiedTypeNameLookupResult::NotFound;
188   // Look for type decls in base classes.
189   UnqualifiedTypeNameLookupResult FoundTypeDecl =
190       UnqualifiedTypeNameLookupResult::NotFound;
191   for (const auto &Base : RD->bases()) {
192     const CXXRecordDecl *BaseRD = nullptr;
193     if (auto *BaseTT = Base.getType()->getAs<TagType>())
194       BaseRD = BaseTT->getAsCXXRecordDecl();
195     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
196       // Look for type decls in dependent base classes that have known primary
197       // templates.
198       if (!TST || !TST->isDependentType())
199         continue;
200       auto *TD = TST->getTemplateName().getAsTemplateDecl();
201       if (!TD)
202         continue;
203       if (auto *BasePrimaryTemplate =
204           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
205         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
206           BaseRD = BasePrimaryTemplate;
207         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208           if (const ClassTemplatePartialSpecializationDecl *PS =
209                   CTD->findPartialSpecialization(Base.getType()))
210             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
211               BaseRD = PS;
212         }
213       }
214     }
215     if (BaseRD) {
216       for (NamedDecl *ND : BaseRD->lookup(&II)) {
217         if (!isa<TypeDecl>(ND))
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220       }
221       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
222         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
223         case UnqualifiedTypeNameLookupResult::FoundNonType:
224           return UnqualifiedTypeNameLookupResult::FoundNonType;
225         case UnqualifiedTypeNameLookupResult::FoundType:
226           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
227           break;
228         case UnqualifiedTypeNameLookupResult::NotFound:
229           break;
230         }
231       }
232     }
233   }
234 
235   return FoundTypeDecl;
236 }
237 
238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
239                                                       const IdentifierInfo &II,
240                                                       SourceLocation NameLoc) {
241   // Lookup in the parent class template context, if any.
242   const CXXRecordDecl *RD = nullptr;
243   UnqualifiedTypeNameLookupResult FoundTypeDecl =
244       UnqualifiedTypeNameLookupResult::NotFound;
245   for (DeclContext *DC = S.CurContext;
246        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
247        DC = DC->getParent()) {
248     // Look for type decls in dependent base classes that have known primary
249     // templates.
250     RD = dyn_cast<CXXRecordDecl>(DC);
251     if (RD && RD->getDescribedClassTemplate())
252       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
253   }
254   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
255     return nullptr;
256 
257   // We found some types in dependent base classes.  Recover as if the user
258   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
259   // lookup during template instantiation.
260   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
261 
262   ASTContext &Context = S.Context;
263   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
264                                           cast<Type>(Context.getRecordType(RD)));
265   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
266 
267   CXXScopeSpec SS;
268   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
269 
270   TypeLocBuilder Builder;
271   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
272   DepTL.setNameLoc(NameLoc);
273   DepTL.setElaboratedKeywordLoc(SourceLocation());
274   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
275   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
276 }
277 
278 /// If the identifier refers to a type name within this scope,
279 /// return the declaration of that type.
280 ///
281 /// This routine performs ordinary name lookup of the identifier II
282 /// within the given scope, with optional C++ scope specifier SS, to
283 /// determine whether the name refers to a type. If so, returns an
284 /// opaque pointer (actually a QualType) corresponding to that
285 /// type. Otherwise, returns NULL.
286 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
287                              Scope *S, CXXScopeSpec *SS,
288                              bool isClassName, bool HasTrailingDot,
289                              ParsedType ObjectTypePtr,
290                              bool IsCtorOrDtorName,
291                              bool WantNontrivialTypeSourceInfo,
292                              bool IsClassTemplateDeductionContext,
293                              IdentifierInfo **CorrectedII) {
294   // FIXME: Consider allowing this outside C++1z mode as an extension.
295   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297                               !isClassName && !HasTrailingDot;
298 
299   // Determine where we will perform name lookup.
300   DeclContext *LookupCtx = nullptr;
301   if (ObjectTypePtr) {
302     QualType ObjectType = ObjectTypePtr.get();
303     if (ObjectType->isRecordType())
304       LookupCtx = computeDeclContext(ObjectType);
305   } else if (SS && SS->isNotEmpty()) {
306     LookupCtx = computeDeclContext(*SS, false);
307 
308     if (!LookupCtx) {
309       if (isDependentScopeSpecifier(*SS)) {
310         // C++ [temp.res]p3:
311         //   A qualified-id that refers to a type and in which the
312         //   nested-name-specifier depends on a template-parameter (14.6.2)
313         //   shall be prefixed by the keyword typename to indicate that the
314         //   qualified-id denotes a type, forming an
315         //   elaborated-type-specifier (7.1.5.3).
316         //
317         // We therefore do not perform any name lookup if the result would
318         // refer to a member of an unknown specialization.
319         if (!isClassName && !IsCtorOrDtorName)
320           return nullptr;
321 
322         // We know from the grammar that this name refers to a type,
323         // so build a dependent node to describe the type.
324         if (WantNontrivialTypeSourceInfo)
325           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
326 
327         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
328         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
329                                        II, NameLoc);
330         return ParsedType::make(T);
331       }
332 
333       return nullptr;
334     }
335 
336     if (!LookupCtx->isDependentContext() &&
337         RequireCompleteDeclContext(*SS, LookupCtx))
338       return nullptr;
339   }
340 
341   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
342   // lookup for class-names.
343   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
344                                       LookupOrdinaryName;
345   LookupResult Result(*this, &II, NameLoc, Kind);
346   if (LookupCtx) {
347     // Perform "qualified" name lookup into the declaration context we
348     // computed, which is either the type of the base of a member access
349     // expression or the declaration context associated with a prior
350     // nested-name-specifier.
351     LookupQualifiedName(Result, LookupCtx);
352 
353     if (ObjectTypePtr && Result.empty()) {
354       // C++ [basic.lookup.classref]p3:
355       //   If the unqualified-id is ~type-name, the type-name is looked up
356       //   in the context of the entire postfix-expression. If the type T of
357       //   the object expression is of a class type C, the type-name is also
358       //   looked up in the scope of class C. At least one of the lookups shall
359       //   find a name that refers to (possibly cv-qualified) T.
360       LookupName(Result, S);
361     }
362   } else {
363     // Perform unqualified name lookup.
364     LookupName(Result, S);
365 
366     // For unqualified lookup in a class template in MSVC mode, look into
367     // dependent base classes where the primary class template is known.
368     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
369       if (ParsedType TypeInBase =
370               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
371         return TypeInBase;
372     }
373   }
374 
375   NamedDecl *IIDecl = nullptr;
376   UsingShadowDecl *FoundUsingShadow = nullptr;
377   switch (Result.getResultKind()) {
378   case LookupResult::NotFound:
379   case LookupResult::NotFoundInCurrentInstantiation:
380     if (CorrectedII) {
381       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
382                                AllowDeducedTemplate);
383       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
384                                               S, SS, CCC, CTK_ErrorRecovery);
385       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
386       TemplateTy Template;
387       bool MemberOfUnknownSpecialization;
388       UnqualifiedId TemplateName;
389       TemplateName.setIdentifier(NewII, NameLoc);
390       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
391       CXXScopeSpec NewSS, *NewSSPtr = SS;
392       if (SS && NNS) {
393         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
394         NewSSPtr = &NewSS;
395       }
396       if (Correction && (NNS || NewII != &II) &&
397           // Ignore a correction to a template type as the to-be-corrected
398           // identifier is not a template (typo correction for template names
399           // is handled elsewhere).
400           !(getLangOpts().CPlusPlus && NewSSPtr &&
401             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
402                            Template, MemberOfUnknownSpecialization))) {
403         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
404                                     isClassName, HasTrailingDot, ObjectTypePtr,
405                                     IsCtorOrDtorName,
406                                     WantNontrivialTypeSourceInfo,
407                                     IsClassTemplateDeductionContext);
408         if (Ty) {
409           diagnoseTypo(Correction,
410                        PDiag(diag::err_unknown_type_or_class_name_suggest)
411                          << Result.getLookupName() << isClassName);
412           if (SS && NNS)
413             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
414           *CorrectedII = NewII;
415           return Ty;
416         }
417       }
418     }
419     // If typo correction failed or was not performed, fall through
420     LLVM_FALLTHROUGH;
421   case LookupResult::FoundOverloaded:
422   case LookupResult::FoundUnresolvedValue:
423     Result.suppressDiagnostics();
424     return nullptr;
425 
426   case LookupResult::Ambiguous:
427     // Recover from type-hiding ambiguities by hiding the type.  We'll
428     // do the lookup again when looking for an object, and we can
429     // diagnose the error then.  If we don't do this, then the error
430     // about hiding the type will be immediately followed by an error
431     // that only makes sense if the identifier was treated like a type.
432     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
433       Result.suppressDiagnostics();
434       return nullptr;
435     }
436 
437     // Look to see if we have a type anywhere in the list of results.
438     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
439          Res != ResEnd; ++Res) {
440       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
441       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
442               RealRes) ||
443           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
444         if (!IIDecl ||
445             // Make the selection of the recovery decl deterministic.
446             RealRes->getLocation() < IIDecl->getLocation()) {
447           IIDecl = RealRes;
448           FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
449         }
450       }
451     }
452 
453     if (!IIDecl) {
454       // None of the entities we found is a type, so there is no way
455       // to even assume that the result is a type. In this case, don't
456       // complain about the ambiguity. The parser will either try to
457       // perform this lookup again (e.g., as an object name), which
458       // will produce the ambiguity, or will complain that it expected
459       // a type name.
460       Result.suppressDiagnostics();
461       return nullptr;
462     }
463 
464     // We found a type within the ambiguous lookup; diagnose the
465     // ambiguity and then return that type. This might be the right
466     // answer, or it might not be, but it suppresses any attempt to
467     // perform the name lookup again.
468     break;
469 
470   case LookupResult::Found:
471     IIDecl = Result.getFoundDecl();
472     FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
473     break;
474   }
475 
476   assert(IIDecl && "Didn't find decl");
477 
478   QualType T;
479   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
480     // C++ [class.qual]p2: A lookup that would find the injected-class-name
481     // instead names the constructors of the class, except when naming a class.
482     // This is ill-formed when we're not actually forming a ctor or dtor name.
483     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
484     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
485     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
486         FoundRD->isInjectedClassName() &&
487         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
488       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
489           << &II << /*Type*/1;
490 
491     DiagnoseUseOfDecl(IIDecl, NameLoc);
492 
493     T = Context.getTypeDeclType(TD);
494     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
495   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
496     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
497     if (!HasTrailingDot)
498       T = Context.getObjCInterfaceType(IDecl);
499     FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
500   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
501     (void)DiagnoseUseOfDecl(UD, NameLoc);
502     // Recover with 'int'
503     T = Context.IntTy;
504     FoundUsingShadow = nullptr;
505   } else if (AllowDeducedTemplate) {
506     if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
507       assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
508       TemplateName Template =
509           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
510       T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
511                                                        false);
512       // Don't wrap in a further UsingType.
513       FoundUsingShadow = nullptr;
514     }
515   }
516 
517   if (T.isNull()) {
518     // If it's not plausibly a type, suppress diagnostics.
519     Result.suppressDiagnostics();
520     return nullptr;
521   }
522 
523   if (FoundUsingShadow)
524     T = Context.getUsingType(FoundUsingShadow, T);
525 
526   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
527   // constructor or destructor name (in such a case, the scope specifier
528   // will be attached to the enclosing Expr or Decl node).
529   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
530       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
531     if (WantNontrivialTypeSourceInfo) {
532       // Construct a type with type-source information.
533       TypeLocBuilder Builder;
534       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
535 
536       T = getElaboratedType(ETK_None, *SS, T);
537       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
538       ElabTL.setElaboratedKeywordLoc(SourceLocation());
539       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
540       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
541     } else {
542       T = getElaboratedType(ETK_None, *SS, T);
543     }
544   }
545 
546   return ParsedType::make(T);
547 }
548 
549 // Builds a fake NNS for the given decl context.
550 static NestedNameSpecifier *
551 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
552   for (;; DC = DC->getLookupParent()) {
553     DC = DC->getPrimaryContext();
554     auto *ND = dyn_cast<NamespaceDecl>(DC);
555     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
556       return NestedNameSpecifier::Create(Context, nullptr, ND);
557     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
558       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
559                                          RD->getTypeForDecl());
560     else if (isa<TranslationUnitDecl>(DC))
561       return NestedNameSpecifier::GlobalSpecifier(Context);
562   }
563   llvm_unreachable("something isn't in TU scope?");
564 }
565 
566 /// Find the parent class with dependent bases of the innermost enclosing method
567 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
568 /// up allowing unqualified dependent type names at class-level, which MSVC
569 /// correctly rejects.
570 static const CXXRecordDecl *
571 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
572   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
573     DC = DC->getPrimaryContext();
574     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
575       if (MD->getParent()->hasAnyDependentBases())
576         return MD->getParent();
577   }
578   return nullptr;
579 }
580 
581 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
582                                           SourceLocation NameLoc,
583                                           bool IsTemplateTypeArg) {
584   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
585 
586   NestedNameSpecifier *NNS = nullptr;
587   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
588     // If we weren't able to parse a default template argument, delay lookup
589     // until instantiation time by making a non-dependent DependentTypeName. We
590     // pretend we saw a NestedNameSpecifier referring to the current scope, and
591     // lookup is retried.
592     // FIXME: This hurts our diagnostic quality, since we get errors like "no
593     // type named 'Foo' in 'current_namespace'" when the user didn't write any
594     // name specifiers.
595     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
596     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
597   } else if (const CXXRecordDecl *RD =
598                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
599     // Build a DependentNameType that will perform lookup into RD at
600     // instantiation time.
601     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
602                                       RD->getTypeForDecl());
603 
604     // Diagnose that this identifier was undeclared, and retry the lookup during
605     // template instantiation.
606     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
607                                                                       << RD;
608   } else {
609     // This is not a situation that we should recover from.
610     return ParsedType();
611   }
612 
613   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
614 
615   // Build type location information.  We synthesized the qualifier, so we have
616   // to build a fake NestedNameSpecifierLoc.
617   NestedNameSpecifierLocBuilder NNSLocBuilder;
618   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
619   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
620 
621   TypeLocBuilder Builder;
622   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
623   DepTL.setNameLoc(NameLoc);
624   DepTL.setElaboratedKeywordLoc(SourceLocation());
625   DepTL.setQualifierLoc(QualifierLoc);
626   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
627 }
628 
629 /// isTagName() - This method is called *for error recovery purposes only*
630 /// to determine if the specified name is a valid tag name ("struct foo").  If
631 /// so, this returns the TST for the tag corresponding to it (TST_enum,
632 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
633 /// cases in C where the user forgot to specify the tag.
634 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
635   // Do a tag name lookup in this scope.
636   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
637   LookupName(R, S, false);
638   R.suppressDiagnostics();
639   if (R.getResultKind() == LookupResult::Found)
640     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
641       switch (TD->getTagKind()) {
642       case TTK_Struct: return DeclSpec::TST_struct;
643       case TTK_Interface: return DeclSpec::TST_interface;
644       case TTK_Union:  return DeclSpec::TST_union;
645       case TTK_Class:  return DeclSpec::TST_class;
646       case TTK_Enum:   return DeclSpec::TST_enum;
647       }
648     }
649 
650   return DeclSpec::TST_unspecified;
651 }
652 
653 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
654 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
655 /// then downgrade the missing typename error to a warning.
656 /// This is needed for MSVC compatibility; Example:
657 /// @code
658 /// template<class T> class A {
659 /// public:
660 ///   typedef int TYPE;
661 /// };
662 /// template<class T> class B : public A<T> {
663 /// public:
664 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
665 /// };
666 /// @endcode
667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
668   if (CurContext->isRecord()) {
669     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
670       return true;
671 
672     const Type *Ty = SS->getScopeRep()->getAsType();
673 
674     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675     for (const auto &Base : RD->bases())
676       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677         return true;
678     return S->isFunctionPrototypeScope();
679   }
680   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
681 }
682 
683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
684                                    SourceLocation IILoc,
685                                    Scope *S,
686                                    CXXScopeSpec *SS,
687                                    ParsedType &SuggestedType,
688                                    bool IsTemplateName) {
689   // Don't report typename errors for editor placeholders.
690   if (II->isEditorPlaceholder())
691     return;
692   // We don't have anything to suggest (yet).
693   SuggestedType = nullptr;
694 
695   // There may have been a typo in the name of the type. Look up typo
696   // results, in case we have something that we can suggest.
697   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698                            /*AllowTemplates=*/IsTemplateName,
699                            /*AllowNonTemplates=*/!IsTemplateName);
700   if (TypoCorrection Corrected =
701           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
702                       CCC, CTK_ErrorRecovery)) {
703     // FIXME: Support error recovery for the template-name case.
704     bool CanRecover = !IsTemplateName;
705     if (Corrected.isKeyword()) {
706       // We corrected to a keyword.
707       diagnoseTypo(Corrected,
708                    PDiag(IsTemplateName ? diag::err_no_template_suggest
709                                         : diag::err_unknown_typename_suggest)
710                        << II);
711       II = Corrected.getCorrectionAsIdentifierInfo();
712     } else {
713       // We found a similarly-named type or interface; suggest that.
714       if (!SS || !SS->isSet()) {
715         diagnoseTypo(Corrected,
716                      PDiag(IsTemplateName ? diag::err_no_template_suggest
717                                           : diag::err_unknown_typename_suggest)
718                          << II, CanRecover);
719       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
722                                 II->getName().equals(CorrectedStr);
723         diagnoseTypo(Corrected,
724                      PDiag(IsTemplateName
725                                ? diag::err_no_member_template_suggest
726                                : diag::err_unknown_nested_typename_suggest)
727                          << II << DC << DroppedSpecifier << SS->getRange(),
728                      CanRecover);
729       } else {
730         llvm_unreachable("could not have corrected a typo here");
731       }
732 
733       if (!CanRecover)
734         return;
735 
736       CXXScopeSpec tmpSS;
737       if (Corrected.getCorrectionSpecifier())
738         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739                           SourceRange(IILoc));
740       // FIXME: Support class template argument deduction here.
741       SuggestedType =
742           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744                       /*IsCtorOrDtorName=*/false,
745                       /*WantNontrivialTypeSourceInfo=*/true);
746     }
747     return;
748   }
749 
750   if (getLangOpts().CPlusPlus && !IsTemplateName) {
751     // See if II is a class template that the user forgot to pass arguments to.
752     UnqualifiedId Name;
753     Name.setIdentifier(II, IILoc);
754     CXXScopeSpec EmptySS;
755     TemplateTy TemplateResult;
756     bool MemberOfUnknownSpecialization;
757     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758                        Name, nullptr, true, TemplateResult,
759                        MemberOfUnknownSpecialization) == TNK_Type_template) {
760       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761       return;
762     }
763   }
764 
765   // FIXME: Should we move the logic that tries to recover from a missing tag
766   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
767 
768   if (!SS || (!SS->isSet() && !SS->isInvalid()))
769     Diag(IILoc, IsTemplateName ? diag::err_no_template
770                                : diag::err_unknown_typename)
771         << II;
772   else if (DeclContext *DC = computeDeclContext(*SS, false))
773     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774                                : diag::err_typename_nested_not_found)
775         << II << DC << SS->getRange();
776   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777     SuggestedType =
778         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779   } else if (isDependentScopeSpecifier(*SS)) {
780     unsigned DiagID = diag::err_typename_missing;
781     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782       DiagID = diag::ext_typename_missing;
783 
784     Diag(SS->getRange().getBegin(), DiagID)
785       << SS->getScopeRep() << II->getName()
786       << SourceRange(SS->getRange().getBegin(), IILoc)
787       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788     SuggestedType = ActOnTypenameType(S, SourceLocation(),
789                                       *SS, *II, IILoc).get();
790   } else {
791     assert(SS && SS->isInvalid() &&
792            "Invalid scope specifier has already been diagnosed");
793   }
794 }
795 
796 /// Determine whether the given result set contains either a type name
797 /// or
798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800                        NextToken.is(tok::less);
801 
802   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804       return true;
805 
806     if (CheckTemplate && isa<TemplateDecl>(*I))
807       return true;
808   }
809 
810   return false;
811 }
812 
813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
814                                     Scope *S, CXXScopeSpec &SS,
815                                     IdentifierInfo *&Name,
816                                     SourceLocation NameLoc) {
817   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818   SemaRef.LookupParsedName(R, S, &SS);
819   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820     StringRef FixItTagName;
821     switch (Tag->getTagKind()) {
822       case TTK_Class:
823         FixItTagName = "class ";
824         break;
825 
826       case TTK_Enum:
827         FixItTagName = "enum ";
828         break;
829 
830       case TTK_Struct:
831         FixItTagName = "struct ";
832         break;
833 
834       case TTK_Interface:
835         FixItTagName = "__interface ";
836         break;
837 
838       case TTK_Union:
839         FixItTagName = "union ";
840         break;
841     }
842 
843     StringRef TagName = FixItTagName.drop_back();
844     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
847 
848     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849          I != IEnd; ++I)
850       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851         << Name << TagName;
852 
853     // Replace lookup results with just the tag decl.
854     Result.clear(Sema::LookupTagName);
855     SemaRef.LookupParsedName(Result, S, &SS);
856     return true;
857   }
858 
859   return false;
860 }
861 
862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
863                                             IdentifierInfo *&Name,
864                                             SourceLocation NameLoc,
865                                             const Token &NextToken,
866                                             CorrectionCandidateCallback *CCC) {
867   DeclarationNameInfo NameInfo(Name, NameLoc);
868   ObjCMethodDecl *CurMethod = getCurMethodDecl();
869 
870   assert(NextToken.isNot(tok::coloncolon) &&
871          "parse nested name specifiers before calling ClassifyName");
872   if (getLangOpts().CPlusPlus && SS.isSet() &&
873       isCurrentClassName(*Name, S, &SS)) {
874     // Per [class.qual]p2, this names the constructors of SS, not the
875     // injected-class-name. We don't have a classification for that.
876     // There's not much point caching this result, since the parser
877     // will reject it later.
878     return NameClassification::Unknown();
879   }
880 
881   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882   LookupParsedName(Result, S, &SS, !CurMethod);
883 
884   if (SS.isInvalid())
885     return NameClassification::Error();
886 
887   // For unqualified lookup in a class template in MSVC mode, look into
888   // dependent base classes where the primary class template is known.
889   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
890     if (ParsedType TypeInBase =
891             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
892       return TypeInBase;
893   }
894 
895   // Perform lookup for Objective-C instance variables (including automatically
896   // synthesized instance variables), if we're in an Objective-C method.
897   // FIXME: This lookup really, really needs to be folded in to the normal
898   // unqualified lookup mechanism.
899   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
900     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
901     if (Ivar.isInvalid())
902       return NameClassification::Error();
903     if (Ivar.isUsable())
904       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
905 
906     // We defer builtin creation until after ivar lookup inside ObjC methods.
907     if (Result.empty())
908       LookupBuiltin(Result);
909   }
910 
911   bool SecondTry = false;
912   bool IsFilteredTemplateName = false;
913 
914 Corrected:
915   switch (Result.getResultKind()) {
916   case LookupResult::NotFound:
917     // If an unqualified-id is followed by a '(', then we have a function
918     // call.
919     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
920       // In C++, this is an ADL-only call.
921       // FIXME: Reference?
922       if (getLangOpts().CPlusPlus)
923         return NameClassification::UndeclaredNonType();
924 
925       // C90 6.3.2.2:
926       //   If the expression that precedes the parenthesized argument list in a
927       //   function call consists solely of an identifier, and if no
928       //   declaration is visible for this identifier, the identifier is
929       //   implicitly declared exactly as if, in the innermost block containing
930       //   the function call, the declaration
931       //
932       //     extern int identifier ();
933       //
934       //   appeared.
935       //
936       // We also allow this in C99 as an extension. However, this is not
937       // allowed in all language modes as functions without prototypes may not
938       // be supported.
939       if (getLangOpts().implicitFunctionsAllowed()) {
940         if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
941           return NameClassification::NonType(D);
942       }
943     }
944 
945     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
946       // In C++20 onwards, this could be an ADL-only call to a function
947       // template, and we're required to assume that this is a template name.
948       //
949       // FIXME: Find a way to still do typo correction in this case.
950       TemplateName Template =
951           Context.getAssumedTemplateName(NameInfo.getName());
952       return NameClassification::UndeclaredTemplate(Template);
953     }
954 
955     // In C, we first see whether there is a tag type by the same name, in
956     // which case it's likely that the user just forgot to write "enum",
957     // "struct", or "union".
958     if (!getLangOpts().CPlusPlus && !SecondTry &&
959         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
960       break;
961     }
962 
963     // Perform typo correction to determine if there is another name that is
964     // close to this name.
965     if (!SecondTry && CCC) {
966       SecondTry = true;
967       if (TypoCorrection Corrected =
968               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
969                           &SS, *CCC, CTK_ErrorRecovery)) {
970         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
971         unsigned QualifiedDiag = diag::err_no_member_suggest;
972 
973         NamedDecl *FirstDecl = Corrected.getFoundDecl();
974         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
975         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
976             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
977           UnqualifiedDiag = diag::err_no_template_suggest;
978           QualifiedDiag = diag::err_no_member_template_suggest;
979         } else if (UnderlyingFirstDecl &&
980                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
981                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
982                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
983           UnqualifiedDiag = diag::err_unknown_typename_suggest;
984           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
985         }
986 
987         if (SS.isEmpty()) {
988           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
989         } else {// FIXME: is this even reachable? Test it.
990           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
991           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
992                                   Name->getName().equals(CorrectedStr);
993           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
994                                     << Name << computeDeclContext(SS, false)
995                                     << DroppedSpecifier << SS.getRange());
996         }
997 
998         // Update the name, so that the caller has the new name.
999         Name = Corrected.getCorrectionAsIdentifierInfo();
1000 
1001         // Typo correction corrected to a keyword.
1002         if (Corrected.isKeyword())
1003           return Name;
1004 
1005         // Also update the LookupResult...
1006         // FIXME: This should probably go away at some point
1007         Result.clear();
1008         Result.setLookupName(Corrected.getCorrection());
1009         if (FirstDecl)
1010           Result.addDecl(FirstDecl);
1011 
1012         // If we found an Objective-C instance variable, let
1013         // LookupInObjCMethod build the appropriate expression to
1014         // reference the ivar.
1015         // FIXME: This is a gross hack.
1016         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1017           DeclResult R =
1018               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1019           if (R.isInvalid())
1020             return NameClassification::Error();
1021           if (R.isUsable())
1022             return NameClassification::NonType(Ivar);
1023         }
1024 
1025         goto Corrected;
1026       }
1027     }
1028 
1029     // We failed to correct; just fall through and let the parser deal with it.
1030     Result.suppressDiagnostics();
1031     return NameClassification::Unknown();
1032 
1033   case LookupResult::NotFoundInCurrentInstantiation: {
1034     // We performed name lookup into the current instantiation, and there were
1035     // dependent bases, so we treat this result the same way as any other
1036     // dependent nested-name-specifier.
1037 
1038     // C++ [temp.res]p2:
1039     //   A name used in a template declaration or definition and that is
1040     //   dependent on a template-parameter is assumed not to name a type
1041     //   unless the applicable name lookup finds a type name or the name is
1042     //   qualified by the keyword typename.
1043     //
1044     // FIXME: If the next token is '<', we might want to ask the parser to
1045     // perform some heroics to see if we actually have a
1046     // template-argument-list, which would indicate a missing 'template'
1047     // keyword here.
1048     return NameClassification::DependentNonType();
1049   }
1050 
1051   case LookupResult::Found:
1052   case LookupResult::FoundOverloaded:
1053   case LookupResult::FoundUnresolvedValue:
1054     break;
1055 
1056   case LookupResult::Ambiguous:
1057     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1058         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1059                                       /*AllowDependent=*/false)) {
1060       // C++ [temp.local]p3:
1061       //   A lookup that finds an injected-class-name (10.2) can result in an
1062       //   ambiguity in certain cases (for example, if it is found in more than
1063       //   one base class). If all of the injected-class-names that are found
1064       //   refer to specializations of the same class template, and if the name
1065       //   is followed by a template-argument-list, the reference refers to the
1066       //   class template itself and not a specialization thereof, and is not
1067       //   ambiguous.
1068       //
1069       // This filtering can make an ambiguous result into an unambiguous one,
1070       // so try again after filtering out template names.
1071       FilterAcceptableTemplateNames(Result);
1072       if (!Result.isAmbiguous()) {
1073         IsFilteredTemplateName = true;
1074         break;
1075       }
1076     }
1077 
1078     // Diagnose the ambiguity and return an error.
1079     return NameClassification::Error();
1080   }
1081 
1082   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1083       (IsFilteredTemplateName ||
1084        hasAnyAcceptableTemplateNames(
1085            Result, /*AllowFunctionTemplates=*/true,
1086            /*AllowDependent=*/false,
1087            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1088                getLangOpts().CPlusPlus20))) {
1089     // C++ [temp.names]p3:
1090     //   After name lookup (3.4) finds that a name is a template-name or that
1091     //   an operator-function-id or a literal- operator-id refers to a set of
1092     //   overloaded functions any member of which is a function template if
1093     //   this is followed by a <, the < is always taken as the delimiter of a
1094     //   template-argument-list and never as the less-than operator.
1095     // C++2a [temp.names]p2:
1096     //   A name is also considered to refer to a template if it is an
1097     //   unqualified-id followed by a < and name lookup finds either one
1098     //   or more functions or finds nothing.
1099     if (!IsFilteredTemplateName)
1100       FilterAcceptableTemplateNames(Result);
1101 
1102     bool IsFunctionTemplate;
1103     bool IsVarTemplate;
1104     TemplateName Template;
1105     if (Result.end() - Result.begin() > 1) {
1106       IsFunctionTemplate = true;
1107       Template = Context.getOverloadedTemplateName(Result.begin(),
1108                                                    Result.end());
1109     } else if (!Result.empty()) {
1110       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1111           *Result.begin(), /*AllowFunctionTemplates=*/true,
1112           /*AllowDependent=*/false));
1113       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1114       IsVarTemplate = isa<VarTemplateDecl>(TD);
1115 
1116       UsingShadowDecl *FoundUsingShadow =
1117           dyn_cast<UsingShadowDecl>(*Result.begin());
1118       assert(!FoundUsingShadow ||
1119              TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1120       Template =
1121           FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1122       if (SS.isNotEmpty())
1123         Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1124                                                     /*TemplateKeyword=*/false,
1125                                                     Template);
1126     } else {
1127       // All results were non-template functions. This is a function template
1128       // name.
1129       IsFunctionTemplate = true;
1130       Template = Context.getAssumedTemplateName(NameInfo.getName());
1131     }
1132 
1133     if (IsFunctionTemplate) {
1134       // Function templates always go through overload resolution, at which
1135       // point we'll perform the various checks (e.g., accessibility) we need
1136       // to based on which function we selected.
1137       Result.suppressDiagnostics();
1138 
1139       return NameClassification::FunctionTemplate(Template);
1140     }
1141 
1142     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1143                          : NameClassification::TypeTemplate(Template);
1144   }
1145 
1146   auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1147     QualType T = Context.getTypeDeclType(Type);
1148     if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1149       T = Context.getUsingType(USD, T);
1150 
1151     if (SS.isEmpty()) // No elaborated type, trivial location info
1152       return ParsedType::make(T);
1153 
1154     TypeLocBuilder Builder;
1155     Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1156     T = getElaboratedType(ETK_None, SS, T);
1157     ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1158     ElabTL.setElaboratedKeywordLoc(SourceLocation());
1159     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1160     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1161   };
1162 
1163   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1164   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1165     DiagnoseUseOfDecl(Type, NameLoc);
1166     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1167     return BuildTypeFor(Type, *Result.begin());
1168   }
1169 
1170   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1171   if (!Class) {
1172     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1173     if (ObjCCompatibleAliasDecl *Alias =
1174             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1175       Class = Alias->getClassInterface();
1176   }
1177 
1178   if (Class) {
1179     DiagnoseUseOfDecl(Class, NameLoc);
1180 
1181     if (NextToken.is(tok::period)) {
1182       // Interface. <something> is parsed as a property reference expression.
1183       // Just return "unknown" as a fall-through for now.
1184       Result.suppressDiagnostics();
1185       return NameClassification::Unknown();
1186     }
1187 
1188     QualType T = Context.getObjCInterfaceType(Class);
1189     return ParsedType::make(T);
1190   }
1191 
1192   if (isa<ConceptDecl>(FirstDecl))
1193     return NameClassification::Concept(
1194         TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1197     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1198     return NameClassification::Error();
1199   }
1200 
1201   // We can have a type template here if we're classifying a template argument.
1202   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1203       !isa<VarTemplateDecl>(FirstDecl))
1204     return NameClassification::TypeTemplate(
1205         TemplateName(cast<TemplateDecl>(FirstDecl)));
1206 
1207   // Check for a tag type hidden by a non-type decl in a few cases where it
1208   // seems likely a type is wanted instead of the non-type that was found.
1209   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1210   if ((NextToken.is(tok::identifier) ||
1211        (NextIsOp &&
1212         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1213       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1214     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1215     DiagnoseUseOfDecl(Type, NameLoc);
1216     return BuildTypeFor(Type, *Result.begin());
1217   }
1218 
1219   // If we already know which single declaration is referenced, just annotate
1220   // that declaration directly. Defer resolving even non-overloaded class
1221   // member accesses, as we need to defer certain access checks until we know
1222   // the context.
1223   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1224   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1225     return NameClassification::NonType(Result.getRepresentativeDecl());
1226 
1227   // Otherwise, this is an overload set that we will need to resolve later.
1228   Result.suppressDiagnostics();
1229   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1230       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1231       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1232       Result.begin(), Result.end()));
1233 }
1234 
1235 ExprResult
1236 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1237                                              SourceLocation NameLoc) {
1238   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1239   CXXScopeSpec SS;
1240   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1241   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1242 }
1243 
1244 ExprResult
1245 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1246                                             IdentifierInfo *Name,
1247                                             SourceLocation NameLoc,
1248                                             bool IsAddressOfOperand) {
1249   DeclarationNameInfo NameInfo(Name, NameLoc);
1250   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1251                                     NameInfo, IsAddressOfOperand,
1252                                     /*TemplateArgs=*/nullptr);
1253 }
1254 
1255 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1256                                               NamedDecl *Found,
1257                                               SourceLocation NameLoc,
1258                                               const Token &NextToken) {
1259   if (getCurMethodDecl() && SS.isEmpty())
1260     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1261       return BuildIvarRefExpr(S, NameLoc, Ivar);
1262 
1263   // Reconstruct the lookup result.
1264   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1265   Result.addDecl(Found);
1266   Result.resolveKind();
1267 
1268   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1269   return BuildDeclarationNameExpr(SS, Result, ADL);
1270 }
1271 
1272 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1273   // For an implicit class member access, transform the result into a member
1274   // access expression if necessary.
1275   auto *ULE = cast<UnresolvedLookupExpr>(E);
1276   if ((*ULE->decls_begin())->isCXXClassMember()) {
1277     CXXScopeSpec SS;
1278     SS.Adopt(ULE->getQualifierLoc());
1279 
1280     // Reconstruct the lookup result.
1281     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1282                         LookupOrdinaryName);
1283     Result.setNamingClass(ULE->getNamingClass());
1284     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1285       Result.addDecl(*I, I.getAccess());
1286     Result.resolveKind();
1287     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1288                                            nullptr, S);
1289   }
1290 
1291   // Otherwise, this is already in the form we needed, and no further checks
1292   // are necessary.
1293   return ULE;
1294 }
1295 
1296 Sema::TemplateNameKindForDiagnostics
1297 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1298   auto *TD = Name.getAsTemplateDecl();
1299   if (!TD)
1300     return TemplateNameKindForDiagnostics::DependentTemplate;
1301   if (isa<ClassTemplateDecl>(TD))
1302     return TemplateNameKindForDiagnostics::ClassTemplate;
1303   if (isa<FunctionTemplateDecl>(TD))
1304     return TemplateNameKindForDiagnostics::FunctionTemplate;
1305   if (isa<VarTemplateDecl>(TD))
1306     return TemplateNameKindForDiagnostics::VarTemplate;
1307   if (isa<TypeAliasTemplateDecl>(TD))
1308     return TemplateNameKindForDiagnostics::AliasTemplate;
1309   if (isa<TemplateTemplateParmDecl>(TD))
1310     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1311   if (isa<ConceptDecl>(TD))
1312     return TemplateNameKindForDiagnostics::Concept;
1313   return TemplateNameKindForDiagnostics::DependentTemplate;
1314 }
1315 
1316 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1317   assert(DC->getLexicalParent() == CurContext &&
1318       "The next DeclContext should be lexically contained in the current one.");
1319   CurContext = DC;
1320   S->setEntity(DC);
1321 }
1322 
1323 void Sema::PopDeclContext() {
1324   assert(CurContext && "DeclContext imbalance!");
1325 
1326   CurContext = CurContext->getLexicalParent();
1327   assert(CurContext && "Popped translation unit!");
1328 }
1329 
1330 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1331                                                                     Decl *D) {
1332   // Unlike PushDeclContext, the context to which we return is not necessarily
1333   // the containing DC of TD, because the new context will be some pre-existing
1334   // TagDecl definition instead of a fresh one.
1335   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1336   CurContext = cast<TagDecl>(D)->getDefinition();
1337   assert(CurContext && "skipping definition of undefined tag");
1338   // Start lookups from the parent of the current context; we don't want to look
1339   // into the pre-existing complete definition.
1340   S->setEntity(CurContext->getLookupParent());
1341   return Result;
1342 }
1343 
1344 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1345   CurContext = static_cast<decltype(CurContext)>(Context);
1346 }
1347 
1348 /// EnterDeclaratorContext - Used when we must lookup names in the context
1349 /// of a declarator's nested name specifier.
1350 ///
1351 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1352   // C++0x [basic.lookup.unqual]p13:
1353   //   A name used in the definition of a static data member of class
1354   //   X (after the qualified-id of the static member) is looked up as
1355   //   if the name was used in a member function of X.
1356   // C++0x [basic.lookup.unqual]p14:
1357   //   If a variable member of a namespace is defined outside of the
1358   //   scope of its namespace then any name used in the definition of
1359   //   the variable member (after the declarator-id) is looked up as
1360   //   if the definition of the variable member occurred in its
1361   //   namespace.
1362   // Both of these imply that we should push a scope whose context
1363   // is the semantic context of the declaration.  We can't use
1364   // PushDeclContext here because that context is not necessarily
1365   // lexically contained in the current context.  Fortunately,
1366   // the containing scope should have the appropriate information.
1367 
1368   assert(!S->getEntity() && "scope already has entity");
1369 
1370 #ifndef NDEBUG
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1374 #endif
1375 
1376   CurContext = DC;
1377   S->setEntity(DC);
1378 
1379   if (S->getParent()->isTemplateParamScope()) {
1380     // Also set the corresponding entities for all immediately-enclosing
1381     // template parameter scopes.
1382     EnterTemplatedContext(S->getParent(), DC);
1383   }
1384 }
1385 
1386 void Sema::ExitDeclaratorContext(Scope *S) {
1387   assert(S->getEntity() == CurContext && "Context imbalance!");
1388 
1389   // Switch back to the lexical context.  The safety of this is
1390   // enforced by an assert in EnterDeclaratorContext.
1391   Scope *Ancestor = S->getParent();
1392   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1393   CurContext = Ancestor->getEntity();
1394 
1395   // We don't need to do anything with the scope, which is going to
1396   // disappear.
1397 }
1398 
1399 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1400   assert(S->isTemplateParamScope() &&
1401          "expected to be initializing a template parameter scope");
1402 
1403   // C++20 [temp.local]p7:
1404   //   In the definition of a member of a class template that appears outside
1405   //   of the class template definition, the name of a member of the class
1406   //   template hides the name of a template-parameter of any enclosing class
1407   //   templates (but not a template-parameter of the member if the member is a
1408   //   class or function template).
1409   // C++20 [temp.local]p9:
1410   //   In the definition of a class template or in the definition of a member
1411   //   of such a template that appears outside of the template definition, for
1412   //   each non-dependent base class (13.8.2.1), if the name of the base class
1413   //   or the name of a member of the base class is the same as the name of a
1414   //   template-parameter, the base class name or member name hides the
1415   //   template-parameter name (6.4.10).
1416   //
1417   // This means that a template parameter scope should be searched immediately
1418   // after searching the DeclContext for which it is a template parameter
1419   // scope. For example, for
1420   //   template<typename T> template<typename U> template<typename V>
1421   //     void N::A<T>::B<U>::f(...)
1422   // we search V then B<U> (and base classes) then U then A<T> (and base
1423   // classes) then T then N then ::.
1424   unsigned ScopeDepth = getTemplateDepth(S);
1425   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1426     DeclContext *SearchDCAfterScope = DC;
1427     for (; DC; DC = DC->getLookupParent()) {
1428       if (const TemplateParameterList *TPL =
1429               cast<Decl>(DC)->getDescribedTemplateParams()) {
1430         unsigned DCDepth = TPL->getDepth() + 1;
1431         if (DCDepth > ScopeDepth)
1432           continue;
1433         if (ScopeDepth == DCDepth)
1434           SearchDCAfterScope = DC = DC->getLookupParent();
1435         break;
1436       }
1437     }
1438     S->setLookupEntity(SearchDCAfterScope);
1439   }
1440 }
1441 
1442 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1443   // We assume that the caller has already called
1444   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1445   FunctionDecl *FD = D->getAsFunction();
1446   if (!FD)
1447     return;
1448 
1449   // Same implementation as PushDeclContext, but enters the context
1450   // from the lexical parent, rather than the top-level class.
1451   assert(CurContext == FD->getLexicalParent() &&
1452     "The next DeclContext should be lexically contained in the current one.");
1453   CurContext = FD;
1454   S->setEntity(CurContext);
1455 
1456   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1457     ParmVarDecl *Param = FD->getParamDecl(P);
1458     // If the parameter has an identifier, then add it to the scope
1459     if (Param->getIdentifier()) {
1460       S->AddDecl(Param);
1461       IdResolver.AddDecl(Param);
1462     }
1463   }
1464 }
1465 
1466 void Sema::ActOnExitFunctionContext() {
1467   // Same implementation as PopDeclContext, but returns to the lexical parent,
1468   // rather than the top-level class.
1469   assert(CurContext && "DeclContext imbalance!");
1470   CurContext = CurContext->getLexicalParent();
1471   assert(CurContext && "Popped translation unit!");
1472 }
1473 
1474 /// Determine whether overloading is allowed for a new function
1475 /// declaration considering prior declarations of the same name.
1476 ///
1477 /// This routine determines whether overloading is possible, not
1478 /// whether a new declaration actually overloads a previous one.
1479 /// It will return true in C++ (where overloads are alway permitted)
1480 /// or, as a C extension, when either the new declaration or a
1481 /// previous one is declared with the 'overloadable' attribute.
1482 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1483                                        ASTContext &Context,
1484                                        const FunctionDecl *New) {
1485   if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1486     return true;
1487 
1488   // Multiversion function declarations are not overloads in the
1489   // usual sense of that term, but lookup will report that an
1490   // overload set was found if more than one multiversion function
1491   // declaration is present for the same name. It is therefore
1492   // inadequate to assume that some prior declaration(s) had
1493   // the overloadable attribute; checking is required. Since one
1494   // declaration is permitted to omit the attribute, it is necessary
1495   // to check at least two; hence the 'any_of' check below. Note that
1496   // the overloadable attribute is implicitly added to declarations
1497   // that were required to have it but did not.
1498   if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1499     return llvm::any_of(Previous, [](const NamedDecl *ND) {
1500       return ND->hasAttr<OverloadableAttr>();
1501     });
1502   } else if (Previous.getResultKind() == LookupResult::Found)
1503     return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1504 
1505   return false;
1506 }
1507 
1508 /// Add this decl to the scope shadowed decl chains.
1509 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1510   // Move up the scope chain until we find the nearest enclosing
1511   // non-transparent context. The declaration will be introduced into this
1512   // scope.
1513   while (S->getEntity() && S->getEntity()->isTransparentContext())
1514     S = S->getParent();
1515 
1516   // Add scoped declarations into their context, so that they can be
1517   // found later. Declarations without a context won't be inserted
1518   // into any context.
1519   if (AddToContext)
1520     CurContext->addDecl(D);
1521 
1522   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1523   // are function-local declarations.
1524   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1525     return;
1526 
1527   // Template instantiations should also not be pushed into scope.
1528   if (isa<FunctionDecl>(D) &&
1529       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1530     return;
1531 
1532   // If this replaces anything in the current scope,
1533   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1534                                IEnd = IdResolver.end();
1535   for (; I != IEnd; ++I) {
1536     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1537       S->RemoveDecl(*I);
1538       IdResolver.RemoveDecl(*I);
1539 
1540       // Should only need to replace one decl.
1541       break;
1542     }
1543   }
1544 
1545   S->AddDecl(D);
1546 
1547   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1548     // Implicitly-generated labels may end up getting generated in an order that
1549     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1550     // the label at the appropriate place in the identifier chain.
1551     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1552       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1553       if (IDC == CurContext) {
1554         if (!S->isDeclScope(*I))
1555           continue;
1556       } else if (IDC->Encloses(CurContext))
1557         break;
1558     }
1559 
1560     IdResolver.InsertDeclAfter(I, D);
1561   } else {
1562     IdResolver.AddDecl(D);
1563   }
1564   warnOnReservedIdentifier(D);
1565 }
1566 
1567 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1568                          bool AllowInlineNamespace) {
1569   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1570 }
1571 
1572 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1573   DeclContext *TargetDC = DC->getPrimaryContext();
1574   do {
1575     if (DeclContext *ScopeDC = S->getEntity())
1576       if (ScopeDC->getPrimaryContext() == TargetDC)
1577         return S;
1578   } while ((S = S->getParent()));
1579 
1580   return nullptr;
1581 }
1582 
1583 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1584                                             DeclContext*,
1585                                             ASTContext&);
1586 
1587 /// Filters out lookup results that don't fall within the given scope
1588 /// as determined by isDeclInScope.
1589 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1590                                 bool ConsiderLinkage,
1591                                 bool AllowInlineNamespace) {
1592   LookupResult::Filter F = R.makeFilter();
1593   while (F.hasNext()) {
1594     NamedDecl *D = F.next();
1595 
1596     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1597       continue;
1598 
1599     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1600       continue;
1601 
1602     F.erase();
1603   }
1604 
1605   F.done();
1606 }
1607 
1608 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1609 /// have compatible owning modules.
1610 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1611   // [module.interface]p7:
1612   // A declaration is attached to a module as follows:
1613   // - If the declaration is a non-dependent friend declaration that nominates a
1614   // function with a declarator-id that is a qualified-id or template-id or that
1615   // nominates a class other than with an elaborated-type-specifier with neither
1616   // a nested-name-specifier nor a simple-template-id, it is attached to the
1617   // module to which the friend is attached ([basic.link]).
1618   if (New->getFriendObjectKind() &&
1619       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1620     New->setLocalOwningModule(Old->getOwningModule());
1621     makeMergedDefinitionVisible(New);
1622     return false;
1623   }
1624 
1625   Module *NewM = New->getOwningModule();
1626   Module *OldM = Old->getOwningModule();
1627 
1628   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1629     NewM = NewM->Parent;
1630   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1631     OldM = OldM->Parent;
1632 
1633   // If we have a decl in a module partition, it is part of the containing
1634   // module (which is the only thing that can be importing it).
1635   if (NewM && OldM &&
1636       (OldM->Kind == Module::ModulePartitionInterface ||
1637        OldM->Kind == Module::ModulePartitionImplementation)) {
1638     return false;
1639   }
1640 
1641   if (NewM == OldM)
1642     return false;
1643 
1644   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1645   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1646   if (NewIsModuleInterface || OldIsModuleInterface) {
1647     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1648     //   if a declaration of D [...] appears in the purview of a module, all
1649     //   other such declarations shall appear in the purview of the same module
1650     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1651       << New
1652       << NewIsModuleInterface
1653       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1654       << OldIsModuleInterface
1655       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1656     Diag(Old->getLocation(), diag::note_previous_declaration);
1657     New->setInvalidDecl();
1658     return true;
1659   }
1660 
1661   return false;
1662 }
1663 
1664 // [module.interface]p6:
1665 // A redeclaration of an entity X is implicitly exported if X was introduced by
1666 // an exported declaration; otherwise it shall not be exported.
1667 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1668   // [module.interface]p1:
1669   // An export-declaration shall inhabit a namespace scope.
1670   //
1671   // So it is meaningless to talk about redeclaration which is not at namespace
1672   // scope.
1673   if (!New->getLexicalDeclContext()
1674            ->getNonTransparentContext()
1675            ->isFileContext() ||
1676       !Old->getLexicalDeclContext()
1677            ->getNonTransparentContext()
1678            ->isFileContext())
1679     return false;
1680 
1681   bool IsNewExported = New->isInExportDeclContext();
1682   bool IsOldExported = Old->isInExportDeclContext();
1683 
1684   // It should be irrevelant if both of them are not exported.
1685   if (!IsNewExported && !IsOldExported)
1686     return false;
1687 
1688   if (IsOldExported)
1689     return false;
1690 
1691   assert(IsNewExported);
1692 
1693   auto Lk = Old->getFormalLinkage();
1694   int S = 0;
1695   if (Lk == Linkage::InternalLinkage)
1696     S = 1;
1697   else if (Lk == Linkage::ModuleLinkage)
1698     S = 2;
1699   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1700   Diag(Old->getLocation(), diag::note_previous_declaration);
1701   return true;
1702 }
1703 
1704 // A wrapper function for checking the semantic restrictions of
1705 // a redeclaration within a module.
1706 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1707   if (CheckRedeclarationModuleOwnership(New, Old))
1708     return true;
1709 
1710   if (CheckRedeclarationExported(New, Old))
1711     return true;
1712 
1713   return false;
1714 }
1715 
1716 static bool isUsingDecl(NamedDecl *D) {
1717   return isa<UsingShadowDecl>(D) ||
1718          isa<UnresolvedUsingTypenameDecl>(D) ||
1719          isa<UnresolvedUsingValueDecl>(D);
1720 }
1721 
1722 /// Removes using shadow declarations from the lookup results.
1723 static void RemoveUsingDecls(LookupResult &R) {
1724   LookupResult::Filter F = R.makeFilter();
1725   while (F.hasNext())
1726     if (isUsingDecl(F.next()))
1727       F.erase();
1728 
1729   F.done();
1730 }
1731 
1732 /// Check for this common pattern:
1733 /// @code
1734 /// class S {
1735 ///   S(const S&); // DO NOT IMPLEMENT
1736 ///   void operator=(const S&); // DO NOT IMPLEMENT
1737 /// };
1738 /// @endcode
1739 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1740   // FIXME: Should check for private access too but access is set after we get
1741   // the decl here.
1742   if (D->doesThisDeclarationHaveABody())
1743     return false;
1744 
1745   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1746     return CD->isCopyConstructor();
1747   return D->isCopyAssignmentOperator();
1748 }
1749 
1750 // We need this to handle
1751 //
1752 // typedef struct {
1753 //   void *foo() { return 0; }
1754 // } A;
1755 //
1756 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1757 // for example. If 'A', foo will have external linkage. If we have '*A',
1758 // foo will have no linkage. Since we can't know until we get to the end
1759 // of the typedef, this function finds out if D might have non-external linkage.
1760 // Callers should verify at the end of the TU if it D has external linkage or
1761 // not.
1762 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1763   const DeclContext *DC = D->getDeclContext();
1764   while (!DC->isTranslationUnit()) {
1765     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1766       if (!RD->hasNameForLinkage())
1767         return true;
1768     }
1769     DC = DC->getParent();
1770   }
1771 
1772   return !D->isExternallyVisible();
1773 }
1774 
1775 // FIXME: This needs to be refactored; some other isInMainFile users want
1776 // these semantics.
1777 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1778   if (S.TUKind != TU_Complete)
1779     return false;
1780   return S.SourceMgr.isInMainFile(Loc);
1781 }
1782 
1783 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1784   assert(D);
1785 
1786   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1787     return false;
1788 
1789   // Ignore all entities declared within templates, and out-of-line definitions
1790   // of members of class templates.
1791   if (D->getDeclContext()->isDependentContext() ||
1792       D->getLexicalDeclContext()->isDependentContext())
1793     return false;
1794 
1795   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1796     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1797       return false;
1798     // A non-out-of-line declaration of a member specialization was implicitly
1799     // instantiated; it's the out-of-line declaration that we're interested in.
1800     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1801         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1802       return false;
1803 
1804     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1805       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1806         return false;
1807     } else {
1808       // 'static inline' functions are defined in headers; don't warn.
1809       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1810         return false;
1811     }
1812 
1813     if (FD->doesThisDeclarationHaveABody() &&
1814         Context.DeclMustBeEmitted(FD))
1815       return false;
1816   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1817     // Constants and utility variables are defined in headers with internal
1818     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1819     // like "inline".)
1820     if (!isMainFileLoc(*this, VD->getLocation()))
1821       return false;
1822 
1823     if (Context.DeclMustBeEmitted(VD))
1824       return false;
1825 
1826     if (VD->isStaticDataMember() &&
1827         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1828       return false;
1829     if (VD->isStaticDataMember() &&
1830         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1831         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1832       return false;
1833 
1834     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1835       return false;
1836   } else {
1837     return false;
1838   }
1839 
1840   // Only warn for unused decls internal to the translation unit.
1841   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1842   // for inline functions defined in the main source file, for instance.
1843   return mightHaveNonExternalLinkage(D);
1844 }
1845 
1846 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1847   if (!D)
1848     return;
1849 
1850   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1851     const FunctionDecl *First = FD->getFirstDecl();
1852     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1853       return; // First should already be in the vector.
1854   }
1855 
1856   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1857     const VarDecl *First = VD->getFirstDecl();
1858     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1859       return; // First should already be in the vector.
1860   }
1861 
1862   if (ShouldWarnIfUnusedFileScopedDecl(D))
1863     UnusedFileScopedDecls.push_back(D);
1864 }
1865 
1866 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1867   if (D->isInvalidDecl())
1868     return false;
1869 
1870   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1871     // For a decomposition declaration, warn if none of the bindings are
1872     // referenced, instead of if the variable itself is referenced (which
1873     // it is, by the bindings' expressions).
1874     for (auto *BD : DD->bindings())
1875       if (BD->isReferenced())
1876         return false;
1877   } else if (!D->getDeclName()) {
1878     return false;
1879   } else if (D->isReferenced() || D->isUsed()) {
1880     return false;
1881   }
1882 
1883   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1884     return false;
1885 
1886   if (isa<LabelDecl>(D))
1887     return true;
1888 
1889   // Except for labels, we only care about unused decls that are local to
1890   // functions.
1891   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1892   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1893     // For dependent types, the diagnostic is deferred.
1894     WithinFunction =
1895         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1896   if (!WithinFunction)
1897     return false;
1898 
1899   if (isa<TypedefNameDecl>(D))
1900     return true;
1901 
1902   // White-list anything that isn't a local variable.
1903   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1904     return false;
1905 
1906   // Types of valid local variables should be complete, so this should succeed.
1907   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1908 
1909     const Expr *Init = VD->getInit();
1910     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1911       Init = Cleanups->getSubExpr();
1912 
1913     const auto *Ty = VD->getType().getTypePtr();
1914 
1915     // Only look at the outermost level of typedef.
1916     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1917       // Allow anything marked with __attribute__((unused)).
1918       if (TT->getDecl()->hasAttr<UnusedAttr>())
1919         return false;
1920     }
1921 
1922     // Warn for reference variables whose initializtion performs lifetime
1923     // extension.
1924     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1925       if (MTE->getExtendingDecl()) {
1926         Ty = VD->getType().getNonReferenceType().getTypePtr();
1927         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1928       }
1929     }
1930 
1931     // If we failed to complete the type for some reason, or if the type is
1932     // dependent, don't diagnose the variable.
1933     if (Ty->isIncompleteType() || Ty->isDependentType())
1934       return false;
1935 
1936     // Look at the element type to ensure that the warning behaviour is
1937     // consistent for both scalars and arrays.
1938     Ty = Ty->getBaseElementTypeUnsafe();
1939 
1940     if (const TagType *TT = Ty->getAs<TagType>()) {
1941       const TagDecl *Tag = TT->getDecl();
1942       if (Tag->hasAttr<UnusedAttr>())
1943         return false;
1944 
1945       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1946         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1947           return false;
1948 
1949         if (Init) {
1950           const CXXConstructExpr *Construct =
1951             dyn_cast<CXXConstructExpr>(Init);
1952           if (Construct && !Construct->isElidable()) {
1953             CXXConstructorDecl *CD = Construct->getConstructor();
1954             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1955                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1956               return false;
1957           }
1958 
1959           // Suppress the warning if we don't know how this is constructed, and
1960           // it could possibly be non-trivial constructor.
1961           if (Init->isTypeDependent()) {
1962             for (const CXXConstructorDecl *Ctor : RD->ctors())
1963               if (!Ctor->isTrivial())
1964                 return false;
1965           }
1966 
1967           // Suppress the warning if the constructor is unresolved because
1968           // its arguments are dependent.
1969           if (isa<CXXUnresolvedConstructExpr>(Init))
1970             return false;
1971         }
1972       }
1973     }
1974 
1975     // TODO: __attribute__((unused)) templates?
1976   }
1977 
1978   return true;
1979 }
1980 
1981 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1982                                      FixItHint &Hint) {
1983   if (isa<LabelDecl>(D)) {
1984     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1985         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1986         true);
1987     if (AfterColon.isInvalid())
1988       return;
1989     Hint = FixItHint::CreateRemoval(
1990         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1991   }
1992 }
1993 
1994 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1995   if (D->getTypeForDecl()->isDependentType())
1996     return;
1997 
1998   for (auto *TmpD : D->decls()) {
1999     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2000       DiagnoseUnusedDecl(T);
2001     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2002       DiagnoseUnusedNestedTypedefs(R);
2003   }
2004 }
2005 
2006 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2007 /// unless they are marked attr(unused).
2008 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2009   if (!ShouldDiagnoseUnusedDecl(D))
2010     return;
2011 
2012   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2013     // typedefs can be referenced later on, so the diagnostics are emitted
2014     // at end-of-translation-unit.
2015     UnusedLocalTypedefNameCandidates.insert(TD);
2016     return;
2017   }
2018 
2019   FixItHint Hint;
2020   GenerateFixForUnusedDecl(D, Context, Hint);
2021 
2022   unsigned DiagID;
2023   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2024     DiagID = diag::warn_unused_exception_param;
2025   else if (isa<LabelDecl>(D))
2026     DiagID = diag::warn_unused_label;
2027   else
2028     DiagID = diag::warn_unused_variable;
2029 
2030   Diag(D->getLocation(), DiagID) << D << Hint;
2031 }
2032 
2033 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2034   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2035   // it's not really unused.
2036   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2037       VD->hasAttr<CleanupAttr>())
2038     return;
2039 
2040   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2041 
2042   if (Ty->isReferenceType() || Ty->isDependentType())
2043     return;
2044 
2045   if (const TagType *TT = Ty->getAs<TagType>()) {
2046     const TagDecl *Tag = TT->getDecl();
2047     if (Tag->hasAttr<UnusedAttr>())
2048       return;
2049     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2050     // mimic gcc's behavior.
2051     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2052       if (!RD->hasAttr<WarnUnusedAttr>())
2053         return;
2054     }
2055   }
2056 
2057   // Don't warn about __block Objective-C pointer variables, as they might
2058   // be assigned in the block but not used elsewhere for the purpose of lifetime
2059   // extension.
2060   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2061     return;
2062 
2063   // Don't warn about Objective-C pointer variables with precise lifetime
2064   // semantics; they can be used to ensure ARC releases the object at a known
2065   // time, which may mean assignment but no other references.
2066   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2067     return;
2068 
2069   auto iter = RefsMinusAssignments.find(VD);
2070   if (iter == RefsMinusAssignments.end())
2071     return;
2072 
2073   assert(iter->getSecond() >= 0 &&
2074          "Found a negative number of references to a VarDecl");
2075   if (iter->getSecond() != 0)
2076     return;
2077   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2078                                          : diag::warn_unused_but_set_variable;
2079   Diag(VD->getLocation(), DiagID) << VD;
2080 }
2081 
2082 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2083   // Verify that we have no forward references left.  If so, there was a goto
2084   // or address of a label taken, but no definition of it.  Label fwd
2085   // definitions are indicated with a null substmt which is also not a resolved
2086   // MS inline assembly label name.
2087   bool Diagnose = false;
2088   if (L->isMSAsmLabel())
2089     Diagnose = !L->isResolvedMSAsmLabel();
2090   else
2091     Diagnose = L->getStmt() == nullptr;
2092   if (Diagnose)
2093     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2094 }
2095 
2096 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2097   S->mergeNRVOIntoParent();
2098 
2099   if (S->decl_empty()) return;
2100   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2101          "Scope shouldn't contain decls!");
2102 
2103   for (auto *TmpD : S->decls()) {
2104     assert(TmpD && "This decl didn't get pushed??");
2105 
2106     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2107     NamedDecl *D = cast<NamedDecl>(TmpD);
2108 
2109     // Diagnose unused variables in this scope.
2110     if (!S->hasUnrecoverableErrorOccurred()) {
2111       DiagnoseUnusedDecl(D);
2112       if (const auto *RD = dyn_cast<RecordDecl>(D))
2113         DiagnoseUnusedNestedTypedefs(RD);
2114       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2115         DiagnoseUnusedButSetDecl(VD);
2116         RefsMinusAssignments.erase(VD);
2117       }
2118     }
2119 
2120     if (!D->getDeclName()) continue;
2121 
2122     // If this was a forward reference to a label, verify it was defined.
2123     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2124       CheckPoppedLabel(LD, *this);
2125 
2126     // Remove this name from our lexical scope, and warn on it if we haven't
2127     // already.
2128     IdResolver.RemoveDecl(D);
2129     auto ShadowI = ShadowingDecls.find(D);
2130     if (ShadowI != ShadowingDecls.end()) {
2131       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2132         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2133             << D << FD << FD->getParent();
2134         Diag(FD->getLocation(), diag::note_previous_declaration);
2135       }
2136       ShadowingDecls.erase(ShadowI);
2137     }
2138   }
2139 }
2140 
2141 /// Look for an Objective-C class in the translation unit.
2142 ///
2143 /// \param Id The name of the Objective-C class we're looking for. If
2144 /// typo-correction fixes this name, the Id will be updated
2145 /// to the fixed name.
2146 ///
2147 /// \param IdLoc The location of the name in the translation unit.
2148 ///
2149 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2150 /// if there is no class with the given name.
2151 ///
2152 /// \returns The declaration of the named Objective-C class, or NULL if the
2153 /// class could not be found.
2154 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2155                                               SourceLocation IdLoc,
2156                                               bool DoTypoCorrection) {
2157   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2158   // creation from this context.
2159   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2160 
2161   if (!IDecl && DoTypoCorrection) {
2162     // Perform typo correction at the given location, but only if we
2163     // find an Objective-C class name.
2164     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2165     if (TypoCorrection C =
2166             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2167                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2168       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2169       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2170       Id = IDecl->getIdentifier();
2171     }
2172   }
2173   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2174   // This routine must always return a class definition, if any.
2175   if (Def && Def->getDefinition())
2176       Def = Def->getDefinition();
2177   return Def;
2178 }
2179 
2180 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2181 /// from S, where a non-field would be declared. This routine copes
2182 /// with the difference between C and C++ scoping rules in structs and
2183 /// unions. For example, the following code is well-formed in C but
2184 /// ill-formed in C++:
2185 /// @code
2186 /// struct S6 {
2187 ///   enum { BAR } e;
2188 /// };
2189 ///
2190 /// void test_S6() {
2191 ///   struct S6 a;
2192 ///   a.e = BAR;
2193 /// }
2194 /// @endcode
2195 /// For the declaration of BAR, this routine will return a different
2196 /// scope. The scope S will be the scope of the unnamed enumeration
2197 /// within S6. In C++, this routine will return the scope associated
2198 /// with S6, because the enumeration's scope is a transparent
2199 /// context but structures can contain non-field names. In C, this
2200 /// routine will return the translation unit scope, since the
2201 /// enumeration's scope is a transparent context and structures cannot
2202 /// contain non-field names.
2203 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2204   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2205          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2206          (S->isClassScope() && !getLangOpts().CPlusPlus))
2207     S = S->getParent();
2208   return S;
2209 }
2210 
2211 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2212                                ASTContext::GetBuiltinTypeError Error) {
2213   switch (Error) {
2214   case ASTContext::GE_None:
2215     return "";
2216   case ASTContext::GE_Missing_type:
2217     return BuiltinInfo.getHeaderName(ID);
2218   case ASTContext::GE_Missing_stdio:
2219     return "stdio.h";
2220   case ASTContext::GE_Missing_setjmp:
2221     return "setjmp.h";
2222   case ASTContext::GE_Missing_ucontext:
2223     return "ucontext.h";
2224   }
2225   llvm_unreachable("unhandled error kind");
2226 }
2227 
2228 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2229                                   unsigned ID, SourceLocation Loc) {
2230   DeclContext *Parent = Context.getTranslationUnitDecl();
2231 
2232   if (getLangOpts().CPlusPlus) {
2233     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2234         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2235     CLinkageDecl->setImplicit();
2236     Parent->addDecl(CLinkageDecl);
2237     Parent = CLinkageDecl;
2238   }
2239 
2240   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2241                                            /*TInfo=*/nullptr, SC_Extern,
2242                                            getCurFPFeatures().isFPConstrained(),
2243                                            false, Type->isFunctionProtoType());
2244   New->setImplicit();
2245   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2246 
2247   // Create Decl objects for each parameter, adding them to the
2248   // FunctionDecl.
2249   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2250     SmallVector<ParmVarDecl *, 16> Params;
2251     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2252       ParmVarDecl *parm = ParmVarDecl::Create(
2253           Context, New, SourceLocation(), SourceLocation(), nullptr,
2254           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2255       parm->setScopeInfo(0, i);
2256       Params.push_back(parm);
2257     }
2258     New->setParams(Params);
2259   }
2260 
2261   AddKnownFunctionAttributes(New);
2262   return New;
2263 }
2264 
2265 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2266 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2267 /// if we're creating this built-in in anticipation of redeclaring the
2268 /// built-in.
2269 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2270                                      Scope *S, bool ForRedeclaration,
2271                                      SourceLocation Loc) {
2272   LookupNecessaryTypesForBuiltin(S, ID);
2273 
2274   ASTContext::GetBuiltinTypeError Error;
2275   QualType R = Context.GetBuiltinType(ID, Error);
2276   if (Error) {
2277     if (!ForRedeclaration)
2278       return nullptr;
2279 
2280     // If we have a builtin without an associated type we should not emit a
2281     // warning when we were not able to find a type for it.
2282     if (Error == ASTContext::GE_Missing_type ||
2283         Context.BuiltinInfo.allowTypeMismatch(ID))
2284       return nullptr;
2285 
2286     // If we could not find a type for setjmp it is because the jmp_buf type was
2287     // not defined prior to the setjmp declaration.
2288     if (Error == ASTContext::GE_Missing_setjmp) {
2289       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2290           << Context.BuiltinInfo.getName(ID);
2291       return nullptr;
2292     }
2293 
2294     // Generally, we emit a warning that the declaration requires the
2295     // appropriate header.
2296     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2297         << getHeaderName(Context.BuiltinInfo, ID, Error)
2298         << Context.BuiltinInfo.getName(ID);
2299     return nullptr;
2300   }
2301 
2302   if (!ForRedeclaration &&
2303       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2304        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2305     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2306                            : diag::ext_implicit_lib_function_decl)
2307         << Context.BuiltinInfo.getName(ID) << R;
2308     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2309       Diag(Loc, diag::note_include_header_or_declare)
2310           << Header << Context.BuiltinInfo.getName(ID);
2311   }
2312 
2313   if (R.isNull())
2314     return nullptr;
2315 
2316   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2317   RegisterLocallyScopedExternCDecl(New, S);
2318 
2319   // TUScope is the translation-unit scope to insert this function into.
2320   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2321   // relate Scopes to DeclContexts, and probably eliminate CurContext
2322   // entirely, but we're not there yet.
2323   DeclContext *SavedContext = CurContext;
2324   CurContext = New->getDeclContext();
2325   PushOnScopeChains(New, TUScope);
2326   CurContext = SavedContext;
2327   return New;
2328 }
2329 
2330 /// Typedef declarations don't have linkage, but they still denote the same
2331 /// entity if their types are the same.
2332 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2333 /// isSameEntity.
2334 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2335                                                      TypedefNameDecl *Decl,
2336                                                      LookupResult &Previous) {
2337   // This is only interesting when modules are enabled.
2338   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2339     return;
2340 
2341   // Empty sets are uninteresting.
2342   if (Previous.empty())
2343     return;
2344 
2345   LookupResult::Filter Filter = Previous.makeFilter();
2346   while (Filter.hasNext()) {
2347     NamedDecl *Old = Filter.next();
2348 
2349     // Non-hidden declarations are never ignored.
2350     if (S.isVisible(Old))
2351       continue;
2352 
2353     // Declarations of the same entity are not ignored, even if they have
2354     // different linkages.
2355     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2356       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2357                                 Decl->getUnderlyingType()))
2358         continue;
2359 
2360       // If both declarations give a tag declaration a typedef name for linkage
2361       // purposes, then they declare the same entity.
2362       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2363           Decl->getAnonDeclWithTypedefName())
2364         continue;
2365     }
2366 
2367     Filter.erase();
2368   }
2369 
2370   Filter.done();
2371 }
2372 
2373 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2374   QualType OldType;
2375   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2376     OldType = OldTypedef->getUnderlyingType();
2377   else
2378     OldType = Context.getTypeDeclType(Old);
2379   QualType NewType = New->getUnderlyingType();
2380 
2381   if (NewType->isVariablyModifiedType()) {
2382     // Must not redefine a typedef with a variably-modified type.
2383     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2384     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2385       << Kind << NewType;
2386     if (Old->getLocation().isValid())
2387       notePreviousDefinition(Old, New->getLocation());
2388     New->setInvalidDecl();
2389     return true;
2390   }
2391 
2392   if (OldType != NewType &&
2393       !OldType->isDependentType() &&
2394       !NewType->isDependentType() &&
2395       !Context.hasSameType(OldType, NewType)) {
2396     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2397     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2398       << Kind << NewType << OldType;
2399     if (Old->getLocation().isValid())
2400       notePreviousDefinition(Old, New->getLocation());
2401     New->setInvalidDecl();
2402     return true;
2403   }
2404   return false;
2405 }
2406 
2407 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2408 /// same name and scope as a previous declaration 'Old'.  Figure out
2409 /// how to resolve this situation, merging decls or emitting
2410 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2411 ///
2412 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2413                                 LookupResult &OldDecls) {
2414   // If the new decl is known invalid already, don't bother doing any
2415   // merging checks.
2416   if (New->isInvalidDecl()) return;
2417 
2418   // Allow multiple definitions for ObjC built-in typedefs.
2419   // FIXME: Verify the underlying types are equivalent!
2420   if (getLangOpts().ObjC) {
2421     const IdentifierInfo *TypeID = New->getIdentifier();
2422     switch (TypeID->getLength()) {
2423     default: break;
2424     case 2:
2425       {
2426         if (!TypeID->isStr("id"))
2427           break;
2428         QualType T = New->getUnderlyingType();
2429         if (!T->isPointerType())
2430           break;
2431         if (!T->isVoidPointerType()) {
2432           QualType PT = T->castAs<PointerType>()->getPointeeType();
2433           if (!PT->isStructureType())
2434             break;
2435         }
2436         Context.setObjCIdRedefinitionType(T);
2437         // Install the built-in type for 'id', ignoring the current definition.
2438         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2439         return;
2440       }
2441     case 5:
2442       if (!TypeID->isStr("Class"))
2443         break;
2444       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2445       // Install the built-in type for 'Class', ignoring the current definition.
2446       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2447       return;
2448     case 3:
2449       if (!TypeID->isStr("SEL"))
2450         break;
2451       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2452       // Install the built-in type for 'SEL', ignoring the current definition.
2453       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2454       return;
2455     }
2456     // Fall through - the typedef name was not a builtin type.
2457   }
2458 
2459   // Verify the old decl was also a type.
2460   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2461   if (!Old) {
2462     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2463       << New->getDeclName();
2464 
2465     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2466     if (OldD->getLocation().isValid())
2467       notePreviousDefinition(OldD, New->getLocation());
2468 
2469     return New->setInvalidDecl();
2470   }
2471 
2472   // If the old declaration is invalid, just give up here.
2473   if (Old->isInvalidDecl())
2474     return New->setInvalidDecl();
2475 
2476   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2477     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2478     auto *NewTag = New->getAnonDeclWithTypedefName();
2479     NamedDecl *Hidden = nullptr;
2480     if (OldTag && NewTag &&
2481         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2482         !hasVisibleDefinition(OldTag, &Hidden)) {
2483       // There is a definition of this tag, but it is not visible. Use it
2484       // instead of our tag.
2485       New->setTypeForDecl(OldTD->getTypeForDecl());
2486       if (OldTD->isModed())
2487         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2488                                     OldTD->getUnderlyingType());
2489       else
2490         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2491 
2492       // Make the old tag definition visible.
2493       makeMergedDefinitionVisible(Hidden);
2494 
2495       // If this was an unscoped enumeration, yank all of its enumerators
2496       // out of the scope.
2497       if (isa<EnumDecl>(NewTag)) {
2498         Scope *EnumScope = getNonFieldDeclScope(S);
2499         for (auto *D : NewTag->decls()) {
2500           auto *ED = cast<EnumConstantDecl>(D);
2501           assert(EnumScope->isDeclScope(ED));
2502           EnumScope->RemoveDecl(ED);
2503           IdResolver.RemoveDecl(ED);
2504           ED->getLexicalDeclContext()->removeDecl(ED);
2505         }
2506       }
2507     }
2508   }
2509 
2510   // If the typedef types are not identical, reject them in all languages and
2511   // with any extensions enabled.
2512   if (isIncompatibleTypedef(Old, New))
2513     return;
2514 
2515   // The types match.  Link up the redeclaration chain and merge attributes if
2516   // the old declaration was a typedef.
2517   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2518     New->setPreviousDecl(Typedef);
2519     mergeDeclAttributes(New, Old);
2520   }
2521 
2522   if (getLangOpts().MicrosoftExt)
2523     return;
2524 
2525   if (getLangOpts().CPlusPlus) {
2526     // C++ [dcl.typedef]p2:
2527     //   In a given non-class scope, a typedef specifier can be used to
2528     //   redefine the name of any type declared in that scope to refer
2529     //   to the type to which it already refers.
2530     if (!isa<CXXRecordDecl>(CurContext))
2531       return;
2532 
2533     // C++0x [dcl.typedef]p4:
2534     //   In a given class scope, a typedef specifier can be used to redefine
2535     //   any class-name declared in that scope that is not also a typedef-name
2536     //   to refer to the type to which it already refers.
2537     //
2538     // This wording came in via DR424, which was a correction to the
2539     // wording in DR56, which accidentally banned code like:
2540     //
2541     //   struct S {
2542     //     typedef struct A { } A;
2543     //   };
2544     //
2545     // in the C++03 standard. We implement the C++0x semantics, which
2546     // allow the above but disallow
2547     //
2548     //   struct S {
2549     //     typedef int I;
2550     //     typedef int I;
2551     //   };
2552     //
2553     // since that was the intent of DR56.
2554     if (!isa<TypedefNameDecl>(Old))
2555       return;
2556 
2557     Diag(New->getLocation(), diag::err_redefinition)
2558       << New->getDeclName();
2559     notePreviousDefinition(Old, New->getLocation());
2560     return New->setInvalidDecl();
2561   }
2562 
2563   // Modules always permit redefinition of typedefs, as does C11.
2564   if (getLangOpts().Modules || getLangOpts().C11)
2565     return;
2566 
2567   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2568   // is normally mapped to an error, but can be controlled with
2569   // -Wtypedef-redefinition.  If either the original or the redefinition is
2570   // in a system header, don't emit this for compatibility with GCC.
2571   if (getDiagnostics().getSuppressSystemWarnings() &&
2572       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2573       (Old->isImplicit() ||
2574        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2575        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2576     return;
2577 
2578   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2579     << New->getDeclName();
2580   notePreviousDefinition(Old, New->getLocation());
2581 }
2582 
2583 /// DeclhasAttr - returns true if decl Declaration already has the target
2584 /// attribute.
2585 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2586   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2587   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2588   for (const auto *i : D->attrs())
2589     if (i->getKind() == A->getKind()) {
2590       if (Ann) {
2591         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2592           return true;
2593         continue;
2594       }
2595       // FIXME: Don't hardcode this check
2596       if (OA && isa<OwnershipAttr>(i))
2597         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2598       return true;
2599     }
2600 
2601   return false;
2602 }
2603 
2604 static bool isAttributeTargetADefinition(Decl *D) {
2605   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2606     return VD->isThisDeclarationADefinition();
2607   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2608     return TD->isCompleteDefinition() || TD->isBeingDefined();
2609   return true;
2610 }
2611 
2612 /// Merge alignment attributes from \p Old to \p New, taking into account the
2613 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2614 ///
2615 /// \return \c true if any attributes were added to \p New.
2616 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2617   // Look for alignas attributes on Old, and pick out whichever attribute
2618   // specifies the strictest alignment requirement.
2619   AlignedAttr *OldAlignasAttr = nullptr;
2620   AlignedAttr *OldStrictestAlignAttr = nullptr;
2621   unsigned OldAlign = 0;
2622   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2623     // FIXME: We have no way of representing inherited dependent alignments
2624     // in a case like:
2625     //   template<int A, int B> struct alignas(A) X;
2626     //   template<int A, int B> struct alignas(B) X {};
2627     // For now, we just ignore any alignas attributes which are not on the
2628     // definition in such a case.
2629     if (I->isAlignmentDependent())
2630       return false;
2631 
2632     if (I->isAlignas())
2633       OldAlignasAttr = I;
2634 
2635     unsigned Align = I->getAlignment(S.Context);
2636     if (Align > OldAlign) {
2637       OldAlign = Align;
2638       OldStrictestAlignAttr = I;
2639     }
2640   }
2641 
2642   // Look for alignas attributes on New.
2643   AlignedAttr *NewAlignasAttr = nullptr;
2644   unsigned NewAlign = 0;
2645   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2646     if (I->isAlignmentDependent())
2647       return false;
2648 
2649     if (I->isAlignas())
2650       NewAlignasAttr = I;
2651 
2652     unsigned Align = I->getAlignment(S.Context);
2653     if (Align > NewAlign)
2654       NewAlign = Align;
2655   }
2656 
2657   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2658     // Both declarations have 'alignas' attributes. We require them to match.
2659     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2660     // fall short. (If two declarations both have alignas, they must both match
2661     // every definition, and so must match each other if there is a definition.)
2662 
2663     // If either declaration only contains 'alignas(0)' specifiers, then it
2664     // specifies the natural alignment for the type.
2665     if (OldAlign == 0 || NewAlign == 0) {
2666       QualType Ty;
2667       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2668         Ty = VD->getType();
2669       else
2670         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2671 
2672       if (OldAlign == 0)
2673         OldAlign = S.Context.getTypeAlign(Ty);
2674       if (NewAlign == 0)
2675         NewAlign = S.Context.getTypeAlign(Ty);
2676     }
2677 
2678     if (OldAlign != NewAlign) {
2679       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2680         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2681         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2682       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2683     }
2684   }
2685 
2686   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2687     // C++11 [dcl.align]p6:
2688     //   if any declaration of an entity has an alignment-specifier,
2689     //   every defining declaration of that entity shall specify an
2690     //   equivalent alignment.
2691     // C11 6.7.5/7:
2692     //   If the definition of an object does not have an alignment
2693     //   specifier, any other declaration of that object shall also
2694     //   have no alignment specifier.
2695     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2696       << OldAlignasAttr;
2697     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2698       << OldAlignasAttr;
2699   }
2700 
2701   bool AnyAdded = false;
2702 
2703   // Ensure we have an attribute representing the strictest alignment.
2704   if (OldAlign > NewAlign) {
2705     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2706     Clone->setInherited(true);
2707     New->addAttr(Clone);
2708     AnyAdded = true;
2709   }
2710 
2711   // Ensure we have an alignas attribute if the old declaration had one.
2712   if (OldAlignasAttr && !NewAlignasAttr &&
2713       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2714     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2715     Clone->setInherited(true);
2716     New->addAttr(Clone);
2717     AnyAdded = true;
2718   }
2719 
2720   return AnyAdded;
2721 }
2722 
2723 #define WANT_DECL_MERGE_LOGIC
2724 #include "clang/Sema/AttrParsedAttrImpl.inc"
2725 #undef WANT_DECL_MERGE_LOGIC
2726 
2727 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2728                                const InheritableAttr *Attr,
2729                                Sema::AvailabilityMergeKind AMK) {
2730   // Diagnose any mutual exclusions between the attribute that we want to add
2731   // and attributes that already exist on the declaration.
2732   if (!DiagnoseMutualExclusions(S, D, Attr))
2733     return false;
2734 
2735   // This function copies an attribute Attr from a previous declaration to the
2736   // new declaration D if the new declaration doesn't itself have that attribute
2737   // yet or if that attribute allows duplicates.
2738   // If you're adding a new attribute that requires logic different from
2739   // "use explicit attribute on decl if present, else use attribute from
2740   // previous decl", for example if the attribute needs to be consistent
2741   // between redeclarations, you need to call a custom merge function here.
2742   InheritableAttr *NewAttr = nullptr;
2743   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2744     NewAttr = S.mergeAvailabilityAttr(
2745         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2746         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2747         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2748         AA->getPriority());
2749   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2750     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2751   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2752     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2753   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2754     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2755   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2756     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2757   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2758     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2759   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2760     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2761                                 FA->getFirstArg());
2762   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2763     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2764   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2765     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2766   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2767     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2768                                        IA->getInheritanceModel());
2769   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2770     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2771                                       &S.Context.Idents.get(AA->getSpelling()));
2772   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2773            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2774             isa<CUDAGlobalAttr>(Attr))) {
2775     // CUDA target attributes are part of function signature for
2776     // overloading purposes and must not be merged.
2777     return false;
2778   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2779     NewAttr = S.mergeMinSizeAttr(D, *MA);
2780   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2781     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2782   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2783     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2784   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2785     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2786   else if (isa<AlignedAttr>(Attr))
2787     // AlignedAttrs are handled separately, because we need to handle all
2788     // such attributes on a declaration at the same time.
2789     NewAttr = nullptr;
2790   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2791            (AMK == Sema::AMK_Override ||
2792             AMK == Sema::AMK_ProtocolImplementation ||
2793             AMK == Sema::AMK_OptionalProtocolImplementation))
2794     NewAttr = nullptr;
2795   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2796     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2797   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2798     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2799   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2800     NewAttr = S.mergeImportNameAttr(D, *INA);
2801   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2802     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2803   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2804     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2805   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2806     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2807   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2808     NewAttr =
2809         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2810   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2811     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2812   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2813     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2814 
2815   if (NewAttr) {
2816     NewAttr->setInherited(true);
2817     D->addAttr(NewAttr);
2818     if (isa<MSInheritanceAttr>(NewAttr))
2819       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2820     return true;
2821   }
2822 
2823   return false;
2824 }
2825 
2826 static const NamedDecl *getDefinition(const Decl *D) {
2827   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2828     return TD->getDefinition();
2829   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2830     const VarDecl *Def = VD->getDefinition();
2831     if (Def)
2832       return Def;
2833     return VD->getActingDefinition();
2834   }
2835   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2836     const FunctionDecl *Def = nullptr;
2837     if (FD->isDefined(Def, true))
2838       return Def;
2839   }
2840   return nullptr;
2841 }
2842 
2843 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2844   for (const auto *Attribute : D->attrs())
2845     if (Attribute->getKind() == Kind)
2846       return true;
2847   return false;
2848 }
2849 
2850 /// checkNewAttributesAfterDef - If we already have a definition, check that
2851 /// there are no new attributes in this declaration.
2852 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2853   if (!New->hasAttrs())
2854     return;
2855 
2856   const NamedDecl *Def = getDefinition(Old);
2857   if (!Def || Def == New)
2858     return;
2859 
2860   AttrVec &NewAttributes = New->getAttrs();
2861   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2862     const Attr *NewAttribute = NewAttributes[I];
2863 
2864     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2865       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2866         Sema::SkipBodyInfo SkipBody;
2867         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2868 
2869         // If we're skipping this definition, drop the "alias" attribute.
2870         if (SkipBody.ShouldSkip) {
2871           NewAttributes.erase(NewAttributes.begin() + I);
2872           --E;
2873           continue;
2874         }
2875       } else {
2876         VarDecl *VD = cast<VarDecl>(New);
2877         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2878                                 VarDecl::TentativeDefinition
2879                             ? diag::err_alias_after_tentative
2880                             : diag::err_redefinition;
2881         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2882         if (Diag == diag::err_redefinition)
2883           S.notePreviousDefinition(Def, VD->getLocation());
2884         else
2885           S.Diag(Def->getLocation(), diag::note_previous_definition);
2886         VD->setInvalidDecl();
2887       }
2888       ++I;
2889       continue;
2890     }
2891 
2892     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2893       // Tentative definitions are only interesting for the alias check above.
2894       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2895         ++I;
2896         continue;
2897       }
2898     }
2899 
2900     if (hasAttribute(Def, NewAttribute->getKind())) {
2901       ++I;
2902       continue; // regular attr merging will take care of validating this.
2903     }
2904 
2905     if (isa<C11NoReturnAttr>(NewAttribute)) {
2906       // C's _Noreturn is allowed to be added to a function after it is defined.
2907       ++I;
2908       continue;
2909     } else if (isa<UuidAttr>(NewAttribute)) {
2910       // msvc will allow a subsequent definition to add an uuid to a class
2911       ++I;
2912       continue;
2913     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2914       if (AA->isAlignas()) {
2915         // C++11 [dcl.align]p6:
2916         //   if any declaration of an entity has an alignment-specifier,
2917         //   every defining declaration of that entity shall specify an
2918         //   equivalent alignment.
2919         // C11 6.7.5/7:
2920         //   If the definition of an object does not have an alignment
2921         //   specifier, any other declaration of that object shall also
2922         //   have no alignment specifier.
2923         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2924           << AA;
2925         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2926           << AA;
2927         NewAttributes.erase(NewAttributes.begin() + I);
2928         --E;
2929         continue;
2930       }
2931     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2932       // If there is a C definition followed by a redeclaration with this
2933       // attribute then there are two different definitions. In C++, prefer the
2934       // standard diagnostics.
2935       if (!S.getLangOpts().CPlusPlus) {
2936         S.Diag(NewAttribute->getLocation(),
2937                diag::err_loader_uninitialized_redeclaration);
2938         S.Diag(Def->getLocation(), diag::note_previous_definition);
2939         NewAttributes.erase(NewAttributes.begin() + I);
2940         --E;
2941         continue;
2942       }
2943     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2944                cast<VarDecl>(New)->isInline() &&
2945                !cast<VarDecl>(New)->isInlineSpecified()) {
2946       // Don't warn about applying selectany to implicitly inline variables.
2947       // Older compilers and language modes would require the use of selectany
2948       // to make such variables inline, and it would have no effect if we
2949       // honored it.
2950       ++I;
2951       continue;
2952     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2953       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2954       // declarations after defintions.
2955       ++I;
2956       continue;
2957     }
2958 
2959     S.Diag(NewAttribute->getLocation(),
2960            diag::warn_attribute_precede_definition);
2961     S.Diag(Def->getLocation(), diag::note_previous_definition);
2962     NewAttributes.erase(NewAttributes.begin() + I);
2963     --E;
2964   }
2965 }
2966 
2967 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2968                                      const ConstInitAttr *CIAttr,
2969                                      bool AttrBeforeInit) {
2970   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2971 
2972   // Figure out a good way to write this specifier on the old declaration.
2973   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2974   // enough of the attribute list spelling information to extract that without
2975   // heroics.
2976   std::string SuitableSpelling;
2977   if (S.getLangOpts().CPlusPlus20)
2978     SuitableSpelling = std::string(
2979         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2980   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2981     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2982         InsertLoc, {tok::l_square, tok::l_square,
2983                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2984                     S.PP.getIdentifierInfo("require_constant_initialization"),
2985                     tok::r_square, tok::r_square}));
2986   if (SuitableSpelling.empty())
2987     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2988         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2989                     S.PP.getIdentifierInfo("require_constant_initialization"),
2990                     tok::r_paren, tok::r_paren}));
2991   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2992     SuitableSpelling = "constinit";
2993   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2994     SuitableSpelling = "[[clang::require_constant_initialization]]";
2995   if (SuitableSpelling.empty())
2996     SuitableSpelling = "__attribute__((require_constant_initialization))";
2997   SuitableSpelling += " ";
2998 
2999   if (AttrBeforeInit) {
3000     // extern constinit int a;
3001     // int a = 0; // error (missing 'constinit'), accepted as extension
3002     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3003     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3004         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3005     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3006   } else {
3007     // int a = 0;
3008     // constinit extern int a; // error (missing 'constinit')
3009     S.Diag(CIAttr->getLocation(),
3010            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3011                                  : diag::warn_require_const_init_added_too_late)
3012         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3013     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3014         << CIAttr->isConstinit()
3015         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3016   }
3017 }
3018 
3019 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3020 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3021                                AvailabilityMergeKind AMK) {
3022   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3023     UsedAttr *NewAttr = OldAttr->clone(Context);
3024     NewAttr->setInherited(true);
3025     New->addAttr(NewAttr);
3026   }
3027   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3028     RetainAttr *NewAttr = OldAttr->clone(Context);
3029     NewAttr->setInherited(true);
3030     New->addAttr(NewAttr);
3031   }
3032 
3033   if (!Old->hasAttrs() && !New->hasAttrs())
3034     return;
3035 
3036   // [dcl.constinit]p1:
3037   //   If the [constinit] specifier is applied to any declaration of a
3038   //   variable, it shall be applied to the initializing declaration.
3039   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3040   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3041   if (bool(OldConstInit) != bool(NewConstInit)) {
3042     const auto *OldVD = cast<VarDecl>(Old);
3043     auto *NewVD = cast<VarDecl>(New);
3044 
3045     // Find the initializing declaration. Note that we might not have linked
3046     // the new declaration into the redeclaration chain yet.
3047     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3048     if (!InitDecl &&
3049         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3050       InitDecl = NewVD;
3051 
3052     if (InitDecl == NewVD) {
3053       // This is the initializing declaration. If it would inherit 'constinit',
3054       // that's ill-formed. (Note that we do not apply this to the attribute
3055       // form).
3056       if (OldConstInit && OldConstInit->isConstinit())
3057         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3058                                  /*AttrBeforeInit=*/true);
3059     } else if (NewConstInit) {
3060       // This is the first time we've been told that this declaration should
3061       // have a constant initializer. If we already saw the initializing
3062       // declaration, this is too late.
3063       if (InitDecl && InitDecl != NewVD) {
3064         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3065                                  /*AttrBeforeInit=*/false);
3066         NewVD->dropAttr<ConstInitAttr>();
3067       }
3068     }
3069   }
3070 
3071   // Attributes declared post-definition are currently ignored.
3072   checkNewAttributesAfterDef(*this, New, Old);
3073 
3074   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3075     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3076       if (!OldA->isEquivalent(NewA)) {
3077         // This redeclaration changes __asm__ label.
3078         Diag(New->getLocation(), diag::err_different_asm_label);
3079         Diag(OldA->getLocation(), diag::note_previous_declaration);
3080       }
3081     } else if (Old->isUsed()) {
3082       // This redeclaration adds an __asm__ label to a declaration that has
3083       // already been ODR-used.
3084       Diag(New->getLocation(), diag::err_late_asm_label_name)
3085         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3086     }
3087   }
3088 
3089   // Re-declaration cannot add abi_tag's.
3090   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3091     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3092       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3093         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3094           Diag(NewAbiTagAttr->getLocation(),
3095                diag::err_new_abi_tag_on_redeclaration)
3096               << NewTag;
3097           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3098         }
3099       }
3100     } else {
3101       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3102       Diag(Old->getLocation(), diag::note_previous_declaration);
3103     }
3104   }
3105 
3106   // This redeclaration adds a section attribute.
3107   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3108     if (auto *VD = dyn_cast<VarDecl>(New)) {
3109       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3110         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3111         Diag(Old->getLocation(), diag::note_previous_declaration);
3112       }
3113     }
3114   }
3115 
3116   // Redeclaration adds code-seg attribute.
3117   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3118   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3119       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3120     Diag(New->getLocation(), diag::warn_mismatched_section)
3121          << 0 /*codeseg*/;
3122     Diag(Old->getLocation(), diag::note_previous_declaration);
3123   }
3124 
3125   if (!Old->hasAttrs())
3126     return;
3127 
3128   bool foundAny = New->hasAttrs();
3129 
3130   // Ensure that any moving of objects within the allocated map is done before
3131   // we process them.
3132   if (!foundAny) New->setAttrs(AttrVec());
3133 
3134   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3135     // Ignore deprecated/unavailable/availability attributes if requested.
3136     AvailabilityMergeKind LocalAMK = AMK_None;
3137     if (isa<DeprecatedAttr>(I) ||
3138         isa<UnavailableAttr>(I) ||
3139         isa<AvailabilityAttr>(I)) {
3140       switch (AMK) {
3141       case AMK_None:
3142         continue;
3143 
3144       case AMK_Redeclaration:
3145       case AMK_Override:
3146       case AMK_ProtocolImplementation:
3147       case AMK_OptionalProtocolImplementation:
3148         LocalAMK = AMK;
3149         break;
3150       }
3151     }
3152 
3153     // Already handled.
3154     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3155       continue;
3156 
3157     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3158       foundAny = true;
3159   }
3160 
3161   if (mergeAlignedAttrs(*this, New, Old))
3162     foundAny = true;
3163 
3164   if (!foundAny) New->dropAttrs();
3165 }
3166 
3167 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3168 /// to the new one.
3169 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3170                                      const ParmVarDecl *oldDecl,
3171                                      Sema &S) {
3172   // C++11 [dcl.attr.depend]p2:
3173   //   The first declaration of a function shall specify the
3174   //   carries_dependency attribute for its declarator-id if any declaration
3175   //   of the function specifies the carries_dependency attribute.
3176   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3177   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3178     S.Diag(CDA->getLocation(),
3179            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3180     // Find the first declaration of the parameter.
3181     // FIXME: Should we build redeclaration chains for function parameters?
3182     const FunctionDecl *FirstFD =
3183       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3184     const ParmVarDecl *FirstVD =
3185       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3186     S.Diag(FirstVD->getLocation(),
3187            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3188   }
3189 
3190   if (!oldDecl->hasAttrs())
3191     return;
3192 
3193   bool foundAny = newDecl->hasAttrs();
3194 
3195   // Ensure that any moving of objects within the allocated map is
3196   // done before we process them.
3197   if (!foundAny) newDecl->setAttrs(AttrVec());
3198 
3199   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3200     if (!DeclHasAttr(newDecl, I)) {
3201       InheritableAttr *newAttr =
3202         cast<InheritableParamAttr>(I->clone(S.Context));
3203       newAttr->setInherited(true);
3204       newDecl->addAttr(newAttr);
3205       foundAny = true;
3206     }
3207   }
3208 
3209   if (!foundAny) newDecl->dropAttrs();
3210 }
3211 
3212 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3213                                 const ParmVarDecl *OldParam,
3214                                 Sema &S) {
3215   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3216     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3217       if (*Oldnullability != *Newnullability) {
3218         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3219           << DiagNullabilityKind(
3220                *Newnullability,
3221                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3222                 != 0))
3223           << DiagNullabilityKind(
3224                *Oldnullability,
3225                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3226                 != 0));
3227         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3228       }
3229     } else {
3230       QualType NewT = NewParam->getType();
3231       NewT = S.Context.getAttributedType(
3232                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3233                          NewT, NewT);
3234       NewParam->setType(NewT);
3235     }
3236   }
3237 }
3238 
3239 namespace {
3240 
3241 /// Used in MergeFunctionDecl to keep track of function parameters in
3242 /// C.
3243 struct GNUCompatibleParamWarning {
3244   ParmVarDecl *OldParm;
3245   ParmVarDecl *NewParm;
3246   QualType PromotedType;
3247 };
3248 
3249 } // end anonymous namespace
3250 
3251 // Determine whether the previous declaration was a definition, implicit
3252 // declaration, or a declaration.
3253 template <typename T>
3254 static std::pair<diag::kind, SourceLocation>
3255 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3256   diag::kind PrevDiag;
3257   SourceLocation OldLocation = Old->getLocation();
3258   if (Old->isThisDeclarationADefinition())
3259     PrevDiag = diag::note_previous_definition;
3260   else if (Old->isImplicit()) {
3261     PrevDiag = diag::note_previous_implicit_declaration;
3262     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3263       if (FD->getBuiltinID())
3264         PrevDiag = diag::note_previous_builtin_declaration;
3265     }
3266     if (OldLocation.isInvalid())
3267       OldLocation = New->getLocation();
3268   } else
3269     PrevDiag = diag::note_previous_declaration;
3270   return std::make_pair(PrevDiag, OldLocation);
3271 }
3272 
3273 /// canRedefineFunction - checks if a function can be redefined. Currently,
3274 /// only extern inline functions can be redefined, and even then only in
3275 /// GNU89 mode.
3276 static bool canRedefineFunction(const FunctionDecl *FD,
3277                                 const LangOptions& LangOpts) {
3278   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3279           !LangOpts.CPlusPlus &&
3280           FD->isInlineSpecified() &&
3281           FD->getStorageClass() == SC_Extern);
3282 }
3283 
3284 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3285   const AttributedType *AT = T->getAs<AttributedType>();
3286   while (AT && !AT->isCallingConv())
3287     AT = AT->getModifiedType()->getAs<AttributedType>();
3288   return AT;
3289 }
3290 
3291 template <typename T>
3292 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3293   const DeclContext *DC = Old->getDeclContext();
3294   if (DC->isRecord())
3295     return false;
3296 
3297   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3298   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3299     return true;
3300   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3301     return true;
3302   return false;
3303 }
3304 
3305 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3306 static bool isExternC(VarTemplateDecl *) { return false; }
3307 static bool isExternC(FunctionTemplateDecl *) { return false; }
3308 
3309 /// Check whether a redeclaration of an entity introduced by a
3310 /// using-declaration is valid, given that we know it's not an overload
3311 /// (nor a hidden tag declaration).
3312 template<typename ExpectedDecl>
3313 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3314                                    ExpectedDecl *New) {
3315   // C++11 [basic.scope.declarative]p4:
3316   //   Given a set of declarations in a single declarative region, each of
3317   //   which specifies the same unqualified name,
3318   //   -- they shall all refer to the same entity, or all refer to functions
3319   //      and function templates; or
3320   //   -- exactly one declaration shall declare a class name or enumeration
3321   //      name that is not a typedef name and the other declarations shall all
3322   //      refer to the same variable or enumerator, or all refer to functions
3323   //      and function templates; in this case the class name or enumeration
3324   //      name is hidden (3.3.10).
3325 
3326   // C++11 [namespace.udecl]p14:
3327   //   If a function declaration in namespace scope or block scope has the
3328   //   same name and the same parameter-type-list as a function introduced
3329   //   by a using-declaration, and the declarations do not declare the same
3330   //   function, the program is ill-formed.
3331 
3332   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3333   if (Old &&
3334       !Old->getDeclContext()->getRedeclContext()->Equals(
3335           New->getDeclContext()->getRedeclContext()) &&
3336       !(isExternC(Old) && isExternC(New)))
3337     Old = nullptr;
3338 
3339   if (!Old) {
3340     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3341     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3342     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3343     return true;
3344   }
3345   return false;
3346 }
3347 
3348 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3349                                             const FunctionDecl *B) {
3350   assert(A->getNumParams() == B->getNumParams());
3351 
3352   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3353     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3354     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3355     if (AttrA == AttrB)
3356       return true;
3357     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3358            AttrA->isDynamic() == AttrB->isDynamic();
3359   };
3360 
3361   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3362 }
3363 
3364 /// If necessary, adjust the semantic declaration context for a qualified
3365 /// declaration to name the correct inline namespace within the qualifier.
3366 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3367                                                DeclaratorDecl *OldD) {
3368   // The only case where we need to update the DeclContext is when
3369   // redeclaration lookup for a qualified name finds a declaration
3370   // in an inline namespace within the context named by the qualifier:
3371   //
3372   //   inline namespace N { int f(); }
3373   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3374   //
3375   // For unqualified declarations, the semantic context *can* change
3376   // along the redeclaration chain (for local extern declarations,
3377   // extern "C" declarations, and friend declarations in particular).
3378   if (!NewD->getQualifier())
3379     return;
3380 
3381   // NewD is probably already in the right context.
3382   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3383   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3384   if (NamedDC->Equals(SemaDC))
3385     return;
3386 
3387   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3388           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3389          "unexpected context for redeclaration");
3390 
3391   auto *LexDC = NewD->getLexicalDeclContext();
3392   auto FixSemaDC = [=](NamedDecl *D) {
3393     if (!D)
3394       return;
3395     D->setDeclContext(SemaDC);
3396     D->setLexicalDeclContext(LexDC);
3397   };
3398 
3399   FixSemaDC(NewD);
3400   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3401     FixSemaDC(FD->getDescribedFunctionTemplate());
3402   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3403     FixSemaDC(VD->getDescribedVarTemplate());
3404 }
3405 
3406 /// MergeFunctionDecl - We just parsed a function 'New' from
3407 /// declarator D which has the same name and scope as a previous
3408 /// declaration 'Old'.  Figure out how to resolve this situation,
3409 /// merging decls or emitting diagnostics as appropriate.
3410 ///
3411 /// In C++, New and Old must be declarations that are not
3412 /// overloaded. Use IsOverload to determine whether New and Old are
3413 /// overloaded, and to select the Old declaration that New should be
3414 /// merged with.
3415 ///
3416 /// Returns true if there was an error, false otherwise.
3417 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3418                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3419   // Verify the old decl was also a function.
3420   FunctionDecl *Old = OldD->getAsFunction();
3421   if (!Old) {
3422     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3423       if (New->getFriendObjectKind()) {
3424         Diag(New->getLocation(), diag::err_using_decl_friend);
3425         Diag(Shadow->getTargetDecl()->getLocation(),
3426              diag::note_using_decl_target);
3427         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3428             << 0;
3429         return true;
3430       }
3431 
3432       // Check whether the two declarations might declare the same function or
3433       // function template.
3434       if (FunctionTemplateDecl *NewTemplate =
3435               New->getDescribedFunctionTemplate()) {
3436         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3437                                                          NewTemplate))
3438           return true;
3439         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3440                          ->getAsFunction();
3441       } else {
3442         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3443           return true;
3444         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3445       }
3446     } else {
3447       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3448         << New->getDeclName();
3449       notePreviousDefinition(OldD, New->getLocation());
3450       return true;
3451     }
3452   }
3453 
3454   // If the old declaration was found in an inline namespace and the new
3455   // declaration was qualified, update the DeclContext to match.
3456   adjustDeclContextForDeclaratorDecl(New, Old);
3457 
3458   // If the old declaration is invalid, just give up here.
3459   if (Old->isInvalidDecl())
3460     return true;
3461 
3462   // Disallow redeclaration of some builtins.
3463   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3464     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3465     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3466         << Old << Old->getType();
3467     return true;
3468   }
3469 
3470   diag::kind PrevDiag;
3471   SourceLocation OldLocation;
3472   std::tie(PrevDiag, OldLocation) =
3473       getNoteDiagForInvalidRedeclaration(Old, New);
3474 
3475   // Don't complain about this if we're in GNU89 mode and the old function
3476   // is an extern inline function.
3477   // Don't complain about specializations. They are not supposed to have
3478   // storage classes.
3479   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3480       New->getStorageClass() == SC_Static &&
3481       Old->hasExternalFormalLinkage() &&
3482       !New->getTemplateSpecializationInfo() &&
3483       !canRedefineFunction(Old, getLangOpts())) {
3484     if (getLangOpts().MicrosoftExt) {
3485       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3486       Diag(OldLocation, PrevDiag);
3487     } else {
3488       Diag(New->getLocation(), diag::err_static_non_static) << New;
3489       Diag(OldLocation, PrevDiag);
3490       return true;
3491     }
3492   }
3493 
3494   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3495     if (!Old->hasAttr<InternalLinkageAttr>()) {
3496       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3497           << ILA;
3498       Diag(Old->getLocation(), diag::note_previous_declaration);
3499       New->dropAttr<InternalLinkageAttr>();
3500     }
3501 
3502   if (auto *EA = New->getAttr<ErrorAttr>()) {
3503     if (!Old->hasAttr<ErrorAttr>()) {
3504       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3505       Diag(Old->getLocation(), diag::note_previous_declaration);
3506       New->dropAttr<ErrorAttr>();
3507     }
3508   }
3509 
3510   if (CheckRedeclarationInModule(New, Old))
3511     return true;
3512 
3513   if (!getLangOpts().CPlusPlus) {
3514     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3515     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3516       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3517         << New << OldOvl;
3518 
3519       // Try our best to find a decl that actually has the overloadable
3520       // attribute for the note. In most cases (e.g. programs with only one
3521       // broken declaration/definition), this won't matter.
3522       //
3523       // FIXME: We could do this if we juggled some extra state in
3524       // OverloadableAttr, rather than just removing it.
3525       const Decl *DiagOld = Old;
3526       if (OldOvl) {
3527         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3528           const auto *A = D->getAttr<OverloadableAttr>();
3529           return A && !A->isImplicit();
3530         });
3531         // If we've implicitly added *all* of the overloadable attrs to this
3532         // chain, emitting a "previous redecl" note is pointless.
3533         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3534       }
3535 
3536       if (DiagOld)
3537         Diag(DiagOld->getLocation(),
3538              diag::note_attribute_overloadable_prev_overload)
3539           << OldOvl;
3540 
3541       if (OldOvl)
3542         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3543       else
3544         New->dropAttr<OverloadableAttr>();
3545     }
3546   }
3547 
3548   // If a function is first declared with a calling convention, but is later
3549   // declared or defined without one, all following decls assume the calling
3550   // convention of the first.
3551   //
3552   // It's OK if a function is first declared without a calling convention,
3553   // but is later declared or defined with the default calling convention.
3554   //
3555   // To test if either decl has an explicit calling convention, we look for
3556   // AttributedType sugar nodes on the type as written.  If they are missing or
3557   // were canonicalized away, we assume the calling convention was implicit.
3558   //
3559   // Note also that we DO NOT return at this point, because we still have
3560   // other tests to run.
3561   QualType OldQType = Context.getCanonicalType(Old->getType());
3562   QualType NewQType = Context.getCanonicalType(New->getType());
3563   const FunctionType *OldType = cast<FunctionType>(OldQType);
3564   const FunctionType *NewType = cast<FunctionType>(NewQType);
3565   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3566   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3567   bool RequiresAdjustment = false;
3568 
3569   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3570     FunctionDecl *First = Old->getFirstDecl();
3571     const FunctionType *FT =
3572         First->getType().getCanonicalType()->castAs<FunctionType>();
3573     FunctionType::ExtInfo FI = FT->getExtInfo();
3574     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3575     if (!NewCCExplicit) {
3576       // Inherit the CC from the previous declaration if it was specified
3577       // there but not here.
3578       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3579       RequiresAdjustment = true;
3580     } else if (Old->getBuiltinID()) {
3581       // Builtin attribute isn't propagated to the new one yet at this point,
3582       // so we check if the old one is a builtin.
3583 
3584       // Calling Conventions on a Builtin aren't really useful and setting a
3585       // default calling convention and cdecl'ing some builtin redeclarations is
3586       // common, so warn and ignore the calling convention on the redeclaration.
3587       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3588           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3589           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3590       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3591       RequiresAdjustment = true;
3592     } else {
3593       // Calling conventions aren't compatible, so complain.
3594       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3595       Diag(New->getLocation(), diag::err_cconv_change)
3596         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3597         << !FirstCCExplicit
3598         << (!FirstCCExplicit ? "" :
3599             FunctionType::getNameForCallConv(FI.getCC()));
3600 
3601       // Put the note on the first decl, since it is the one that matters.
3602       Diag(First->getLocation(), diag::note_previous_declaration);
3603       return true;
3604     }
3605   }
3606 
3607   // FIXME: diagnose the other way around?
3608   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3609     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3610     RequiresAdjustment = true;
3611   }
3612 
3613   // Merge regparm attribute.
3614   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3615       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3616     if (NewTypeInfo.getHasRegParm()) {
3617       Diag(New->getLocation(), diag::err_regparm_mismatch)
3618         << NewType->getRegParmType()
3619         << OldType->getRegParmType();
3620       Diag(OldLocation, diag::note_previous_declaration);
3621       return true;
3622     }
3623 
3624     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3625     RequiresAdjustment = true;
3626   }
3627 
3628   // Merge ns_returns_retained attribute.
3629   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3630     if (NewTypeInfo.getProducesResult()) {
3631       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3632           << "'ns_returns_retained'";
3633       Diag(OldLocation, diag::note_previous_declaration);
3634       return true;
3635     }
3636 
3637     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3638     RequiresAdjustment = true;
3639   }
3640 
3641   if (OldTypeInfo.getNoCallerSavedRegs() !=
3642       NewTypeInfo.getNoCallerSavedRegs()) {
3643     if (NewTypeInfo.getNoCallerSavedRegs()) {
3644       AnyX86NoCallerSavedRegistersAttr *Attr =
3645         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3646       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3647       Diag(OldLocation, diag::note_previous_declaration);
3648       return true;
3649     }
3650 
3651     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3652     RequiresAdjustment = true;
3653   }
3654 
3655   if (RequiresAdjustment) {
3656     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3657     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3658     New->setType(QualType(AdjustedType, 0));
3659     NewQType = Context.getCanonicalType(New->getType());
3660   }
3661 
3662   // If this redeclaration makes the function inline, we may need to add it to
3663   // UndefinedButUsed.
3664   if (!Old->isInlined() && New->isInlined() &&
3665       !New->hasAttr<GNUInlineAttr>() &&
3666       !getLangOpts().GNUInline &&
3667       Old->isUsed(false) &&
3668       !Old->isDefined() && !New->isThisDeclarationADefinition())
3669     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3670                                            SourceLocation()));
3671 
3672   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3673   // about it.
3674   if (New->hasAttr<GNUInlineAttr>() &&
3675       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3676     UndefinedButUsed.erase(Old->getCanonicalDecl());
3677   }
3678 
3679   // If pass_object_size params don't match up perfectly, this isn't a valid
3680   // redeclaration.
3681   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3682       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3683     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3684         << New->getDeclName();
3685     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3686     return true;
3687   }
3688 
3689   if (getLangOpts().CPlusPlus) {
3690     // C++1z [over.load]p2
3691     //   Certain function declarations cannot be overloaded:
3692     //     -- Function declarations that differ only in the return type,
3693     //        the exception specification, or both cannot be overloaded.
3694 
3695     // Check the exception specifications match. This may recompute the type of
3696     // both Old and New if it resolved exception specifications, so grab the
3697     // types again after this. Because this updates the type, we do this before
3698     // any of the other checks below, which may update the "de facto" NewQType
3699     // but do not necessarily update the type of New.
3700     if (CheckEquivalentExceptionSpec(Old, New))
3701       return true;
3702     OldQType = Context.getCanonicalType(Old->getType());
3703     NewQType = Context.getCanonicalType(New->getType());
3704 
3705     // Go back to the type source info to compare the declared return types,
3706     // per C++1y [dcl.type.auto]p13:
3707     //   Redeclarations or specializations of a function or function template
3708     //   with a declared return type that uses a placeholder type shall also
3709     //   use that placeholder, not a deduced type.
3710     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3711     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3712     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3713         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3714                                        OldDeclaredReturnType)) {
3715       QualType ResQT;
3716       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3717           OldDeclaredReturnType->isObjCObjectPointerType())
3718         // FIXME: This does the wrong thing for a deduced return type.
3719         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3720       if (ResQT.isNull()) {
3721         if (New->isCXXClassMember() && New->isOutOfLine())
3722           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3723               << New << New->getReturnTypeSourceRange();
3724         else
3725           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3726               << New->getReturnTypeSourceRange();
3727         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3728                                     << Old->getReturnTypeSourceRange();
3729         return true;
3730       }
3731       else
3732         NewQType = ResQT;
3733     }
3734 
3735     QualType OldReturnType = OldType->getReturnType();
3736     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3737     if (OldReturnType != NewReturnType) {
3738       // If this function has a deduced return type and has already been
3739       // defined, copy the deduced value from the old declaration.
3740       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3741       if (OldAT && OldAT->isDeduced()) {
3742         QualType DT = OldAT->getDeducedType();
3743         if (DT.isNull()) {
3744           New->setType(SubstAutoTypeDependent(New->getType()));
3745           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3746         } else {
3747           New->setType(SubstAutoType(New->getType(), DT));
3748           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3749         }
3750       }
3751     }
3752 
3753     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3754     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3755     if (OldMethod && NewMethod) {
3756       // Preserve triviality.
3757       NewMethod->setTrivial(OldMethod->isTrivial());
3758 
3759       // MSVC allows explicit template specialization at class scope:
3760       // 2 CXXMethodDecls referring to the same function will be injected.
3761       // We don't want a redeclaration error.
3762       bool IsClassScopeExplicitSpecialization =
3763                               OldMethod->isFunctionTemplateSpecialization() &&
3764                               NewMethod->isFunctionTemplateSpecialization();
3765       bool isFriend = NewMethod->getFriendObjectKind();
3766 
3767       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3768           !IsClassScopeExplicitSpecialization) {
3769         //    -- Member function declarations with the same name and the
3770         //       same parameter types cannot be overloaded if any of them
3771         //       is a static member function declaration.
3772         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3773           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3774           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3775           return true;
3776         }
3777 
3778         // C++ [class.mem]p1:
3779         //   [...] A member shall not be declared twice in the
3780         //   member-specification, except that a nested class or member
3781         //   class template can be declared and then later defined.
3782         if (!inTemplateInstantiation()) {
3783           unsigned NewDiag;
3784           if (isa<CXXConstructorDecl>(OldMethod))
3785             NewDiag = diag::err_constructor_redeclared;
3786           else if (isa<CXXDestructorDecl>(NewMethod))
3787             NewDiag = diag::err_destructor_redeclared;
3788           else if (isa<CXXConversionDecl>(NewMethod))
3789             NewDiag = diag::err_conv_function_redeclared;
3790           else
3791             NewDiag = diag::err_member_redeclared;
3792 
3793           Diag(New->getLocation(), NewDiag);
3794         } else {
3795           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3796             << New << New->getType();
3797         }
3798         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3799         return true;
3800 
3801       // Complain if this is an explicit declaration of a special
3802       // member that was initially declared implicitly.
3803       //
3804       // As an exception, it's okay to befriend such methods in order
3805       // to permit the implicit constructor/destructor/operator calls.
3806       } else if (OldMethod->isImplicit()) {
3807         if (isFriend) {
3808           NewMethod->setImplicit();
3809         } else {
3810           Diag(NewMethod->getLocation(),
3811                diag::err_definition_of_implicitly_declared_member)
3812             << New << getSpecialMember(OldMethod);
3813           return true;
3814         }
3815       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3816         Diag(NewMethod->getLocation(),
3817              diag::err_definition_of_explicitly_defaulted_member)
3818           << getSpecialMember(OldMethod);
3819         return true;
3820       }
3821     }
3822 
3823     // C++11 [dcl.attr.noreturn]p1:
3824     //   The first declaration of a function shall specify the noreturn
3825     //   attribute if any declaration of that function specifies the noreturn
3826     //   attribute.
3827     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3828       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3829         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3830             << NRA;
3831         Diag(Old->getLocation(), diag::note_previous_declaration);
3832       }
3833 
3834     // C++11 [dcl.attr.depend]p2:
3835     //   The first declaration of a function shall specify the
3836     //   carries_dependency attribute for its declarator-id if any declaration
3837     //   of the function specifies the carries_dependency attribute.
3838     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3839     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3840       Diag(CDA->getLocation(),
3841            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3842       Diag(Old->getFirstDecl()->getLocation(),
3843            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3844     }
3845 
3846     // (C++98 8.3.5p3):
3847     //   All declarations for a function shall agree exactly in both the
3848     //   return type and the parameter-type-list.
3849     // We also want to respect all the extended bits except noreturn.
3850 
3851     // noreturn should now match unless the old type info didn't have it.
3852     QualType OldQTypeForComparison = OldQType;
3853     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3854       auto *OldType = OldQType->castAs<FunctionProtoType>();
3855       const FunctionType *OldTypeForComparison
3856         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3857       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3858       assert(OldQTypeForComparison.isCanonical());
3859     }
3860 
3861     if (haveIncompatibleLanguageLinkages(Old, New)) {
3862       // As a special case, retain the language linkage from previous
3863       // declarations of a friend function as an extension.
3864       //
3865       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3866       // and is useful because there's otherwise no way to specify language
3867       // linkage within class scope.
3868       //
3869       // Check cautiously as the friend object kind isn't yet complete.
3870       if (New->getFriendObjectKind() != Decl::FOK_None) {
3871         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3872         Diag(OldLocation, PrevDiag);
3873       } else {
3874         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3875         Diag(OldLocation, PrevDiag);
3876         return true;
3877       }
3878     }
3879 
3880     // If the function types are compatible, merge the declarations. Ignore the
3881     // exception specifier because it was already checked above in
3882     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3883     // about incompatible types under -fms-compatibility.
3884     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3885                                                          NewQType))
3886       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3887 
3888     // If the types are imprecise (due to dependent constructs in friends or
3889     // local extern declarations), it's OK if they differ. We'll check again
3890     // during instantiation.
3891     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3892       return false;
3893 
3894     // Fall through for conflicting redeclarations and redefinitions.
3895   }
3896 
3897   // C: Function types need to be compatible, not identical. This handles
3898   // duplicate function decls like "void f(int); void f(enum X);" properly.
3899   if (!getLangOpts().CPlusPlus) {
3900     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3901     // type is specified by a function definition that contains a (possibly
3902     // empty) identifier list, both shall agree in the number of parameters
3903     // and the type of each parameter shall be compatible with the type that
3904     // results from the application of default argument promotions to the
3905     // type of the corresponding identifier. ...
3906     // This cannot be handled by ASTContext::typesAreCompatible() because that
3907     // doesn't know whether the function type is for a definition or not when
3908     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3909     // we need to cover here is that the number of arguments agree as the
3910     // default argument promotion rules were already checked by
3911     // ASTContext::typesAreCompatible().
3912     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3913         Old->getNumParams() != New->getNumParams()) {
3914       if (Old->hasInheritedPrototype())
3915         Old = Old->getCanonicalDecl();
3916       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3917       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3918       return true;
3919     }
3920 
3921     // If we are merging two functions where only one of them has a prototype,
3922     // we may have enough information to decide to issue a diagnostic that the
3923     // function without a protoype will change behavior in C2x. This handles
3924     // cases like:
3925     //   void i(); void i(int j);
3926     //   void i(int j); void i();
3927     //   void i(); void i(int j) {}
3928     // See ActOnFinishFunctionBody() for other cases of the behavior change
3929     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3930     // type without a prototype.
3931     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3932         !New->isImplicit() && !Old->isImplicit()) {
3933       const FunctionDecl *WithProto, *WithoutProto;
3934       if (New->hasWrittenPrototype()) {
3935         WithProto = New;
3936         WithoutProto = Old;
3937       } else {
3938         WithProto = Old;
3939         WithoutProto = New;
3940       }
3941 
3942       if (WithProto->getNumParams() != 0) {
3943         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3944           // The one without the prototype will be changing behavior in C2x, so
3945           // warn about that one so long as it's a user-visible declaration.
3946           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3947           if (WithoutProto == New)
3948             IsWithoutProtoADef = NewDeclIsDefn;
3949           else
3950             IsWithProtoADef = NewDeclIsDefn;
3951           Diag(WithoutProto->getLocation(),
3952                diag::warn_non_prototype_changes_behavior)
3953               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
3954               << (WithoutProto == Old) << IsWithProtoADef;
3955 
3956           // The reason the one without the prototype will be changing behavior
3957           // is because of the one with the prototype, so note that so long as
3958           // it's a user-visible declaration. There is one exception to this:
3959           // when the new declaration is a definition without a prototype, the
3960           // old declaration with a prototype is not the cause of the issue,
3961           // and that does not need to be noted because the one with a
3962           // prototype will not change behavior in C2x.
3963           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
3964               !IsWithoutProtoADef)
3965             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
3966         }
3967       }
3968     }
3969 
3970     if (Context.typesAreCompatible(OldQType, NewQType)) {
3971       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3972       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3973       const FunctionProtoType *OldProto = nullptr;
3974       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3975           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3976         // The old declaration provided a function prototype, but the
3977         // new declaration does not. Merge in the prototype.
3978         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3979         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3980         NewQType =
3981             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3982                                     OldProto->getExtProtoInfo());
3983         New->setType(NewQType);
3984         New->setHasInheritedPrototype();
3985 
3986         // Synthesize parameters with the same types.
3987         SmallVector<ParmVarDecl *, 16> Params;
3988         for (const auto &ParamType : OldProto->param_types()) {
3989           ParmVarDecl *Param = ParmVarDecl::Create(
3990               Context, New, SourceLocation(), SourceLocation(), nullptr,
3991               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
3992           Param->setScopeInfo(0, Params.size());
3993           Param->setImplicit();
3994           Params.push_back(Param);
3995         }
3996 
3997         New->setParams(Params);
3998       }
3999 
4000       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4001     }
4002   }
4003 
4004   // Check if the function types are compatible when pointer size address
4005   // spaces are ignored.
4006   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4007     return false;
4008 
4009   // GNU C permits a K&R definition to follow a prototype declaration
4010   // if the declared types of the parameters in the K&R definition
4011   // match the types in the prototype declaration, even when the
4012   // promoted types of the parameters from the K&R definition differ
4013   // from the types in the prototype. GCC then keeps the types from
4014   // the prototype.
4015   //
4016   // If a variadic prototype is followed by a non-variadic K&R definition,
4017   // the K&R definition becomes variadic.  This is sort of an edge case, but
4018   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4019   // C99 6.9.1p8.
4020   if (!getLangOpts().CPlusPlus &&
4021       Old->hasPrototype() && !New->hasPrototype() &&
4022       New->getType()->getAs<FunctionProtoType>() &&
4023       Old->getNumParams() == New->getNumParams()) {
4024     SmallVector<QualType, 16> ArgTypes;
4025     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4026     const FunctionProtoType *OldProto
4027       = Old->getType()->getAs<FunctionProtoType>();
4028     const FunctionProtoType *NewProto
4029       = New->getType()->getAs<FunctionProtoType>();
4030 
4031     // Determine whether this is the GNU C extension.
4032     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4033                                                NewProto->getReturnType());
4034     bool LooseCompatible = !MergedReturn.isNull();
4035     for (unsigned Idx = 0, End = Old->getNumParams();
4036          LooseCompatible && Idx != End; ++Idx) {
4037       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4038       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4039       if (Context.typesAreCompatible(OldParm->getType(),
4040                                      NewProto->getParamType(Idx))) {
4041         ArgTypes.push_back(NewParm->getType());
4042       } else if (Context.typesAreCompatible(OldParm->getType(),
4043                                             NewParm->getType(),
4044                                             /*CompareUnqualified=*/true)) {
4045         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4046                                            NewProto->getParamType(Idx) };
4047         Warnings.push_back(Warn);
4048         ArgTypes.push_back(NewParm->getType());
4049       } else
4050         LooseCompatible = false;
4051     }
4052 
4053     if (LooseCompatible) {
4054       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4055         Diag(Warnings[Warn].NewParm->getLocation(),
4056              diag::ext_param_promoted_not_compatible_with_prototype)
4057           << Warnings[Warn].PromotedType
4058           << Warnings[Warn].OldParm->getType();
4059         if (Warnings[Warn].OldParm->getLocation().isValid())
4060           Diag(Warnings[Warn].OldParm->getLocation(),
4061                diag::note_previous_declaration);
4062       }
4063 
4064       if (MergeTypeWithOld)
4065         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4066                                              OldProto->getExtProtoInfo()));
4067       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4068     }
4069 
4070     // Fall through to diagnose conflicting types.
4071   }
4072 
4073   // A function that has already been declared has been redeclared or
4074   // defined with a different type; show an appropriate diagnostic.
4075 
4076   // If the previous declaration was an implicitly-generated builtin
4077   // declaration, then at the very least we should use a specialized note.
4078   unsigned BuiltinID;
4079   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4080     // If it's actually a library-defined builtin function like 'malloc'
4081     // or 'printf', just warn about the incompatible redeclaration.
4082     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4083       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4084       Diag(OldLocation, diag::note_previous_builtin_declaration)
4085         << Old << Old->getType();
4086       return false;
4087     }
4088 
4089     PrevDiag = diag::note_previous_builtin_declaration;
4090   }
4091 
4092   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4093   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4094   return true;
4095 }
4096 
4097 /// Completes the merge of two function declarations that are
4098 /// known to be compatible.
4099 ///
4100 /// This routine handles the merging of attributes and other
4101 /// properties of function declarations from the old declaration to
4102 /// the new declaration, once we know that New is in fact a
4103 /// redeclaration of Old.
4104 ///
4105 /// \returns false
4106 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4107                                         Scope *S, bool MergeTypeWithOld) {
4108   // Merge the attributes
4109   mergeDeclAttributes(New, Old);
4110 
4111   // Merge "pure" flag.
4112   if (Old->isPure())
4113     New->setPure();
4114 
4115   // Merge "used" flag.
4116   if (Old->getMostRecentDecl()->isUsed(false))
4117     New->setIsUsed();
4118 
4119   // Merge attributes from the parameters.  These can mismatch with K&R
4120   // declarations.
4121   if (New->getNumParams() == Old->getNumParams())
4122       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4123         ParmVarDecl *NewParam = New->getParamDecl(i);
4124         ParmVarDecl *OldParam = Old->getParamDecl(i);
4125         mergeParamDeclAttributes(NewParam, OldParam, *this);
4126         mergeParamDeclTypes(NewParam, OldParam, *this);
4127       }
4128 
4129   if (getLangOpts().CPlusPlus)
4130     return MergeCXXFunctionDecl(New, Old, S);
4131 
4132   // Merge the function types so the we get the composite types for the return
4133   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4134   // was visible.
4135   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4136   if (!Merged.isNull() && MergeTypeWithOld)
4137     New->setType(Merged);
4138 
4139   return false;
4140 }
4141 
4142 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4143                                 ObjCMethodDecl *oldMethod) {
4144   // Merge the attributes, including deprecated/unavailable
4145   AvailabilityMergeKind MergeKind =
4146       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4147           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4148                                      : AMK_ProtocolImplementation)
4149           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4150                                                            : AMK_Override;
4151 
4152   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4153 
4154   // Merge attributes from the parameters.
4155   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4156                                        oe = oldMethod->param_end();
4157   for (ObjCMethodDecl::param_iterator
4158          ni = newMethod->param_begin(), ne = newMethod->param_end();
4159        ni != ne && oi != oe; ++ni, ++oi)
4160     mergeParamDeclAttributes(*ni, *oi, *this);
4161 
4162   CheckObjCMethodOverride(newMethod, oldMethod);
4163 }
4164 
4165 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4166   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4167 
4168   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4169          ? diag::err_redefinition_different_type
4170          : diag::err_redeclaration_different_type)
4171     << New->getDeclName() << New->getType() << Old->getType();
4172 
4173   diag::kind PrevDiag;
4174   SourceLocation OldLocation;
4175   std::tie(PrevDiag, OldLocation)
4176     = getNoteDiagForInvalidRedeclaration(Old, New);
4177   S.Diag(OldLocation, PrevDiag);
4178   New->setInvalidDecl();
4179 }
4180 
4181 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4182 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4183 /// emitting diagnostics as appropriate.
4184 ///
4185 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4186 /// to here in AddInitializerToDecl. We can't check them before the initializer
4187 /// is attached.
4188 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4189                              bool MergeTypeWithOld) {
4190   if (New->isInvalidDecl() || Old->isInvalidDecl())
4191     return;
4192 
4193   QualType MergedT;
4194   if (getLangOpts().CPlusPlus) {
4195     if (New->getType()->isUndeducedType()) {
4196       // We don't know what the new type is until the initializer is attached.
4197       return;
4198     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4199       // These could still be something that needs exception specs checked.
4200       return MergeVarDeclExceptionSpecs(New, Old);
4201     }
4202     // C++ [basic.link]p10:
4203     //   [...] the types specified by all declarations referring to a given
4204     //   object or function shall be identical, except that declarations for an
4205     //   array object can specify array types that differ by the presence or
4206     //   absence of a major array bound (8.3.4).
4207     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4208       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4209       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4210 
4211       // We are merging a variable declaration New into Old. If it has an array
4212       // bound, and that bound differs from Old's bound, we should diagnose the
4213       // mismatch.
4214       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4215         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4216              PrevVD = PrevVD->getPreviousDecl()) {
4217           QualType PrevVDTy = PrevVD->getType();
4218           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4219             continue;
4220 
4221           if (!Context.hasSameType(New->getType(), PrevVDTy))
4222             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4223         }
4224       }
4225 
4226       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4227         if (Context.hasSameType(OldArray->getElementType(),
4228                                 NewArray->getElementType()))
4229           MergedT = New->getType();
4230       }
4231       // FIXME: Check visibility. New is hidden but has a complete type. If New
4232       // has no array bound, it should not inherit one from Old, if Old is not
4233       // visible.
4234       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4235         if (Context.hasSameType(OldArray->getElementType(),
4236                                 NewArray->getElementType()))
4237           MergedT = Old->getType();
4238       }
4239     }
4240     else if (New->getType()->isObjCObjectPointerType() &&
4241                Old->getType()->isObjCObjectPointerType()) {
4242       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4243                                               Old->getType());
4244     }
4245   } else {
4246     // C 6.2.7p2:
4247     //   All declarations that refer to the same object or function shall have
4248     //   compatible type.
4249     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4250   }
4251   if (MergedT.isNull()) {
4252     // It's OK if we couldn't merge types if either type is dependent, for a
4253     // block-scope variable. In other cases (static data members of class
4254     // templates, variable templates, ...), we require the types to be
4255     // equivalent.
4256     // FIXME: The C++ standard doesn't say anything about this.
4257     if ((New->getType()->isDependentType() ||
4258          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4259       // If the old type was dependent, we can't merge with it, so the new type
4260       // becomes dependent for now. We'll reproduce the original type when we
4261       // instantiate the TypeSourceInfo for the variable.
4262       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4263         New->setType(Context.DependentTy);
4264       return;
4265     }
4266     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4267   }
4268 
4269   // Don't actually update the type on the new declaration if the old
4270   // declaration was an extern declaration in a different scope.
4271   if (MergeTypeWithOld)
4272     New->setType(MergedT);
4273 }
4274 
4275 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4276                                   LookupResult &Previous) {
4277   // C11 6.2.7p4:
4278   //   For an identifier with internal or external linkage declared
4279   //   in a scope in which a prior declaration of that identifier is
4280   //   visible, if the prior declaration specifies internal or
4281   //   external linkage, the type of the identifier at the later
4282   //   declaration becomes the composite type.
4283   //
4284   // If the variable isn't visible, we do not merge with its type.
4285   if (Previous.isShadowed())
4286     return false;
4287 
4288   if (S.getLangOpts().CPlusPlus) {
4289     // C++11 [dcl.array]p3:
4290     //   If there is a preceding declaration of the entity in the same
4291     //   scope in which the bound was specified, an omitted array bound
4292     //   is taken to be the same as in that earlier declaration.
4293     return NewVD->isPreviousDeclInSameBlockScope() ||
4294            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4295             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4296   } else {
4297     // If the old declaration was function-local, don't merge with its
4298     // type unless we're in the same function.
4299     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4300            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4301   }
4302 }
4303 
4304 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4305 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4306 /// situation, merging decls or emitting diagnostics as appropriate.
4307 ///
4308 /// Tentative definition rules (C99 6.9.2p2) are checked by
4309 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4310 /// definitions here, since the initializer hasn't been attached.
4311 ///
4312 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4313   // If the new decl is already invalid, don't do any other checking.
4314   if (New->isInvalidDecl())
4315     return;
4316 
4317   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4318     return;
4319 
4320   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4321 
4322   // Verify the old decl was also a variable or variable template.
4323   VarDecl *Old = nullptr;
4324   VarTemplateDecl *OldTemplate = nullptr;
4325   if (Previous.isSingleResult()) {
4326     if (NewTemplate) {
4327       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4328       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4329 
4330       if (auto *Shadow =
4331               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4332         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4333           return New->setInvalidDecl();
4334     } else {
4335       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4336 
4337       if (auto *Shadow =
4338               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4339         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4340           return New->setInvalidDecl();
4341     }
4342   }
4343   if (!Old) {
4344     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4345         << New->getDeclName();
4346     notePreviousDefinition(Previous.getRepresentativeDecl(),
4347                            New->getLocation());
4348     return New->setInvalidDecl();
4349   }
4350 
4351   // If the old declaration was found in an inline namespace and the new
4352   // declaration was qualified, update the DeclContext to match.
4353   adjustDeclContextForDeclaratorDecl(New, Old);
4354 
4355   // Ensure the template parameters are compatible.
4356   if (NewTemplate &&
4357       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4358                                       OldTemplate->getTemplateParameters(),
4359                                       /*Complain=*/true, TPL_TemplateMatch))
4360     return New->setInvalidDecl();
4361 
4362   // C++ [class.mem]p1:
4363   //   A member shall not be declared twice in the member-specification [...]
4364   //
4365   // Here, we need only consider static data members.
4366   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4367     Diag(New->getLocation(), diag::err_duplicate_member)
4368       << New->getIdentifier();
4369     Diag(Old->getLocation(), diag::note_previous_declaration);
4370     New->setInvalidDecl();
4371   }
4372 
4373   mergeDeclAttributes(New, Old);
4374   // Warn if an already-declared variable is made a weak_import in a subsequent
4375   // declaration
4376   if (New->hasAttr<WeakImportAttr>() &&
4377       Old->getStorageClass() == SC_None &&
4378       !Old->hasAttr<WeakImportAttr>()) {
4379     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4380     Diag(Old->getLocation(), diag::note_previous_declaration);
4381     // Remove weak_import attribute on new declaration.
4382     New->dropAttr<WeakImportAttr>();
4383   }
4384 
4385   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4386     if (!Old->hasAttr<InternalLinkageAttr>()) {
4387       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4388           << ILA;
4389       Diag(Old->getLocation(), diag::note_previous_declaration);
4390       New->dropAttr<InternalLinkageAttr>();
4391     }
4392 
4393   // Merge the types.
4394   VarDecl *MostRecent = Old->getMostRecentDecl();
4395   if (MostRecent != Old) {
4396     MergeVarDeclTypes(New, MostRecent,
4397                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4398     if (New->isInvalidDecl())
4399       return;
4400   }
4401 
4402   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4403   if (New->isInvalidDecl())
4404     return;
4405 
4406   diag::kind PrevDiag;
4407   SourceLocation OldLocation;
4408   std::tie(PrevDiag, OldLocation) =
4409       getNoteDiagForInvalidRedeclaration(Old, New);
4410 
4411   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4412   if (New->getStorageClass() == SC_Static &&
4413       !New->isStaticDataMember() &&
4414       Old->hasExternalFormalLinkage()) {
4415     if (getLangOpts().MicrosoftExt) {
4416       Diag(New->getLocation(), diag::ext_static_non_static)
4417           << New->getDeclName();
4418       Diag(OldLocation, PrevDiag);
4419     } else {
4420       Diag(New->getLocation(), diag::err_static_non_static)
4421           << New->getDeclName();
4422       Diag(OldLocation, PrevDiag);
4423       return New->setInvalidDecl();
4424     }
4425   }
4426   // C99 6.2.2p4:
4427   //   For an identifier declared with the storage-class specifier
4428   //   extern in a scope in which a prior declaration of that
4429   //   identifier is visible,23) if the prior declaration specifies
4430   //   internal or external linkage, the linkage of the identifier at
4431   //   the later declaration is the same as the linkage specified at
4432   //   the prior declaration. If no prior declaration is visible, or
4433   //   if the prior declaration specifies no linkage, then the
4434   //   identifier has external linkage.
4435   if (New->hasExternalStorage() && Old->hasLinkage())
4436     /* Okay */;
4437   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4438            !New->isStaticDataMember() &&
4439            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4440     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4441     Diag(OldLocation, PrevDiag);
4442     return New->setInvalidDecl();
4443   }
4444 
4445   // Check if extern is followed by non-extern and vice-versa.
4446   if (New->hasExternalStorage() &&
4447       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4448     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4449     Diag(OldLocation, PrevDiag);
4450     return New->setInvalidDecl();
4451   }
4452   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4453       !New->hasExternalStorage()) {
4454     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4455     Diag(OldLocation, PrevDiag);
4456     return New->setInvalidDecl();
4457   }
4458 
4459   if (CheckRedeclarationInModule(New, Old))
4460     return;
4461 
4462   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4463 
4464   // FIXME: The test for external storage here seems wrong? We still
4465   // need to check for mismatches.
4466   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4467       // Don't complain about out-of-line definitions of static members.
4468       !(Old->getLexicalDeclContext()->isRecord() &&
4469         !New->getLexicalDeclContext()->isRecord())) {
4470     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4471     Diag(OldLocation, PrevDiag);
4472     return New->setInvalidDecl();
4473   }
4474 
4475   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4476     if (VarDecl *Def = Old->getDefinition()) {
4477       // C++1z [dcl.fcn.spec]p4:
4478       //   If the definition of a variable appears in a translation unit before
4479       //   its first declaration as inline, the program is ill-formed.
4480       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4481       Diag(Def->getLocation(), diag::note_previous_definition);
4482     }
4483   }
4484 
4485   // If this redeclaration makes the variable inline, we may need to add it to
4486   // UndefinedButUsed.
4487   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4488       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4489     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4490                                            SourceLocation()));
4491 
4492   if (New->getTLSKind() != Old->getTLSKind()) {
4493     if (!Old->getTLSKind()) {
4494       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4495       Diag(OldLocation, PrevDiag);
4496     } else if (!New->getTLSKind()) {
4497       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4498       Diag(OldLocation, PrevDiag);
4499     } else {
4500       // Do not allow redeclaration to change the variable between requiring
4501       // static and dynamic initialization.
4502       // FIXME: GCC allows this, but uses the TLS keyword on the first
4503       // declaration to determine the kind. Do we need to be compatible here?
4504       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4505         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4506       Diag(OldLocation, PrevDiag);
4507     }
4508   }
4509 
4510   // C++ doesn't have tentative definitions, so go right ahead and check here.
4511   if (getLangOpts().CPlusPlus) {
4512     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4513         Old->getCanonicalDecl()->isConstexpr()) {
4514       // This definition won't be a definition any more once it's been merged.
4515       Diag(New->getLocation(),
4516            diag::warn_deprecated_redundant_constexpr_static_def);
4517     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4518       VarDecl *Def = Old->getDefinition();
4519       if (Def && checkVarDeclRedefinition(Def, New))
4520         return;
4521     }
4522   }
4523 
4524   if (haveIncompatibleLanguageLinkages(Old, New)) {
4525     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4526     Diag(OldLocation, PrevDiag);
4527     New->setInvalidDecl();
4528     return;
4529   }
4530 
4531   // Merge "used" flag.
4532   if (Old->getMostRecentDecl()->isUsed(false))
4533     New->setIsUsed();
4534 
4535   // Keep a chain of previous declarations.
4536   New->setPreviousDecl(Old);
4537   if (NewTemplate)
4538     NewTemplate->setPreviousDecl(OldTemplate);
4539 
4540   // Inherit access appropriately.
4541   New->setAccess(Old->getAccess());
4542   if (NewTemplate)
4543     NewTemplate->setAccess(New->getAccess());
4544 
4545   if (Old->isInline())
4546     New->setImplicitlyInline();
4547 }
4548 
4549 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4550   SourceManager &SrcMgr = getSourceManager();
4551   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4552   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4553   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4554   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4555   auto &HSI = PP.getHeaderSearchInfo();
4556   StringRef HdrFilename =
4557       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4558 
4559   auto noteFromModuleOrInclude = [&](Module *Mod,
4560                                      SourceLocation IncLoc) -> bool {
4561     // Redefinition errors with modules are common with non modular mapped
4562     // headers, example: a non-modular header H in module A that also gets
4563     // included directly in a TU. Pointing twice to the same header/definition
4564     // is confusing, try to get better diagnostics when modules is on.
4565     if (IncLoc.isValid()) {
4566       if (Mod) {
4567         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4568             << HdrFilename.str() << Mod->getFullModuleName();
4569         if (!Mod->DefinitionLoc.isInvalid())
4570           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4571               << Mod->getFullModuleName();
4572       } else {
4573         Diag(IncLoc, diag::note_redefinition_include_same_file)
4574             << HdrFilename.str();
4575       }
4576       return true;
4577     }
4578 
4579     return false;
4580   };
4581 
4582   // Is it the same file and same offset? Provide more information on why
4583   // this leads to a redefinition error.
4584   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4585     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4586     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4587     bool EmittedDiag =
4588         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4589     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4590 
4591     // If the header has no guards, emit a note suggesting one.
4592     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4593       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4594 
4595     if (EmittedDiag)
4596       return;
4597   }
4598 
4599   // Redefinition coming from different files or couldn't do better above.
4600   if (Old->getLocation().isValid())
4601     Diag(Old->getLocation(), diag::note_previous_definition);
4602 }
4603 
4604 /// We've just determined that \p Old and \p New both appear to be definitions
4605 /// of the same variable. Either diagnose or fix the problem.
4606 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4607   if (!hasVisibleDefinition(Old) &&
4608       (New->getFormalLinkage() == InternalLinkage ||
4609        New->isInline() ||
4610        New->getDescribedVarTemplate() ||
4611        New->getNumTemplateParameterLists() ||
4612        New->getDeclContext()->isDependentContext())) {
4613     // The previous definition is hidden, and multiple definitions are
4614     // permitted (in separate TUs). Demote this to a declaration.
4615     New->demoteThisDefinitionToDeclaration();
4616 
4617     // Make the canonical definition visible.
4618     if (auto *OldTD = Old->getDescribedVarTemplate())
4619       makeMergedDefinitionVisible(OldTD);
4620     makeMergedDefinitionVisible(Old);
4621     return false;
4622   } else {
4623     Diag(New->getLocation(), diag::err_redefinition) << New;
4624     notePreviousDefinition(Old, New->getLocation());
4625     New->setInvalidDecl();
4626     return true;
4627   }
4628 }
4629 
4630 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4631 /// no declarator (e.g. "struct foo;") is parsed.
4632 Decl *
4633 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4634                                  RecordDecl *&AnonRecord) {
4635   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4636                                     AnonRecord);
4637 }
4638 
4639 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4640 // disambiguate entities defined in different scopes.
4641 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4642 // compatibility.
4643 // We will pick our mangling number depending on which version of MSVC is being
4644 // targeted.
4645 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4646   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4647              ? S->getMSCurManglingNumber()
4648              : S->getMSLastManglingNumber();
4649 }
4650 
4651 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4652   if (!Context.getLangOpts().CPlusPlus)
4653     return;
4654 
4655   if (isa<CXXRecordDecl>(Tag->getParent())) {
4656     // If this tag is the direct child of a class, number it if
4657     // it is anonymous.
4658     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4659       return;
4660     MangleNumberingContext &MCtx =
4661         Context.getManglingNumberContext(Tag->getParent());
4662     Context.setManglingNumber(
4663         Tag, MCtx.getManglingNumber(
4664                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4665     return;
4666   }
4667 
4668   // If this tag isn't a direct child of a class, number it if it is local.
4669   MangleNumberingContext *MCtx;
4670   Decl *ManglingContextDecl;
4671   std::tie(MCtx, ManglingContextDecl) =
4672       getCurrentMangleNumberContext(Tag->getDeclContext());
4673   if (MCtx) {
4674     Context.setManglingNumber(
4675         Tag, MCtx->getManglingNumber(
4676                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4677   }
4678 }
4679 
4680 namespace {
4681 struct NonCLikeKind {
4682   enum {
4683     None,
4684     BaseClass,
4685     DefaultMemberInit,
4686     Lambda,
4687     Friend,
4688     OtherMember,
4689     Invalid,
4690   } Kind = None;
4691   SourceRange Range;
4692 
4693   explicit operator bool() { return Kind != None; }
4694 };
4695 }
4696 
4697 /// Determine whether a class is C-like, according to the rules of C++
4698 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4699 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4700   if (RD->isInvalidDecl())
4701     return {NonCLikeKind::Invalid, {}};
4702 
4703   // C++ [dcl.typedef]p9: [P1766R1]
4704   //   An unnamed class with a typedef name for linkage purposes shall not
4705   //
4706   //    -- have any base classes
4707   if (RD->getNumBases())
4708     return {NonCLikeKind::BaseClass,
4709             SourceRange(RD->bases_begin()->getBeginLoc(),
4710                         RD->bases_end()[-1].getEndLoc())};
4711   bool Invalid = false;
4712   for (Decl *D : RD->decls()) {
4713     // Don't complain about things we already diagnosed.
4714     if (D->isInvalidDecl()) {
4715       Invalid = true;
4716       continue;
4717     }
4718 
4719     //  -- have any [...] default member initializers
4720     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4721       if (FD->hasInClassInitializer()) {
4722         auto *Init = FD->getInClassInitializer();
4723         return {NonCLikeKind::DefaultMemberInit,
4724                 Init ? Init->getSourceRange() : D->getSourceRange()};
4725       }
4726       continue;
4727     }
4728 
4729     // FIXME: We don't allow friend declarations. This violates the wording of
4730     // P1766, but not the intent.
4731     if (isa<FriendDecl>(D))
4732       return {NonCLikeKind::Friend, D->getSourceRange()};
4733 
4734     //  -- declare any members other than non-static data members, member
4735     //     enumerations, or member classes,
4736     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4737         isa<EnumDecl>(D))
4738       continue;
4739     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4740     if (!MemberRD) {
4741       if (D->isImplicit())
4742         continue;
4743       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4744     }
4745 
4746     //  -- contain a lambda-expression,
4747     if (MemberRD->isLambda())
4748       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4749 
4750     //  and all member classes shall also satisfy these requirements
4751     //  (recursively).
4752     if (MemberRD->isThisDeclarationADefinition()) {
4753       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4754         return Kind;
4755     }
4756   }
4757 
4758   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4759 }
4760 
4761 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4762                                         TypedefNameDecl *NewTD) {
4763   if (TagFromDeclSpec->isInvalidDecl())
4764     return;
4765 
4766   // Do nothing if the tag already has a name for linkage purposes.
4767   if (TagFromDeclSpec->hasNameForLinkage())
4768     return;
4769 
4770   // A well-formed anonymous tag must always be a TUK_Definition.
4771   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4772 
4773   // The type must match the tag exactly;  no qualifiers allowed.
4774   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4775                            Context.getTagDeclType(TagFromDeclSpec))) {
4776     if (getLangOpts().CPlusPlus)
4777       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4778     return;
4779   }
4780 
4781   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4782   //   An unnamed class with a typedef name for linkage purposes shall [be
4783   //   C-like].
4784   //
4785   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4786   // shouldn't happen, but there are constructs that the language rule doesn't
4787   // disallow for which we can't reasonably avoid computing linkage early.
4788   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4789   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4790                              : NonCLikeKind();
4791   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4792   if (NonCLike || ChangesLinkage) {
4793     if (NonCLike.Kind == NonCLikeKind::Invalid)
4794       return;
4795 
4796     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4797     if (ChangesLinkage) {
4798       // If the linkage changes, we can't accept this as an extension.
4799       if (NonCLike.Kind == NonCLikeKind::None)
4800         DiagID = diag::err_typedef_changes_linkage;
4801       else
4802         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4803     }
4804 
4805     SourceLocation FixitLoc =
4806         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4807     llvm::SmallString<40> TextToInsert;
4808     TextToInsert += ' ';
4809     TextToInsert += NewTD->getIdentifier()->getName();
4810 
4811     Diag(FixitLoc, DiagID)
4812       << isa<TypeAliasDecl>(NewTD)
4813       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4814     if (NonCLike.Kind != NonCLikeKind::None) {
4815       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4816         << NonCLike.Kind - 1 << NonCLike.Range;
4817     }
4818     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4819       << NewTD << isa<TypeAliasDecl>(NewTD);
4820 
4821     if (ChangesLinkage)
4822       return;
4823   }
4824 
4825   // Otherwise, set this as the anon-decl typedef for the tag.
4826   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4827 }
4828 
4829 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4830   switch (T) {
4831   case DeclSpec::TST_class:
4832     return 0;
4833   case DeclSpec::TST_struct:
4834     return 1;
4835   case DeclSpec::TST_interface:
4836     return 2;
4837   case DeclSpec::TST_union:
4838     return 3;
4839   case DeclSpec::TST_enum:
4840     return 4;
4841   default:
4842     llvm_unreachable("unexpected type specifier");
4843   }
4844 }
4845 
4846 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4847 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4848 /// parameters to cope with template friend declarations.
4849 Decl *
4850 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4851                                  MultiTemplateParamsArg TemplateParams,
4852                                  bool IsExplicitInstantiation,
4853                                  RecordDecl *&AnonRecord) {
4854   Decl *TagD = nullptr;
4855   TagDecl *Tag = nullptr;
4856   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4857       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4858       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4859       DS.getTypeSpecType() == DeclSpec::TST_union ||
4860       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4861     TagD = DS.getRepAsDecl();
4862 
4863     if (!TagD) // We probably had an error
4864       return nullptr;
4865 
4866     // Note that the above type specs guarantee that the
4867     // type rep is a Decl, whereas in many of the others
4868     // it's a Type.
4869     if (isa<TagDecl>(TagD))
4870       Tag = cast<TagDecl>(TagD);
4871     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4872       Tag = CTD->getTemplatedDecl();
4873   }
4874 
4875   if (Tag) {
4876     handleTagNumbering(Tag, S);
4877     Tag->setFreeStanding();
4878     if (Tag->isInvalidDecl())
4879       return Tag;
4880   }
4881 
4882   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4883     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4884     // or incomplete types shall not be restrict-qualified."
4885     if (TypeQuals & DeclSpec::TQ_restrict)
4886       Diag(DS.getRestrictSpecLoc(),
4887            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4888            << DS.getSourceRange();
4889   }
4890 
4891   if (DS.isInlineSpecified())
4892     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4893         << getLangOpts().CPlusPlus17;
4894 
4895   if (DS.hasConstexprSpecifier()) {
4896     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4897     // and definitions of functions and variables.
4898     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4899     // the declaration of a function or function template
4900     if (Tag)
4901       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4902           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4903           << static_cast<int>(DS.getConstexprSpecifier());
4904     else
4905       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4906           << static_cast<int>(DS.getConstexprSpecifier());
4907     // Don't emit warnings after this error.
4908     return TagD;
4909   }
4910 
4911   DiagnoseFunctionSpecifiers(DS);
4912 
4913   if (DS.isFriendSpecified()) {
4914     // If we're dealing with a decl but not a TagDecl, assume that
4915     // whatever routines created it handled the friendship aspect.
4916     if (TagD && !Tag)
4917       return nullptr;
4918     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4919   }
4920 
4921   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4922   bool IsExplicitSpecialization =
4923     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4924   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4925       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4926       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4927     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4928     // nested-name-specifier unless it is an explicit instantiation
4929     // or an explicit specialization.
4930     //
4931     // FIXME: We allow class template partial specializations here too, per the
4932     // obvious intent of DR1819.
4933     //
4934     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4935     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4936         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4937     return nullptr;
4938   }
4939 
4940   // Track whether this decl-specifier declares anything.
4941   bool DeclaresAnything = true;
4942 
4943   // Handle anonymous struct definitions.
4944   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4945     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4946         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4947       if (getLangOpts().CPlusPlus ||
4948           Record->getDeclContext()->isRecord()) {
4949         // If CurContext is a DeclContext that can contain statements,
4950         // RecursiveASTVisitor won't visit the decls that
4951         // BuildAnonymousStructOrUnion() will put into CurContext.
4952         // Also store them here so that they can be part of the
4953         // DeclStmt that gets created in this case.
4954         // FIXME: Also return the IndirectFieldDecls created by
4955         // BuildAnonymousStructOr union, for the same reason?
4956         if (CurContext->isFunctionOrMethod())
4957           AnonRecord = Record;
4958         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4959                                            Context.getPrintingPolicy());
4960       }
4961 
4962       DeclaresAnything = false;
4963     }
4964   }
4965 
4966   // C11 6.7.2.1p2:
4967   //   A struct-declaration that does not declare an anonymous structure or
4968   //   anonymous union shall contain a struct-declarator-list.
4969   //
4970   // This rule also existed in C89 and C99; the grammar for struct-declaration
4971   // did not permit a struct-declaration without a struct-declarator-list.
4972   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4973       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4974     // Check for Microsoft C extension: anonymous struct/union member.
4975     // Handle 2 kinds of anonymous struct/union:
4976     //   struct STRUCT;
4977     //   union UNION;
4978     // and
4979     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4980     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4981     if ((Tag && Tag->getDeclName()) ||
4982         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4983       RecordDecl *Record = nullptr;
4984       if (Tag)
4985         Record = dyn_cast<RecordDecl>(Tag);
4986       else if (const RecordType *RT =
4987                    DS.getRepAsType().get()->getAsStructureType())
4988         Record = RT->getDecl();
4989       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4990         Record = UT->getDecl();
4991 
4992       if (Record && getLangOpts().MicrosoftExt) {
4993         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4994             << Record->isUnion() << DS.getSourceRange();
4995         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4996       }
4997 
4998       DeclaresAnything = false;
4999     }
5000   }
5001 
5002   // Skip all the checks below if we have a type error.
5003   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5004       (TagD && TagD->isInvalidDecl()))
5005     return TagD;
5006 
5007   if (getLangOpts().CPlusPlus &&
5008       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5009     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5010       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5011           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5012         DeclaresAnything = false;
5013 
5014   if (!DS.isMissingDeclaratorOk()) {
5015     // Customize diagnostic for a typedef missing a name.
5016     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5017       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5018           << DS.getSourceRange();
5019     else
5020       DeclaresAnything = false;
5021   }
5022 
5023   if (DS.isModulePrivateSpecified() &&
5024       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5025     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5026       << Tag->getTagKind()
5027       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5028 
5029   ActOnDocumentableDecl(TagD);
5030 
5031   // C 6.7/2:
5032   //   A declaration [...] shall declare at least a declarator [...], a tag,
5033   //   or the members of an enumeration.
5034   // C++ [dcl.dcl]p3:
5035   //   [If there are no declarators], and except for the declaration of an
5036   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5037   //   names into the program, or shall redeclare a name introduced by a
5038   //   previous declaration.
5039   if (!DeclaresAnything) {
5040     // In C, we allow this as a (popular) extension / bug. Don't bother
5041     // producing further diagnostics for redundant qualifiers after this.
5042     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5043                                ? diag::err_no_declarators
5044                                : diag::ext_no_declarators)
5045         << DS.getSourceRange();
5046     return TagD;
5047   }
5048 
5049   // C++ [dcl.stc]p1:
5050   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5051   //   init-declarator-list of the declaration shall not be empty.
5052   // C++ [dcl.fct.spec]p1:
5053   //   If a cv-qualifier appears in a decl-specifier-seq, the
5054   //   init-declarator-list of the declaration shall not be empty.
5055   //
5056   // Spurious qualifiers here appear to be valid in C.
5057   unsigned DiagID = diag::warn_standalone_specifier;
5058   if (getLangOpts().CPlusPlus)
5059     DiagID = diag::ext_standalone_specifier;
5060 
5061   // Note that a linkage-specification sets a storage class, but
5062   // 'extern "C" struct foo;' is actually valid and not theoretically
5063   // useless.
5064   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5065     if (SCS == DeclSpec::SCS_mutable)
5066       // Since mutable is not a viable storage class specifier in C, there is
5067       // no reason to treat it as an extension. Instead, diagnose as an error.
5068       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5069     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5070       Diag(DS.getStorageClassSpecLoc(), DiagID)
5071         << DeclSpec::getSpecifierName(SCS);
5072   }
5073 
5074   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5075     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5076       << DeclSpec::getSpecifierName(TSCS);
5077   if (DS.getTypeQualifiers()) {
5078     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5079       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5080     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5081       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5082     // Restrict is covered above.
5083     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5084       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5085     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5086       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5087   }
5088 
5089   // Warn about ignored type attributes, for example:
5090   // __attribute__((aligned)) struct A;
5091   // Attributes should be placed after tag to apply to type declaration.
5092   if (!DS.getAttributes().empty()) {
5093     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5094     if (TypeSpecType == DeclSpec::TST_class ||
5095         TypeSpecType == DeclSpec::TST_struct ||
5096         TypeSpecType == DeclSpec::TST_interface ||
5097         TypeSpecType == DeclSpec::TST_union ||
5098         TypeSpecType == DeclSpec::TST_enum) {
5099       for (const ParsedAttr &AL : DS.getAttributes())
5100         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5101             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5102     }
5103   }
5104 
5105   return TagD;
5106 }
5107 
5108 /// We are trying to inject an anonymous member into the given scope;
5109 /// check if there's an existing declaration that can't be overloaded.
5110 ///
5111 /// \return true if this is a forbidden redeclaration
5112 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5113                                          Scope *S,
5114                                          DeclContext *Owner,
5115                                          DeclarationName Name,
5116                                          SourceLocation NameLoc,
5117                                          bool IsUnion) {
5118   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5119                  Sema::ForVisibleRedeclaration);
5120   if (!SemaRef.LookupName(R, S)) return false;
5121 
5122   // Pick a representative declaration.
5123   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5124   assert(PrevDecl && "Expected a non-null Decl");
5125 
5126   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5127     return false;
5128 
5129   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5130     << IsUnion << Name;
5131   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5132 
5133   return true;
5134 }
5135 
5136 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5137 /// anonymous struct or union AnonRecord into the owning context Owner
5138 /// and scope S. This routine will be invoked just after we realize
5139 /// that an unnamed union or struct is actually an anonymous union or
5140 /// struct, e.g.,
5141 ///
5142 /// @code
5143 /// union {
5144 ///   int i;
5145 ///   float f;
5146 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5147 ///    // f into the surrounding scope.x
5148 /// @endcode
5149 ///
5150 /// This routine is recursive, injecting the names of nested anonymous
5151 /// structs/unions into the owning context and scope as well.
5152 static bool
5153 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5154                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5155                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5156   bool Invalid = false;
5157 
5158   // Look every FieldDecl and IndirectFieldDecl with a name.
5159   for (auto *D : AnonRecord->decls()) {
5160     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5161         cast<NamedDecl>(D)->getDeclName()) {
5162       ValueDecl *VD = cast<ValueDecl>(D);
5163       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5164                                        VD->getLocation(),
5165                                        AnonRecord->isUnion())) {
5166         // C++ [class.union]p2:
5167         //   The names of the members of an anonymous union shall be
5168         //   distinct from the names of any other entity in the
5169         //   scope in which the anonymous union is declared.
5170         Invalid = true;
5171       } else {
5172         // C++ [class.union]p2:
5173         //   For the purpose of name lookup, after the anonymous union
5174         //   definition, the members of the anonymous union are
5175         //   considered to have been defined in the scope in which the
5176         //   anonymous union is declared.
5177         unsigned OldChainingSize = Chaining.size();
5178         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5179           Chaining.append(IF->chain_begin(), IF->chain_end());
5180         else
5181           Chaining.push_back(VD);
5182 
5183         assert(Chaining.size() >= 2);
5184         NamedDecl **NamedChain =
5185           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5186         for (unsigned i = 0; i < Chaining.size(); i++)
5187           NamedChain[i] = Chaining[i];
5188 
5189         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5190             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5191             VD->getType(), {NamedChain, Chaining.size()});
5192 
5193         for (const auto *Attr : VD->attrs())
5194           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5195 
5196         IndirectField->setAccess(AS);
5197         IndirectField->setImplicit();
5198         SemaRef.PushOnScopeChains(IndirectField, S);
5199 
5200         // That includes picking up the appropriate access specifier.
5201         if (AS != AS_none) IndirectField->setAccess(AS);
5202 
5203         Chaining.resize(OldChainingSize);
5204       }
5205     }
5206   }
5207 
5208   return Invalid;
5209 }
5210 
5211 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5212 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5213 /// illegal input values are mapped to SC_None.
5214 static StorageClass
5215 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5216   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5217   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5218          "Parser allowed 'typedef' as storage class VarDecl.");
5219   switch (StorageClassSpec) {
5220   case DeclSpec::SCS_unspecified:    return SC_None;
5221   case DeclSpec::SCS_extern:
5222     if (DS.isExternInLinkageSpec())
5223       return SC_None;
5224     return SC_Extern;
5225   case DeclSpec::SCS_static:         return SC_Static;
5226   case DeclSpec::SCS_auto:           return SC_Auto;
5227   case DeclSpec::SCS_register:       return SC_Register;
5228   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5229     // Illegal SCSs map to None: error reporting is up to the caller.
5230   case DeclSpec::SCS_mutable:        // Fall through.
5231   case DeclSpec::SCS_typedef:        return SC_None;
5232   }
5233   llvm_unreachable("unknown storage class specifier");
5234 }
5235 
5236 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5237   assert(Record->hasInClassInitializer());
5238 
5239   for (const auto *I : Record->decls()) {
5240     const auto *FD = dyn_cast<FieldDecl>(I);
5241     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5242       FD = IFD->getAnonField();
5243     if (FD && FD->hasInClassInitializer())
5244       return FD->getLocation();
5245   }
5246 
5247   llvm_unreachable("couldn't find in-class initializer");
5248 }
5249 
5250 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5251                                       SourceLocation DefaultInitLoc) {
5252   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5253     return;
5254 
5255   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5256   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5257 }
5258 
5259 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5260                                       CXXRecordDecl *AnonUnion) {
5261   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5262     return;
5263 
5264   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5265 }
5266 
5267 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5268 /// anonymous structure or union. Anonymous unions are a C++ feature
5269 /// (C++ [class.union]) and a C11 feature; anonymous structures
5270 /// are a C11 feature and GNU C++ extension.
5271 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5272                                         AccessSpecifier AS,
5273                                         RecordDecl *Record,
5274                                         const PrintingPolicy &Policy) {
5275   DeclContext *Owner = Record->getDeclContext();
5276 
5277   // Diagnose whether this anonymous struct/union is an extension.
5278   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5279     Diag(Record->getLocation(), diag::ext_anonymous_union);
5280   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5281     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5282   else if (!Record->isUnion() && !getLangOpts().C11)
5283     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5284 
5285   // C and C++ require different kinds of checks for anonymous
5286   // structs/unions.
5287   bool Invalid = false;
5288   if (getLangOpts().CPlusPlus) {
5289     const char *PrevSpec = nullptr;
5290     if (Record->isUnion()) {
5291       // C++ [class.union]p6:
5292       // C++17 [class.union.anon]p2:
5293       //   Anonymous unions declared in a named namespace or in the
5294       //   global namespace shall be declared static.
5295       unsigned DiagID;
5296       DeclContext *OwnerScope = Owner->getRedeclContext();
5297       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5298           (OwnerScope->isTranslationUnit() ||
5299            (OwnerScope->isNamespace() &&
5300             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5301         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5302           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5303 
5304         // Recover by adding 'static'.
5305         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5306                                PrevSpec, DiagID, Policy);
5307       }
5308       // C++ [class.union]p6:
5309       //   A storage class is not allowed in a declaration of an
5310       //   anonymous union in a class scope.
5311       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5312                isa<RecordDecl>(Owner)) {
5313         Diag(DS.getStorageClassSpecLoc(),
5314              diag::err_anonymous_union_with_storage_spec)
5315           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5316 
5317         // Recover by removing the storage specifier.
5318         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5319                                SourceLocation(),
5320                                PrevSpec, DiagID, Context.getPrintingPolicy());
5321       }
5322     }
5323 
5324     // Ignore const/volatile/restrict qualifiers.
5325     if (DS.getTypeQualifiers()) {
5326       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5327         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5328           << Record->isUnion() << "const"
5329           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5330       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5331         Diag(DS.getVolatileSpecLoc(),
5332              diag::ext_anonymous_struct_union_qualified)
5333           << Record->isUnion() << "volatile"
5334           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5335       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5336         Diag(DS.getRestrictSpecLoc(),
5337              diag::ext_anonymous_struct_union_qualified)
5338           << Record->isUnion() << "restrict"
5339           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5340       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5341         Diag(DS.getAtomicSpecLoc(),
5342              diag::ext_anonymous_struct_union_qualified)
5343           << Record->isUnion() << "_Atomic"
5344           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5345       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5346         Diag(DS.getUnalignedSpecLoc(),
5347              diag::ext_anonymous_struct_union_qualified)
5348           << Record->isUnion() << "__unaligned"
5349           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5350 
5351       DS.ClearTypeQualifiers();
5352     }
5353 
5354     // C++ [class.union]p2:
5355     //   The member-specification of an anonymous union shall only
5356     //   define non-static data members. [Note: nested types and
5357     //   functions cannot be declared within an anonymous union. ]
5358     for (auto *Mem : Record->decls()) {
5359       // Ignore invalid declarations; we already diagnosed them.
5360       if (Mem->isInvalidDecl())
5361         continue;
5362 
5363       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5364         // C++ [class.union]p3:
5365         //   An anonymous union shall not have private or protected
5366         //   members (clause 11).
5367         assert(FD->getAccess() != AS_none);
5368         if (FD->getAccess() != AS_public) {
5369           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5370             << Record->isUnion() << (FD->getAccess() == AS_protected);
5371           Invalid = true;
5372         }
5373 
5374         // C++ [class.union]p1
5375         //   An object of a class with a non-trivial constructor, a non-trivial
5376         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5377         //   assignment operator cannot be a member of a union, nor can an
5378         //   array of such objects.
5379         if (CheckNontrivialField(FD))
5380           Invalid = true;
5381       } else if (Mem->isImplicit()) {
5382         // Any implicit members are fine.
5383       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5384         // This is a type that showed up in an
5385         // elaborated-type-specifier inside the anonymous struct or
5386         // union, but which actually declares a type outside of the
5387         // anonymous struct or union. It's okay.
5388       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5389         if (!MemRecord->isAnonymousStructOrUnion() &&
5390             MemRecord->getDeclName()) {
5391           // Visual C++ allows type definition in anonymous struct or union.
5392           if (getLangOpts().MicrosoftExt)
5393             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5394               << Record->isUnion();
5395           else {
5396             // This is a nested type declaration.
5397             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5398               << Record->isUnion();
5399             Invalid = true;
5400           }
5401         } else {
5402           // This is an anonymous type definition within another anonymous type.
5403           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5404           // not part of standard C++.
5405           Diag(MemRecord->getLocation(),
5406                diag::ext_anonymous_record_with_anonymous_type)
5407             << Record->isUnion();
5408         }
5409       } else if (isa<AccessSpecDecl>(Mem)) {
5410         // Any access specifier is fine.
5411       } else if (isa<StaticAssertDecl>(Mem)) {
5412         // In C++1z, static_assert declarations are also fine.
5413       } else {
5414         // We have something that isn't a non-static data
5415         // member. Complain about it.
5416         unsigned DK = diag::err_anonymous_record_bad_member;
5417         if (isa<TypeDecl>(Mem))
5418           DK = diag::err_anonymous_record_with_type;
5419         else if (isa<FunctionDecl>(Mem))
5420           DK = diag::err_anonymous_record_with_function;
5421         else if (isa<VarDecl>(Mem))
5422           DK = diag::err_anonymous_record_with_static;
5423 
5424         // Visual C++ allows type definition in anonymous struct or union.
5425         if (getLangOpts().MicrosoftExt &&
5426             DK == diag::err_anonymous_record_with_type)
5427           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5428             << Record->isUnion();
5429         else {
5430           Diag(Mem->getLocation(), DK) << Record->isUnion();
5431           Invalid = true;
5432         }
5433       }
5434     }
5435 
5436     // C++11 [class.union]p8 (DR1460):
5437     //   At most one variant member of a union may have a
5438     //   brace-or-equal-initializer.
5439     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5440         Owner->isRecord())
5441       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5442                                 cast<CXXRecordDecl>(Record));
5443   }
5444 
5445   if (!Record->isUnion() && !Owner->isRecord()) {
5446     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5447       << getLangOpts().CPlusPlus;
5448     Invalid = true;
5449   }
5450 
5451   // C++ [dcl.dcl]p3:
5452   //   [If there are no declarators], and except for the declaration of an
5453   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5454   //   names into the program
5455   // C++ [class.mem]p2:
5456   //   each such member-declaration shall either declare at least one member
5457   //   name of the class or declare at least one unnamed bit-field
5458   //
5459   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5460   if (getLangOpts().CPlusPlus && Record->field_empty())
5461     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5462 
5463   // Mock up a declarator.
5464   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5465   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5466   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5467 
5468   // Create a declaration for this anonymous struct/union.
5469   NamedDecl *Anon = nullptr;
5470   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5471     Anon = FieldDecl::Create(
5472         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5473         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5474         /*BitWidth=*/nullptr, /*Mutable=*/false,
5475         /*InitStyle=*/ICIS_NoInit);
5476     Anon->setAccess(AS);
5477     ProcessDeclAttributes(S, Anon, Dc);
5478 
5479     if (getLangOpts().CPlusPlus)
5480       FieldCollector->Add(cast<FieldDecl>(Anon));
5481   } else {
5482     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5483     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5484     if (SCSpec == DeclSpec::SCS_mutable) {
5485       // mutable can only appear on non-static class members, so it's always
5486       // an error here
5487       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5488       Invalid = true;
5489       SC = SC_None;
5490     }
5491 
5492     assert(DS.getAttributes().empty() && "No attribute expected");
5493     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5494                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5495                            Context.getTypeDeclType(Record), TInfo, SC);
5496 
5497     // Default-initialize the implicit variable. This initialization will be
5498     // trivial in almost all cases, except if a union member has an in-class
5499     // initializer:
5500     //   union { int n = 0; };
5501     ActOnUninitializedDecl(Anon);
5502   }
5503   Anon->setImplicit();
5504 
5505   // Mark this as an anonymous struct/union type.
5506   Record->setAnonymousStructOrUnion(true);
5507 
5508   // Add the anonymous struct/union object to the current
5509   // context. We'll be referencing this object when we refer to one of
5510   // its members.
5511   Owner->addDecl(Anon);
5512 
5513   // Inject the members of the anonymous struct/union into the owning
5514   // context and into the identifier resolver chain for name lookup
5515   // purposes.
5516   SmallVector<NamedDecl*, 2> Chain;
5517   Chain.push_back(Anon);
5518 
5519   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5520     Invalid = true;
5521 
5522   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5523     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5524       MangleNumberingContext *MCtx;
5525       Decl *ManglingContextDecl;
5526       std::tie(MCtx, ManglingContextDecl) =
5527           getCurrentMangleNumberContext(NewVD->getDeclContext());
5528       if (MCtx) {
5529         Context.setManglingNumber(
5530             NewVD, MCtx->getManglingNumber(
5531                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5532         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5533       }
5534     }
5535   }
5536 
5537   if (Invalid)
5538     Anon->setInvalidDecl();
5539 
5540   return Anon;
5541 }
5542 
5543 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5544 /// Microsoft C anonymous structure.
5545 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5546 /// Example:
5547 ///
5548 /// struct A { int a; };
5549 /// struct B { struct A; int b; };
5550 ///
5551 /// void foo() {
5552 ///   B var;
5553 ///   var.a = 3;
5554 /// }
5555 ///
5556 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5557                                            RecordDecl *Record) {
5558   assert(Record && "expected a record!");
5559 
5560   // Mock up a declarator.
5561   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5562   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5563   assert(TInfo && "couldn't build declarator info for anonymous struct");
5564 
5565   auto *ParentDecl = cast<RecordDecl>(CurContext);
5566   QualType RecTy = Context.getTypeDeclType(Record);
5567 
5568   // Create a declaration for this anonymous struct.
5569   NamedDecl *Anon =
5570       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5571                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5572                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5573                         /*InitStyle=*/ICIS_NoInit);
5574   Anon->setImplicit();
5575 
5576   // Add the anonymous struct object to the current context.
5577   CurContext->addDecl(Anon);
5578 
5579   // Inject the members of the anonymous struct into the current
5580   // context and into the identifier resolver chain for name lookup
5581   // purposes.
5582   SmallVector<NamedDecl*, 2> Chain;
5583   Chain.push_back(Anon);
5584 
5585   RecordDecl *RecordDef = Record->getDefinition();
5586   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5587                                diag::err_field_incomplete_or_sizeless) ||
5588       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5589                                           AS_none, Chain)) {
5590     Anon->setInvalidDecl();
5591     ParentDecl->setInvalidDecl();
5592   }
5593 
5594   return Anon;
5595 }
5596 
5597 /// GetNameForDeclarator - Determine the full declaration name for the
5598 /// given Declarator.
5599 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5600   return GetNameFromUnqualifiedId(D.getName());
5601 }
5602 
5603 /// Retrieves the declaration name from a parsed unqualified-id.
5604 DeclarationNameInfo
5605 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5606   DeclarationNameInfo NameInfo;
5607   NameInfo.setLoc(Name.StartLocation);
5608 
5609   switch (Name.getKind()) {
5610 
5611   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5612   case UnqualifiedIdKind::IK_Identifier:
5613     NameInfo.setName(Name.Identifier);
5614     return NameInfo;
5615 
5616   case UnqualifiedIdKind::IK_DeductionGuideName: {
5617     // C++ [temp.deduct.guide]p3:
5618     //   The simple-template-id shall name a class template specialization.
5619     //   The template-name shall be the same identifier as the template-name
5620     //   of the simple-template-id.
5621     // These together intend to imply that the template-name shall name a
5622     // class template.
5623     // FIXME: template<typename T> struct X {};
5624     //        template<typename T> using Y = X<T>;
5625     //        Y(int) -> Y<int>;
5626     //   satisfies these rules but does not name a class template.
5627     TemplateName TN = Name.TemplateName.get().get();
5628     auto *Template = TN.getAsTemplateDecl();
5629     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5630       Diag(Name.StartLocation,
5631            diag::err_deduction_guide_name_not_class_template)
5632         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5633       if (Template)
5634         Diag(Template->getLocation(), diag::note_template_decl_here);
5635       return DeclarationNameInfo();
5636     }
5637 
5638     NameInfo.setName(
5639         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5640     return NameInfo;
5641   }
5642 
5643   case UnqualifiedIdKind::IK_OperatorFunctionId:
5644     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5645                                            Name.OperatorFunctionId.Operator));
5646     NameInfo.setCXXOperatorNameRange(SourceRange(
5647         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5648     return NameInfo;
5649 
5650   case UnqualifiedIdKind::IK_LiteralOperatorId:
5651     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5652                                                            Name.Identifier));
5653     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5654     return NameInfo;
5655 
5656   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5657     TypeSourceInfo *TInfo;
5658     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5659     if (Ty.isNull())
5660       return DeclarationNameInfo();
5661     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5662                                                Context.getCanonicalType(Ty)));
5663     NameInfo.setNamedTypeInfo(TInfo);
5664     return NameInfo;
5665   }
5666 
5667   case UnqualifiedIdKind::IK_ConstructorName: {
5668     TypeSourceInfo *TInfo;
5669     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5670     if (Ty.isNull())
5671       return DeclarationNameInfo();
5672     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5673                                               Context.getCanonicalType(Ty)));
5674     NameInfo.setNamedTypeInfo(TInfo);
5675     return NameInfo;
5676   }
5677 
5678   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5679     // In well-formed code, we can only have a constructor
5680     // template-id that refers to the current context, so go there
5681     // to find the actual type being constructed.
5682     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5683     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5684       return DeclarationNameInfo();
5685 
5686     // Determine the type of the class being constructed.
5687     QualType CurClassType = Context.getTypeDeclType(CurClass);
5688 
5689     // FIXME: Check two things: that the template-id names the same type as
5690     // CurClassType, and that the template-id does not occur when the name
5691     // was qualified.
5692 
5693     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5694                                     Context.getCanonicalType(CurClassType)));
5695     // FIXME: should we retrieve TypeSourceInfo?
5696     NameInfo.setNamedTypeInfo(nullptr);
5697     return NameInfo;
5698   }
5699 
5700   case UnqualifiedIdKind::IK_DestructorName: {
5701     TypeSourceInfo *TInfo;
5702     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5703     if (Ty.isNull())
5704       return DeclarationNameInfo();
5705     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5706                                               Context.getCanonicalType(Ty)));
5707     NameInfo.setNamedTypeInfo(TInfo);
5708     return NameInfo;
5709   }
5710 
5711   case UnqualifiedIdKind::IK_TemplateId: {
5712     TemplateName TName = Name.TemplateId->Template.get();
5713     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5714     return Context.getNameForTemplate(TName, TNameLoc);
5715   }
5716 
5717   } // switch (Name.getKind())
5718 
5719   llvm_unreachable("Unknown name kind");
5720 }
5721 
5722 static QualType getCoreType(QualType Ty) {
5723   do {
5724     if (Ty->isPointerType() || Ty->isReferenceType())
5725       Ty = Ty->getPointeeType();
5726     else if (Ty->isArrayType())
5727       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5728     else
5729       return Ty.withoutLocalFastQualifiers();
5730   } while (true);
5731 }
5732 
5733 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5734 /// and Definition have "nearly" matching parameters. This heuristic is
5735 /// used to improve diagnostics in the case where an out-of-line function
5736 /// definition doesn't match any declaration within the class or namespace.
5737 /// Also sets Params to the list of indices to the parameters that differ
5738 /// between the declaration and the definition. If hasSimilarParameters
5739 /// returns true and Params is empty, then all of the parameters match.
5740 static bool hasSimilarParameters(ASTContext &Context,
5741                                      FunctionDecl *Declaration,
5742                                      FunctionDecl *Definition,
5743                                      SmallVectorImpl<unsigned> &Params) {
5744   Params.clear();
5745   if (Declaration->param_size() != Definition->param_size())
5746     return false;
5747   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5748     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5749     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5750 
5751     // The parameter types are identical
5752     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5753       continue;
5754 
5755     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5756     QualType DefParamBaseTy = getCoreType(DefParamTy);
5757     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5758     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5759 
5760     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5761         (DeclTyName && DeclTyName == DefTyName))
5762       Params.push_back(Idx);
5763     else  // The two parameters aren't even close
5764       return false;
5765   }
5766 
5767   return true;
5768 }
5769 
5770 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5771 /// declarator needs to be rebuilt in the current instantiation.
5772 /// Any bits of declarator which appear before the name are valid for
5773 /// consideration here.  That's specifically the type in the decl spec
5774 /// and the base type in any member-pointer chunks.
5775 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5776                                                     DeclarationName Name) {
5777   // The types we specifically need to rebuild are:
5778   //   - typenames, typeofs, and decltypes
5779   //   - types which will become injected class names
5780   // Of course, we also need to rebuild any type referencing such a
5781   // type.  It's safest to just say "dependent", but we call out a
5782   // few cases here.
5783 
5784   DeclSpec &DS = D.getMutableDeclSpec();
5785   switch (DS.getTypeSpecType()) {
5786   case DeclSpec::TST_typename:
5787   case DeclSpec::TST_typeofType:
5788   case DeclSpec::TST_underlyingType:
5789   case DeclSpec::TST_atomic: {
5790     // Grab the type from the parser.
5791     TypeSourceInfo *TSI = nullptr;
5792     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5793     if (T.isNull() || !T->isInstantiationDependentType()) break;
5794 
5795     // Make sure there's a type source info.  This isn't really much
5796     // of a waste; most dependent types should have type source info
5797     // attached already.
5798     if (!TSI)
5799       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5800 
5801     // Rebuild the type in the current instantiation.
5802     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5803     if (!TSI) return true;
5804 
5805     // Store the new type back in the decl spec.
5806     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5807     DS.UpdateTypeRep(LocType);
5808     break;
5809   }
5810 
5811   case DeclSpec::TST_decltype:
5812   case DeclSpec::TST_typeofExpr: {
5813     Expr *E = DS.getRepAsExpr();
5814     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5815     if (Result.isInvalid()) return true;
5816     DS.UpdateExprRep(Result.get());
5817     break;
5818   }
5819 
5820   default:
5821     // Nothing to do for these decl specs.
5822     break;
5823   }
5824 
5825   // It doesn't matter what order we do this in.
5826   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5827     DeclaratorChunk &Chunk = D.getTypeObject(I);
5828 
5829     // The only type information in the declarator which can come
5830     // before the declaration name is the base type of a member
5831     // pointer.
5832     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5833       continue;
5834 
5835     // Rebuild the scope specifier in-place.
5836     CXXScopeSpec &SS = Chunk.Mem.Scope();
5837     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5838       return true;
5839   }
5840 
5841   return false;
5842 }
5843 
5844 /// Returns true if the declaration is declared in a system header or from a
5845 /// system macro.
5846 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5847   return SM.isInSystemHeader(D->getLocation()) ||
5848          SM.isInSystemMacro(D->getLocation());
5849 }
5850 
5851 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5852   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5853   // of system decl.
5854   if (D->getPreviousDecl() || D->isImplicit())
5855     return;
5856   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5857   if (Status != ReservedIdentifierStatus::NotReserved &&
5858       !isFromSystemHeader(Context.getSourceManager(), D)) {
5859     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5860         << D << static_cast<int>(Status);
5861   }
5862 }
5863 
5864 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5865   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5866   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5867 
5868   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5869       Dcl && Dcl->getDeclContext()->isFileContext())
5870     Dcl->setTopLevelDeclInObjCContainer();
5871 
5872   return Dcl;
5873 }
5874 
5875 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5876 ///   If T is the name of a class, then each of the following shall have a
5877 ///   name different from T:
5878 ///     - every static data member of class T;
5879 ///     - every member function of class T
5880 ///     - every member of class T that is itself a type;
5881 /// \returns true if the declaration name violates these rules.
5882 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5883                                    DeclarationNameInfo NameInfo) {
5884   DeclarationName Name = NameInfo.getName();
5885 
5886   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5887   while (Record && Record->isAnonymousStructOrUnion())
5888     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5889   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5890     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5891     return true;
5892   }
5893 
5894   return false;
5895 }
5896 
5897 /// Diagnose a declaration whose declarator-id has the given
5898 /// nested-name-specifier.
5899 ///
5900 /// \param SS The nested-name-specifier of the declarator-id.
5901 ///
5902 /// \param DC The declaration context to which the nested-name-specifier
5903 /// resolves.
5904 ///
5905 /// \param Name The name of the entity being declared.
5906 ///
5907 /// \param Loc The location of the name of the entity being declared.
5908 ///
5909 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5910 /// we're declaring an explicit / partial specialization / instantiation.
5911 ///
5912 /// \returns true if we cannot safely recover from this error, false otherwise.
5913 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5914                                         DeclarationName Name,
5915                                         SourceLocation Loc, bool IsTemplateId) {
5916   DeclContext *Cur = CurContext;
5917   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5918     Cur = Cur->getParent();
5919 
5920   // If the user provided a superfluous scope specifier that refers back to the
5921   // class in which the entity is already declared, diagnose and ignore it.
5922   //
5923   // class X {
5924   //   void X::f();
5925   // };
5926   //
5927   // Note, it was once ill-formed to give redundant qualification in all
5928   // contexts, but that rule was removed by DR482.
5929   if (Cur->Equals(DC)) {
5930     if (Cur->isRecord()) {
5931       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5932                                       : diag::err_member_extra_qualification)
5933         << Name << FixItHint::CreateRemoval(SS.getRange());
5934       SS.clear();
5935     } else {
5936       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5937     }
5938     return false;
5939   }
5940 
5941   // Check whether the qualifying scope encloses the scope of the original
5942   // declaration. For a template-id, we perform the checks in
5943   // CheckTemplateSpecializationScope.
5944   if (!Cur->Encloses(DC) && !IsTemplateId) {
5945     if (Cur->isRecord())
5946       Diag(Loc, diag::err_member_qualification)
5947         << Name << SS.getRange();
5948     else if (isa<TranslationUnitDecl>(DC))
5949       Diag(Loc, diag::err_invalid_declarator_global_scope)
5950         << Name << SS.getRange();
5951     else if (isa<FunctionDecl>(Cur))
5952       Diag(Loc, diag::err_invalid_declarator_in_function)
5953         << Name << SS.getRange();
5954     else if (isa<BlockDecl>(Cur))
5955       Diag(Loc, diag::err_invalid_declarator_in_block)
5956         << Name << SS.getRange();
5957     else if (isa<ExportDecl>(Cur)) {
5958       if (!isa<NamespaceDecl>(DC))
5959         Diag(Loc, diag::err_export_non_namespace_scope_name)
5960             << Name << SS.getRange();
5961       else
5962         // The cases that DC is not NamespaceDecl should be handled in
5963         // CheckRedeclarationExported.
5964         return false;
5965     } else
5966       Diag(Loc, diag::err_invalid_declarator_scope)
5967       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5968 
5969     return true;
5970   }
5971 
5972   if (Cur->isRecord()) {
5973     // Cannot qualify members within a class.
5974     Diag(Loc, diag::err_member_qualification)
5975       << Name << SS.getRange();
5976     SS.clear();
5977 
5978     // C++ constructors and destructors with incorrect scopes can break
5979     // our AST invariants by having the wrong underlying types. If
5980     // that's the case, then drop this declaration entirely.
5981     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5982          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5983         !Context.hasSameType(Name.getCXXNameType(),
5984                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5985       return true;
5986 
5987     return false;
5988   }
5989 
5990   // C++11 [dcl.meaning]p1:
5991   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5992   //   not begin with a decltype-specifer"
5993   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5994   while (SpecLoc.getPrefix())
5995     SpecLoc = SpecLoc.getPrefix();
5996   if (isa_and_nonnull<DecltypeType>(
5997           SpecLoc.getNestedNameSpecifier()->getAsType()))
5998     Diag(Loc, diag::err_decltype_in_declarator)
5999       << SpecLoc.getTypeLoc().getSourceRange();
6000 
6001   return false;
6002 }
6003 
6004 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6005                                   MultiTemplateParamsArg TemplateParamLists) {
6006   // TODO: consider using NameInfo for diagnostic.
6007   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6008   DeclarationName Name = NameInfo.getName();
6009 
6010   // All of these full declarators require an identifier.  If it doesn't have
6011   // one, the ParsedFreeStandingDeclSpec action should be used.
6012   if (D.isDecompositionDeclarator()) {
6013     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6014   } else if (!Name) {
6015     if (!D.isInvalidType())  // Reject this if we think it is valid.
6016       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6017           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6018     return nullptr;
6019   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6020     return nullptr;
6021 
6022   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6023   // we find one that is.
6024   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6025          (S->getFlags() & Scope::TemplateParamScope) != 0)
6026     S = S->getParent();
6027 
6028   DeclContext *DC = CurContext;
6029   if (D.getCXXScopeSpec().isInvalid())
6030     D.setInvalidType();
6031   else if (D.getCXXScopeSpec().isSet()) {
6032     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6033                                         UPPC_DeclarationQualifier))
6034       return nullptr;
6035 
6036     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6037     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6038     if (!DC || isa<EnumDecl>(DC)) {
6039       // If we could not compute the declaration context, it's because the
6040       // declaration context is dependent but does not refer to a class,
6041       // class template, or class template partial specialization. Complain
6042       // and return early, to avoid the coming semantic disaster.
6043       Diag(D.getIdentifierLoc(),
6044            diag::err_template_qualified_declarator_no_match)
6045         << D.getCXXScopeSpec().getScopeRep()
6046         << D.getCXXScopeSpec().getRange();
6047       return nullptr;
6048     }
6049     bool IsDependentContext = DC->isDependentContext();
6050 
6051     if (!IsDependentContext &&
6052         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6053       return nullptr;
6054 
6055     // If a class is incomplete, do not parse entities inside it.
6056     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6057       Diag(D.getIdentifierLoc(),
6058            diag::err_member_def_undefined_record)
6059         << Name << DC << D.getCXXScopeSpec().getRange();
6060       return nullptr;
6061     }
6062     if (!D.getDeclSpec().isFriendSpecified()) {
6063       if (diagnoseQualifiedDeclaration(
6064               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6065               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6066         if (DC->isRecord())
6067           return nullptr;
6068 
6069         D.setInvalidType();
6070       }
6071     }
6072 
6073     // Check whether we need to rebuild the type of the given
6074     // declaration in the current instantiation.
6075     if (EnteringContext && IsDependentContext &&
6076         TemplateParamLists.size() != 0) {
6077       ContextRAII SavedContext(*this, DC);
6078       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6079         D.setInvalidType();
6080     }
6081   }
6082 
6083   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6084   QualType R = TInfo->getType();
6085 
6086   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6087                                       UPPC_DeclarationType))
6088     D.setInvalidType();
6089 
6090   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6091                         forRedeclarationInCurContext());
6092 
6093   // See if this is a redefinition of a variable in the same scope.
6094   if (!D.getCXXScopeSpec().isSet()) {
6095     bool IsLinkageLookup = false;
6096     bool CreateBuiltins = false;
6097 
6098     // If the declaration we're planning to build will be a function
6099     // or object with linkage, then look for another declaration with
6100     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6101     //
6102     // If the declaration we're planning to build will be declared with
6103     // external linkage in the translation unit, create any builtin with
6104     // the same name.
6105     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6106       /* Do nothing*/;
6107     else if (CurContext->isFunctionOrMethod() &&
6108              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6109               R->isFunctionType())) {
6110       IsLinkageLookup = true;
6111       CreateBuiltins =
6112           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6113     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6114                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6115       CreateBuiltins = true;
6116 
6117     if (IsLinkageLookup) {
6118       Previous.clear(LookupRedeclarationWithLinkage);
6119       Previous.setRedeclarationKind(ForExternalRedeclaration);
6120     }
6121 
6122     LookupName(Previous, S, CreateBuiltins);
6123   } else { // Something like "int foo::x;"
6124     LookupQualifiedName(Previous, DC);
6125 
6126     // C++ [dcl.meaning]p1:
6127     //   When the declarator-id is qualified, the declaration shall refer to a
6128     //  previously declared member of the class or namespace to which the
6129     //  qualifier refers (or, in the case of a namespace, of an element of the
6130     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6131     //  thereof; [...]
6132     //
6133     // Note that we already checked the context above, and that we do not have
6134     // enough information to make sure that Previous contains the declaration
6135     // we want to match. For example, given:
6136     //
6137     //   class X {
6138     //     void f();
6139     //     void f(float);
6140     //   };
6141     //
6142     //   void X::f(int) { } // ill-formed
6143     //
6144     // In this case, Previous will point to the overload set
6145     // containing the two f's declared in X, but neither of them
6146     // matches.
6147 
6148     // C++ [dcl.meaning]p1:
6149     //   [...] the member shall not merely have been introduced by a
6150     //   using-declaration in the scope of the class or namespace nominated by
6151     //   the nested-name-specifier of the declarator-id.
6152     RemoveUsingDecls(Previous);
6153   }
6154 
6155   if (Previous.isSingleResult() &&
6156       Previous.getFoundDecl()->isTemplateParameter()) {
6157     // Maybe we will complain about the shadowed template parameter.
6158     if (!D.isInvalidType())
6159       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6160                                       Previous.getFoundDecl());
6161 
6162     // Just pretend that we didn't see the previous declaration.
6163     Previous.clear();
6164   }
6165 
6166   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6167     // Forget that the previous declaration is the injected-class-name.
6168     Previous.clear();
6169 
6170   // In C++, the previous declaration we find might be a tag type
6171   // (class or enum). In this case, the new declaration will hide the
6172   // tag type. Note that this applies to functions, function templates, and
6173   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6174   if (Previous.isSingleTagDecl() &&
6175       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6176       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6177     Previous.clear();
6178 
6179   // Check that there are no default arguments other than in the parameters
6180   // of a function declaration (C++ only).
6181   if (getLangOpts().CPlusPlus)
6182     CheckExtraCXXDefaultArguments(D);
6183 
6184   NamedDecl *New;
6185 
6186   bool AddToScope = true;
6187   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6188     if (TemplateParamLists.size()) {
6189       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6190       return nullptr;
6191     }
6192 
6193     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6194   } else if (R->isFunctionType()) {
6195     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6196                                   TemplateParamLists,
6197                                   AddToScope);
6198   } else {
6199     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6200                                   AddToScope);
6201   }
6202 
6203   if (!New)
6204     return nullptr;
6205 
6206   // If this has an identifier and is not a function template specialization,
6207   // add it to the scope stack.
6208   if (New->getDeclName() && AddToScope)
6209     PushOnScopeChains(New, S);
6210 
6211   if (isInOpenMPDeclareTargetContext())
6212     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6213 
6214   return New;
6215 }
6216 
6217 /// Helper method to turn variable array types into constant array
6218 /// types in certain situations which would otherwise be errors (for
6219 /// GCC compatibility).
6220 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6221                                                     ASTContext &Context,
6222                                                     bool &SizeIsNegative,
6223                                                     llvm::APSInt &Oversized) {
6224   // This method tries to turn a variable array into a constant
6225   // array even when the size isn't an ICE.  This is necessary
6226   // for compatibility with code that depends on gcc's buggy
6227   // constant expression folding, like struct {char x[(int)(char*)2];}
6228   SizeIsNegative = false;
6229   Oversized = 0;
6230 
6231   if (T->isDependentType())
6232     return QualType();
6233 
6234   QualifierCollector Qs;
6235   const Type *Ty = Qs.strip(T);
6236 
6237   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6238     QualType Pointee = PTy->getPointeeType();
6239     QualType FixedType =
6240         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6241                                             Oversized);
6242     if (FixedType.isNull()) return FixedType;
6243     FixedType = Context.getPointerType(FixedType);
6244     return Qs.apply(Context, FixedType);
6245   }
6246   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6247     QualType Inner = PTy->getInnerType();
6248     QualType FixedType =
6249         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6250                                             Oversized);
6251     if (FixedType.isNull()) return FixedType;
6252     FixedType = Context.getParenType(FixedType);
6253     return Qs.apply(Context, FixedType);
6254   }
6255 
6256   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6257   if (!VLATy)
6258     return QualType();
6259 
6260   QualType ElemTy = VLATy->getElementType();
6261   if (ElemTy->isVariablyModifiedType()) {
6262     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6263                                                  SizeIsNegative, Oversized);
6264     if (ElemTy.isNull())
6265       return QualType();
6266   }
6267 
6268   Expr::EvalResult Result;
6269   if (!VLATy->getSizeExpr() ||
6270       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6271     return QualType();
6272 
6273   llvm::APSInt Res = Result.Val.getInt();
6274 
6275   // Check whether the array size is negative.
6276   if (Res.isSigned() && Res.isNegative()) {
6277     SizeIsNegative = true;
6278     return QualType();
6279   }
6280 
6281   // Check whether the array is too large to be addressed.
6282   unsigned ActiveSizeBits =
6283       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6284        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6285           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6286           : Res.getActiveBits();
6287   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6288     Oversized = Res;
6289     return QualType();
6290   }
6291 
6292   QualType FoldedArrayType = Context.getConstantArrayType(
6293       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6294   return Qs.apply(Context, FoldedArrayType);
6295 }
6296 
6297 static void
6298 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6299   SrcTL = SrcTL.getUnqualifiedLoc();
6300   DstTL = DstTL.getUnqualifiedLoc();
6301   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6302     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6303     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6304                                       DstPTL.getPointeeLoc());
6305     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6306     return;
6307   }
6308   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6309     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6310     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6311                                       DstPTL.getInnerLoc());
6312     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6313     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6314     return;
6315   }
6316   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6317   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6318   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6319   TypeLoc DstElemTL = DstATL.getElementLoc();
6320   if (VariableArrayTypeLoc SrcElemATL =
6321           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6322     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6323     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6324   } else {
6325     DstElemTL.initializeFullCopy(SrcElemTL);
6326   }
6327   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6328   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6329   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6330 }
6331 
6332 /// Helper method to turn variable array types into constant array
6333 /// types in certain situations which would otherwise be errors (for
6334 /// GCC compatibility).
6335 static TypeSourceInfo*
6336 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6337                                               ASTContext &Context,
6338                                               bool &SizeIsNegative,
6339                                               llvm::APSInt &Oversized) {
6340   QualType FixedTy
6341     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6342                                           SizeIsNegative, Oversized);
6343   if (FixedTy.isNull())
6344     return nullptr;
6345   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6346   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6347                                     FixedTInfo->getTypeLoc());
6348   return FixedTInfo;
6349 }
6350 
6351 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6352 /// true if we were successful.
6353 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6354                                            QualType &T, SourceLocation Loc,
6355                                            unsigned FailedFoldDiagID) {
6356   bool SizeIsNegative;
6357   llvm::APSInt Oversized;
6358   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6359       TInfo, Context, SizeIsNegative, Oversized);
6360   if (FixedTInfo) {
6361     Diag(Loc, diag::ext_vla_folded_to_constant);
6362     TInfo = FixedTInfo;
6363     T = FixedTInfo->getType();
6364     return true;
6365   }
6366 
6367   if (SizeIsNegative)
6368     Diag(Loc, diag::err_typecheck_negative_array_size);
6369   else if (Oversized.getBoolValue())
6370     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6371   else if (FailedFoldDiagID)
6372     Diag(Loc, FailedFoldDiagID);
6373   return false;
6374 }
6375 
6376 /// Register the given locally-scoped extern "C" declaration so
6377 /// that it can be found later for redeclarations. We include any extern "C"
6378 /// declaration that is not visible in the translation unit here, not just
6379 /// function-scope declarations.
6380 void
6381 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6382   if (!getLangOpts().CPlusPlus &&
6383       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6384     // Don't need to track declarations in the TU in C.
6385     return;
6386 
6387   // Note that we have a locally-scoped external with this name.
6388   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6389 }
6390 
6391 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6392   // FIXME: We can have multiple results via __attribute__((overloadable)).
6393   auto Result = Context.getExternCContextDecl()->lookup(Name);
6394   return Result.empty() ? nullptr : *Result.begin();
6395 }
6396 
6397 /// Diagnose function specifiers on a declaration of an identifier that
6398 /// does not identify a function.
6399 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6400   // FIXME: We should probably indicate the identifier in question to avoid
6401   // confusion for constructs like "virtual int a(), b;"
6402   if (DS.isVirtualSpecified())
6403     Diag(DS.getVirtualSpecLoc(),
6404          diag::err_virtual_non_function);
6405 
6406   if (DS.hasExplicitSpecifier())
6407     Diag(DS.getExplicitSpecLoc(),
6408          diag::err_explicit_non_function);
6409 
6410   if (DS.isNoreturnSpecified())
6411     Diag(DS.getNoreturnSpecLoc(),
6412          diag::err_noreturn_non_function);
6413 }
6414 
6415 NamedDecl*
6416 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6417                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6418   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6419   if (D.getCXXScopeSpec().isSet()) {
6420     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6421       << D.getCXXScopeSpec().getRange();
6422     D.setInvalidType();
6423     // Pretend we didn't see the scope specifier.
6424     DC = CurContext;
6425     Previous.clear();
6426   }
6427 
6428   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6429 
6430   if (D.getDeclSpec().isInlineSpecified())
6431     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6432         << getLangOpts().CPlusPlus17;
6433   if (D.getDeclSpec().hasConstexprSpecifier())
6434     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6435         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6436 
6437   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6438     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6439       Diag(D.getName().StartLocation,
6440            diag::err_deduction_guide_invalid_specifier)
6441           << "typedef";
6442     else
6443       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6444           << D.getName().getSourceRange();
6445     return nullptr;
6446   }
6447 
6448   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6449   if (!NewTD) return nullptr;
6450 
6451   // Handle attributes prior to checking for duplicates in MergeVarDecl
6452   ProcessDeclAttributes(S, NewTD, D);
6453 
6454   CheckTypedefForVariablyModifiedType(S, NewTD);
6455 
6456   bool Redeclaration = D.isRedeclaration();
6457   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6458   D.setRedeclaration(Redeclaration);
6459   return ND;
6460 }
6461 
6462 void
6463 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6464   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6465   // then it shall have block scope.
6466   // Note that variably modified types must be fixed before merging the decl so
6467   // that redeclarations will match.
6468   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6469   QualType T = TInfo->getType();
6470   if (T->isVariablyModifiedType()) {
6471     setFunctionHasBranchProtectedScope();
6472 
6473     if (S->getFnParent() == nullptr) {
6474       bool SizeIsNegative;
6475       llvm::APSInt Oversized;
6476       TypeSourceInfo *FixedTInfo =
6477         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6478                                                       SizeIsNegative,
6479                                                       Oversized);
6480       if (FixedTInfo) {
6481         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6482         NewTD->setTypeSourceInfo(FixedTInfo);
6483       } else {
6484         if (SizeIsNegative)
6485           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6486         else if (T->isVariableArrayType())
6487           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6488         else if (Oversized.getBoolValue())
6489           Diag(NewTD->getLocation(), diag::err_array_too_large)
6490             << toString(Oversized, 10);
6491         else
6492           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6493         NewTD->setInvalidDecl();
6494       }
6495     }
6496   }
6497 }
6498 
6499 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6500 /// declares a typedef-name, either using the 'typedef' type specifier or via
6501 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6502 NamedDecl*
6503 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6504                            LookupResult &Previous, bool &Redeclaration) {
6505 
6506   // Find the shadowed declaration before filtering for scope.
6507   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6508 
6509   // Merge the decl with the existing one if appropriate. If the decl is
6510   // in an outer scope, it isn't the same thing.
6511   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6512                        /*AllowInlineNamespace*/false);
6513   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6514   if (!Previous.empty()) {
6515     Redeclaration = true;
6516     MergeTypedefNameDecl(S, NewTD, Previous);
6517   } else {
6518     inferGslPointerAttribute(NewTD);
6519   }
6520 
6521   if (ShadowedDecl && !Redeclaration)
6522     CheckShadow(NewTD, ShadowedDecl, Previous);
6523 
6524   // If this is the C FILE type, notify the AST context.
6525   if (IdentifierInfo *II = NewTD->getIdentifier())
6526     if (!NewTD->isInvalidDecl() &&
6527         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6528       if (II->isStr("FILE"))
6529         Context.setFILEDecl(NewTD);
6530       else if (II->isStr("jmp_buf"))
6531         Context.setjmp_bufDecl(NewTD);
6532       else if (II->isStr("sigjmp_buf"))
6533         Context.setsigjmp_bufDecl(NewTD);
6534       else if (II->isStr("ucontext_t"))
6535         Context.setucontext_tDecl(NewTD);
6536     }
6537 
6538   return NewTD;
6539 }
6540 
6541 /// Determines whether the given declaration is an out-of-scope
6542 /// previous declaration.
6543 ///
6544 /// This routine should be invoked when name lookup has found a
6545 /// previous declaration (PrevDecl) that is not in the scope where a
6546 /// new declaration by the same name is being introduced. If the new
6547 /// declaration occurs in a local scope, previous declarations with
6548 /// linkage may still be considered previous declarations (C99
6549 /// 6.2.2p4-5, C++ [basic.link]p6).
6550 ///
6551 /// \param PrevDecl the previous declaration found by name
6552 /// lookup
6553 ///
6554 /// \param DC the context in which the new declaration is being
6555 /// declared.
6556 ///
6557 /// \returns true if PrevDecl is an out-of-scope previous declaration
6558 /// for a new delcaration with the same name.
6559 static bool
6560 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6561                                 ASTContext &Context) {
6562   if (!PrevDecl)
6563     return false;
6564 
6565   if (!PrevDecl->hasLinkage())
6566     return false;
6567 
6568   if (Context.getLangOpts().CPlusPlus) {
6569     // C++ [basic.link]p6:
6570     //   If there is a visible declaration of an entity with linkage
6571     //   having the same name and type, ignoring entities declared
6572     //   outside the innermost enclosing namespace scope, the block
6573     //   scope declaration declares that same entity and receives the
6574     //   linkage of the previous declaration.
6575     DeclContext *OuterContext = DC->getRedeclContext();
6576     if (!OuterContext->isFunctionOrMethod())
6577       // This rule only applies to block-scope declarations.
6578       return false;
6579 
6580     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6581     if (PrevOuterContext->isRecord())
6582       // We found a member function: ignore it.
6583       return false;
6584 
6585     // Find the innermost enclosing namespace for the new and
6586     // previous declarations.
6587     OuterContext = OuterContext->getEnclosingNamespaceContext();
6588     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6589 
6590     // The previous declaration is in a different namespace, so it
6591     // isn't the same function.
6592     if (!OuterContext->Equals(PrevOuterContext))
6593       return false;
6594   }
6595 
6596   return true;
6597 }
6598 
6599 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6600   CXXScopeSpec &SS = D.getCXXScopeSpec();
6601   if (!SS.isSet()) return;
6602   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6603 }
6604 
6605 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6606   QualType type = decl->getType();
6607   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6608   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6609     // Various kinds of declaration aren't allowed to be __autoreleasing.
6610     unsigned kind = -1U;
6611     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6612       if (var->hasAttr<BlocksAttr>())
6613         kind = 0; // __block
6614       else if (!var->hasLocalStorage())
6615         kind = 1; // global
6616     } else if (isa<ObjCIvarDecl>(decl)) {
6617       kind = 3; // ivar
6618     } else if (isa<FieldDecl>(decl)) {
6619       kind = 2; // field
6620     }
6621 
6622     if (kind != -1U) {
6623       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6624         << kind;
6625     }
6626   } else if (lifetime == Qualifiers::OCL_None) {
6627     // Try to infer lifetime.
6628     if (!type->isObjCLifetimeType())
6629       return false;
6630 
6631     lifetime = type->getObjCARCImplicitLifetime();
6632     type = Context.getLifetimeQualifiedType(type, lifetime);
6633     decl->setType(type);
6634   }
6635 
6636   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6637     // Thread-local variables cannot have lifetime.
6638     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6639         var->getTLSKind()) {
6640       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6641         << var->getType();
6642       return true;
6643     }
6644   }
6645 
6646   return false;
6647 }
6648 
6649 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6650   if (Decl->getType().hasAddressSpace())
6651     return;
6652   if (Decl->getType()->isDependentType())
6653     return;
6654   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6655     QualType Type = Var->getType();
6656     if (Type->isSamplerT() || Type->isVoidType())
6657       return;
6658     LangAS ImplAS = LangAS::opencl_private;
6659     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6660     // __opencl_c_program_scope_global_variables feature, the address space
6661     // for a variable at program scope or a static or extern variable inside
6662     // a function are inferred to be __global.
6663     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6664         Var->hasGlobalStorage())
6665       ImplAS = LangAS::opencl_global;
6666     // If the original type from a decayed type is an array type and that array
6667     // type has no address space yet, deduce it now.
6668     if (auto DT = dyn_cast<DecayedType>(Type)) {
6669       auto OrigTy = DT->getOriginalType();
6670       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6671         // Add the address space to the original array type and then propagate
6672         // that to the element type through `getAsArrayType`.
6673         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6674         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6675         // Re-generate the decayed type.
6676         Type = Context.getDecayedType(OrigTy);
6677       }
6678     }
6679     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6680     // Apply any qualifiers (including address space) from the array type to
6681     // the element type. This implements C99 6.7.3p8: "If the specification of
6682     // an array type includes any type qualifiers, the element type is so
6683     // qualified, not the array type."
6684     if (Type->isArrayType())
6685       Type = QualType(Context.getAsArrayType(Type), 0);
6686     Decl->setType(Type);
6687   }
6688 }
6689 
6690 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6691   // Ensure that an auto decl is deduced otherwise the checks below might cache
6692   // the wrong linkage.
6693   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6694 
6695   // 'weak' only applies to declarations with external linkage.
6696   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6697     if (!ND.isExternallyVisible()) {
6698       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6699       ND.dropAttr<WeakAttr>();
6700     }
6701   }
6702   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6703     if (ND.isExternallyVisible()) {
6704       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6705       ND.dropAttr<WeakRefAttr>();
6706       ND.dropAttr<AliasAttr>();
6707     }
6708   }
6709 
6710   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6711     if (VD->hasInit()) {
6712       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6713         assert(VD->isThisDeclarationADefinition() &&
6714                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6715         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6716         VD->dropAttr<AliasAttr>();
6717       }
6718     }
6719   }
6720 
6721   // 'selectany' only applies to externally visible variable declarations.
6722   // It does not apply to functions.
6723   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6724     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6725       S.Diag(Attr->getLocation(),
6726              diag::err_attribute_selectany_non_extern_data);
6727       ND.dropAttr<SelectAnyAttr>();
6728     }
6729   }
6730 
6731   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6732     auto *VD = dyn_cast<VarDecl>(&ND);
6733     bool IsAnonymousNS = false;
6734     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6735     if (VD) {
6736       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6737       while (NS && !IsAnonymousNS) {
6738         IsAnonymousNS = NS->isAnonymousNamespace();
6739         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6740       }
6741     }
6742     // dll attributes require external linkage. Static locals may have external
6743     // linkage but still cannot be explicitly imported or exported.
6744     // In Microsoft mode, a variable defined in anonymous namespace must have
6745     // external linkage in order to be exported.
6746     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6747     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6748         (!AnonNSInMicrosoftMode &&
6749          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6750       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6751         << &ND << Attr;
6752       ND.setInvalidDecl();
6753     }
6754   }
6755 
6756   // Check the attributes on the function type, if any.
6757   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6758     // Don't declare this variable in the second operand of the for-statement;
6759     // GCC miscompiles that by ending its lifetime before evaluating the
6760     // third operand. See gcc.gnu.org/PR86769.
6761     AttributedTypeLoc ATL;
6762     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6763          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6764          TL = ATL.getModifiedLoc()) {
6765       // The [[lifetimebound]] attribute can be applied to the implicit object
6766       // parameter of a non-static member function (other than a ctor or dtor)
6767       // by applying it to the function type.
6768       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6769         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6770         if (!MD || MD->isStatic()) {
6771           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6772               << !MD << A->getRange();
6773         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6774           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6775               << isa<CXXDestructorDecl>(MD) << A->getRange();
6776         }
6777       }
6778     }
6779   }
6780 }
6781 
6782 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6783                                            NamedDecl *NewDecl,
6784                                            bool IsSpecialization,
6785                                            bool IsDefinition) {
6786   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6787     return;
6788 
6789   bool IsTemplate = false;
6790   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6791     OldDecl = OldTD->getTemplatedDecl();
6792     IsTemplate = true;
6793     if (!IsSpecialization)
6794       IsDefinition = false;
6795   }
6796   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6797     NewDecl = NewTD->getTemplatedDecl();
6798     IsTemplate = true;
6799   }
6800 
6801   if (!OldDecl || !NewDecl)
6802     return;
6803 
6804   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6805   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6806   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6807   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6808 
6809   // dllimport and dllexport are inheritable attributes so we have to exclude
6810   // inherited attribute instances.
6811   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6812                     (NewExportAttr && !NewExportAttr->isInherited());
6813 
6814   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6815   // the only exception being explicit specializations.
6816   // Implicitly generated declarations are also excluded for now because there
6817   // is no other way to switch these to use dllimport or dllexport.
6818   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6819 
6820   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6821     // Allow with a warning for free functions and global variables.
6822     bool JustWarn = false;
6823     if (!OldDecl->isCXXClassMember()) {
6824       auto *VD = dyn_cast<VarDecl>(OldDecl);
6825       if (VD && !VD->getDescribedVarTemplate())
6826         JustWarn = true;
6827       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6828       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6829         JustWarn = true;
6830     }
6831 
6832     // We cannot change a declaration that's been used because IR has already
6833     // been emitted. Dllimported functions will still work though (modulo
6834     // address equality) as they can use the thunk.
6835     if (OldDecl->isUsed())
6836       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6837         JustWarn = false;
6838 
6839     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6840                                : diag::err_attribute_dll_redeclaration;
6841     S.Diag(NewDecl->getLocation(), DiagID)
6842         << NewDecl
6843         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6844     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6845     if (!JustWarn) {
6846       NewDecl->setInvalidDecl();
6847       return;
6848     }
6849   }
6850 
6851   // A redeclaration is not allowed to drop a dllimport attribute, the only
6852   // exceptions being inline function definitions (except for function
6853   // templates), local extern declarations, qualified friend declarations or
6854   // special MSVC extension: in the last case, the declaration is treated as if
6855   // it were marked dllexport.
6856   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6857   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6858   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6859     // Ignore static data because out-of-line definitions are diagnosed
6860     // separately.
6861     IsStaticDataMember = VD->isStaticDataMember();
6862     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6863                    VarDecl::DeclarationOnly;
6864   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6865     IsInline = FD->isInlined();
6866     IsQualifiedFriend = FD->getQualifier() &&
6867                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6868   }
6869 
6870   if (OldImportAttr && !HasNewAttr &&
6871       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6872       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6873     if (IsMicrosoftABI && IsDefinition) {
6874       S.Diag(NewDecl->getLocation(),
6875              diag::warn_redeclaration_without_import_attribute)
6876           << NewDecl;
6877       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6878       NewDecl->dropAttr<DLLImportAttr>();
6879       NewDecl->addAttr(
6880           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6881     } else {
6882       S.Diag(NewDecl->getLocation(),
6883              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6884           << NewDecl << OldImportAttr;
6885       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6886       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6887       OldDecl->dropAttr<DLLImportAttr>();
6888       NewDecl->dropAttr<DLLImportAttr>();
6889     }
6890   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6891     // In MinGW, seeing a function declared inline drops the dllimport
6892     // attribute.
6893     OldDecl->dropAttr<DLLImportAttr>();
6894     NewDecl->dropAttr<DLLImportAttr>();
6895     S.Diag(NewDecl->getLocation(),
6896            diag::warn_dllimport_dropped_from_inline_function)
6897         << NewDecl << OldImportAttr;
6898   }
6899 
6900   // A specialization of a class template member function is processed here
6901   // since it's a redeclaration. If the parent class is dllexport, the
6902   // specialization inherits that attribute. This doesn't happen automatically
6903   // since the parent class isn't instantiated until later.
6904   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6905     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6906         !NewImportAttr && !NewExportAttr) {
6907       if (const DLLExportAttr *ParentExportAttr =
6908               MD->getParent()->getAttr<DLLExportAttr>()) {
6909         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6910         NewAttr->setInherited(true);
6911         NewDecl->addAttr(NewAttr);
6912       }
6913     }
6914   }
6915 }
6916 
6917 /// Given that we are within the definition of the given function,
6918 /// will that definition behave like C99's 'inline', where the
6919 /// definition is discarded except for optimization purposes?
6920 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6921   // Try to avoid calling GetGVALinkageForFunction.
6922 
6923   // All cases of this require the 'inline' keyword.
6924   if (!FD->isInlined()) return false;
6925 
6926   // This is only possible in C++ with the gnu_inline attribute.
6927   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6928     return false;
6929 
6930   // Okay, go ahead and call the relatively-more-expensive function.
6931   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6932 }
6933 
6934 /// Determine whether a variable is extern "C" prior to attaching
6935 /// an initializer. We can't just call isExternC() here, because that
6936 /// will also compute and cache whether the declaration is externally
6937 /// visible, which might change when we attach the initializer.
6938 ///
6939 /// This can only be used if the declaration is known to not be a
6940 /// redeclaration of an internal linkage declaration.
6941 ///
6942 /// For instance:
6943 ///
6944 ///   auto x = []{};
6945 ///
6946 /// Attaching the initializer here makes this declaration not externally
6947 /// visible, because its type has internal linkage.
6948 ///
6949 /// FIXME: This is a hack.
6950 template<typename T>
6951 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6952   if (S.getLangOpts().CPlusPlus) {
6953     // In C++, the overloadable attribute negates the effects of extern "C".
6954     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6955       return false;
6956 
6957     // So do CUDA's host/device attributes.
6958     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6959                                  D->template hasAttr<CUDAHostAttr>()))
6960       return false;
6961   }
6962   return D->isExternC();
6963 }
6964 
6965 static bool shouldConsiderLinkage(const VarDecl *VD) {
6966   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6967   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6968       isa<OMPDeclareMapperDecl>(DC))
6969     return VD->hasExternalStorage();
6970   if (DC->isFileContext())
6971     return true;
6972   if (DC->isRecord())
6973     return false;
6974   if (isa<RequiresExprBodyDecl>(DC))
6975     return false;
6976   llvm_unreachable("Unexpected context");
6977 }
6978 
6979 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6980   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6981   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6982       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6983     return true;
6984   if (DC->isRecord())
6985     return false;
6986   llvm_unreachable("Unexpected context");
6987 }
6988 
6989 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6990                           ParsedAttr::Kind Kind) {
6991   // Check decl attributes on the DeclSpec.
6992   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6993     return true;
6994 
6995   // Walk the declarator structure, checking decl attributes that were in a type
6996   // position to the decl itself.
6997   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6998     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6999       return true;
7000   }
7001 
7002   // Finally, check attributes on the decl itself.
7003   return PD.getAttributes().hasAttribute(Kind) ||
7004          PD.getDeclarationAttributes().hasAttribute(Kind);
7005 }
7006 
7007 /// Adjust the \c DeclContext for a function or variable that might be a
7008 /// function-local external declaration.
7009 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7010   if (!DC->isFunctionOrMethod())
7011     return false;
7012 
7013   // If this is a local extern function or variable declared within a function
7014   // template, don't add it into the enclosing namespace scope until it is
7015   // instantiated; it might have a dependent type right now.
7016   if (DC->isDependentContext())
7017     return true;
7018 
7019   // C++11 [basic.link]p7:
7020   //   When a block scope declaration of an entity with linkage is not found to
7021   //   refer to some other declaration, then that entity is a member of the
7022   //   innermost enclosing namespace.
7023   //
7024   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7025   // semantically-enclosing namespace, not a lexically-enclosing one.
7026   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7027     DC = DC->getParent();
7028   return true;
7029 }
7030 
7031 /// Returns true if given declaration has external C language linkage.
7032 static bool isDeclExternC(const Decl *D) {
7033   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7034     return FD->isExternC();
7035   if (const auto *VD = dyn_cast<VarDecl>(D))
7036     return VD->isExternC();
7037 
7038   llvm_unreachable("Unknown type of decl!");
7039 }
7040 
7041 /// Returns true if there hasn't been any invalid type diagnosed.
7042 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7043   DeclContext *DC = NewVD->getDeclContext();
7044   QualType R = NewVD->getType();
7045 
7046   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7047   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7048   // argument.
7049   if (R->isImageType() || R->isPipeType()) {
7050     Se.Diag(NewVD->getLocation(),
7051             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7052         << R;
7053     NewVD->setInvalidDecl();
7054     return false;
7055   }
7056 
7057   // OpenCL v1.2 s6.9.r:
7058   // The event type cannot be used to declare a program scope variable.
7059   // OpenCL v2.0 s6.9.q:
7060   // The clk_event_t and reserve_id_t types cannot be declared in program
7061   // scope.
7062   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7063     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7064       Se.Diag(NewVD->getLocation(),
7065               diag::err_invalid_type_for_program_scope_var)
7066           << R;
7067       NewVD->setInvalidDecl();
7068       return false;
7069     }
7070   }
7071 
7072   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7073   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7074                                                Se.getLangOpts())) {
7075     QualType NR = R.getCanonicalType();
7076     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7077            NR->isReferenceType()) {
7078       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7079           NR->isFunctionReferenceType()) {
7080         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7081             << NR->isReferenceType();
7082         NewVD->setInvalidDecl();
7083         return false;
7084       }
7085       NR = NR->getPointeeType();
7086     }
7087   }
7088 
7089   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7090                                                Se.getLangOpts())) {
7091     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7092     // half array type (unless the cl_khr_fp16 extension is enabled).
7093     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7094       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7095       NewVD->setInvalidDecl();
7096       return false;
7097     }
7098   }
7099 
7100   // OpenCL v1.2 s6.9.r:
7101   // The event type cannot be used with the __local, __constant and __global
7102   // address space qualifiers.
7103   if (R->isEventT()) {
7104     if (R.getAddressSpace() != LangAS::opencl_private) {
7105       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7106       NewVD->setInvalidDecl();
7107       return false;
7108     }
7109   }
7110 
7111   if (R->isSamplerT()) {
7112     // OpenCL v1.2 s6.9.b p4:
7113     // The sampler type cannot be used with the __local and __global address
7114     // space qualifiers.
7115     if (R.getAddressSpace() == LangAS::opencl_local ||
7116         R.getAddressSpace() == LangAS::opencl_global) {
7117       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7118       NewVD->setInvalidDecl();
7119     }
7120 
7121     // OpenCL v1.2 s6.12.14.1:
7122     // A global sampler must be declared with either the constant address
7123     // space qualifier or with the const qualifier.
7124     if (DC->isTranslationUnit() &&
7125         !(R.getAddressSpace() == LangAS::opencl_constant ||
7126           R.isConstQualified())) {
7127       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7128       NewVD->setInvalidDecl();
7129     }
7130     if (NewVD->isInvalidDecl())
7131       return false;
7132   }
7133 
7134   return true;
7135 }
7136 
7137 template <typename AttrTy>
7138 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7139   const TypedefNameDecl *TND = TT->getDecl();
7140   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7141     AttrTy *Clone = Attribute->clone(S.Context);
7142     Clone->setInherited(true);
7143     D->addAttr(Clone);
7144   }
7145 }
7146 
7147 NamedDecl *Sema::ActOnVariableDeclarator(
7148     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7149     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7150     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7151   QualType R = TInfo->getType();
7152   DeclarationName Name = GetNameForDeclarator(D).getName();
7153 
7154   IdentifierInfo *II = Name.getAsIdentifierInfo();
7155 
7156   if (D.isDecompositionDeclarator()) {
7157     // Take the name of the first declarator as our name for diagnostic
7158     // purposes.
7159     auto &Decomp = D.getDecompositionDeclarator();
7160     if (!Decomp.bindings().empty()) {
7161       II = Decomp.bindings()[0].Name;
7162       Name = II;
7163     }
7164   } else if (!II) {
7165     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7166     return nullptr;
7167   }
7168 
7169 
7170   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7171   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7172 
7173   // dllimport globals without explicit storage class are treated as extern. We
7174   // have to change the storage class this early to get the right DeclContext.
7175   if (SC == SC_None && !DC->isRecord() &&
7176       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7177       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7178     SC = SC_Extern;
7179 
7180   DeclContext *OriginalDC = DC;
7181   bool IsLocalExternDecl = SC == SC_Extern &&
7182                            adjustContextForLocalExternDecl(DC);
7183 
7184   if (SCSpec == DeclSpec::SCS_mutable) {
7185     // mutable can only appear on non-static class members, so it's always
7186     // an error here
7187     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7188     D.setInvalidType();
7189     SC = SC_None;
7190   }
7191 
7192   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7193       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7194                               D.getDeclSpec().getStorageClassSpecLoc())) {
7195     // In C++11, the 'register' storage class specifier is deprecated.
7196     // Suppress the warning in system macros, it's used in macros in some
7197     // popular C system headers, such as in glibc's htonl() macro.
7198     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7199          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7200                                    : diag::warn_deprecated_register)
7201       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7202   }
7203 
7204   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7205 
7206   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7207     // C99 6.9p2: The storage-class specifiers auto and register shall not
7208     // appear in the declaration specifiers in an external declaration.
7209     // Global Register+Asm is a GNU extension we support.
7210     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7211       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7212       D.setInvalidType();
7213     }
7214   }
7215 
7216   // If this variable has a VLA type and an initializer, try to
7217   // fold to a constant-sized type. This is otherwise invalid.
7218   if (D.hasInitializer() && R->isVariableArrayType())
7219     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7220                                     /*DiagID=*/0);
7221 
7222   bool IsMemberSpecialization = false;
7223   bool IsVariableTemplateSpecialization = false;
7224   bool IsPartialSpecialization = false;
7225   bool IsVariableTemplate = false;
7226   VarDecl *NewVD = nullptr;
7227   VarTemplateDecl *NewTemplate = nullptr;
7228   TemplateParameterList *TemplateParams = nullptr;
7229   if (!getLangOpts().CPlusPlus) {
7230     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7231                             II, R, TInfo, SC);
7232 
7233     if (R->getContainedDeducedType())
7234       ParsingInitForAutoVars.insert(NewVD);
7235 
7236     if (D.isInvalidType())
7237       NewVD->setInvalidDecl();
7238 
7239     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7240         NewVD->hasLocalStorage())
7241       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7242                             NTCUC_AutoVar, NTCUK_Destruct);
7243   } else {
7244     bool Invalid = false;
7245 
7246     if (DC->isRecord() && !CurContext->isRecord()) {
7247       // This is an out-of-line definition of a static data member.
7248       switch (SC) {
7249       case SC_None:
7250         break;
7251       case SC_Static:
7252         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7253              diag::err_static_out_of_line)
7254           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7255         break;
7256       case SC_Auto:
7257       case SC_Register:
7258       case SC_Extern:
7259         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7260         // to names of variables declared in a block or to function parameters.
7261         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7262         // of class members
7263 
7264         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7265              diag::err_storage_class_for_static_member)
7266           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7267         break;
7268       case SC_PrivateExtern:
7269         llvm_unreachable("C storage class in c++!");
7270       }
7271     }
7272 
7273     if (SC == SC_Static && CurContext->isRecord()) {
7274       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7275         // Walk up the enclosing DeclContexts to check for any that are
7276         // incompatible with static data members.
7277         const DeclContext *FunctionOrMethod = nullptr;
7278         const CXXRecordDecl *AnonStruct = nullptr;
7279         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7280           if (Ctxt->isFunctionOrMethod()) {
7281             FunctionOrMethod = Ctxt;
7282             break;
7283           }
7284           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7285           if (ParentDecl && !ParentDecl->getDeclName()) {
7286             AnonStruct = ParentDecl;
7287             break;
7288           }
7289         }
7290         if (FunctionOrMethod) {
7291           // C++ [class.static.data]p5: A local class shall not have static data
7292           // members.
7293           Diag(D.getIdentifierLoc(),
7294                diag::err_static_data_member_not_allowed_in_local_class)
7295             << Name << RD->getDeclName() << RD->getTagKind();
7296         } else if (AnonStruct) {
7297           // C++ [class.static.data]p4: Unnamed classes and classes contained
7298           // directly or indirectly within unnamed classes shall not contain
7299           // static data members.
7300           Diag(D.getIdentifierLoc(),
7301                diag::err_static_data_member_not_allowed_in_anon_struct)
7302             << Name << AnonStruct->getTagKind();
7303           Invalid = true;
7304         } else if (RD->isUnion()) {
7305           // C++98 [class.union]p1: If a union contains a static data member,
7306           // the program is ill-formed. C++11 drops this restriction.
7307           Diag(D.getIdentifierLoc(),
7308                getLangOpts().CPlusPlus11
7309                  ? diag::warn_cxx98_compat_static_data_member_in_union
7310                  : diag::ext_static_data_member_in_union) << Name;
7311         }
7312       }
7313     }
7314 
7315     // Match up the template parameter lists with the scope specifier, then
7316     // determine whether we have a template or a template specialization.
7317     bool InvalidScope = false;
7318     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7319         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7320         D.getCXXScopeSpec(),
7321         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7322             ? D.getName().TemplateId
7323             : nullptr,
7324         TemplateParamLists,
7325         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7326     Invalid |= InvalidScope;
7327 
7328     if (TemplateParams) {
7329       if (!TemplateParams->size() &&
7330           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7331         // There is an extraneous 'template<>' for this variable. Complain
7332         // about it, but allow the declaration of the variable.
7333         Diag(TemplateParams->getTemplateLoc(),
7334              diag::err_template_variable_noparams)
7335           << II
7336           << SourceRange(TemplateParams->getTemplateLoc(),
7337                          TemplateParams->getRAngleLoc());
7338         TemplateParams = nullptr;
7339       } else {
7340         // Check that we can declare a template here.
7341         if (CheckTemplateDeclScope(S, TemplateParams))
7342           return nullptr;
7343 
7344         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7345           // This is an explicit specialization or a partial specialization.
7346           IsVariableTemplateSpecialization = true;
7347           IsPartialSpecialization = TemplateParams->size() > 0;
7348         } else { // if (TemplateParams->size() > 0)
7349           // This is a template declaration.
7350           IsVariableTemplate = true;
7351 
7352           // Only C++1y supports variable templates (N3651).
7353           Diag(D.getIdentifierLoc(),
7354                getLangOpts().CPlusPlus14
7355                    ? diag::warn_cxx11_compat_variable_template
7356                    : diag::ext_variable_template);
7357         }
7358       }
7359     } else {
7360       // Check that we can declare a member specialization here.
7361       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7362           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7363         return nullptr;
7364       assert((Invalid ||
7365               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7366              "should have a 'template<>' for this decl");
7367     }
7368 
7369     if (IsVariableTemplateSpecialization) {
7370       SourceLocation TemplateKWLoc =
7371           TemplateParamLists.size() > 0
7372               ? TemplateParamLists[0]->getTemplateLoc()
7373               : SourceLocation();
7374       DeclResult Res = ActOnVarTemplateSpecialization(
7375           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7376           IsPartialSpecialization);
7377       if (Res.isInvalid())
7378         return nullptr;
7379       NewVD = cast<VarDecl>(Res.get());
7380       AddToScope = false;
7381     } else if (D.isDecompositionDeclarator()) {
7382       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7383                                         D.getIdentifierLoc(), R, TInfo, SC,
7384                                         Bindings);
7385     } else
7386       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7387                               D.getIdentifierLoc(), II, R, TInfo, SC);
7388 
7389     // If this is supposed to be a variable template, create it as such.
7390     if (IsVariableTemplate) {
7391       NewTemplate =
7392           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7393                                   TemplateParams, NewVD);
7394       NewVD->setDescribedVarTemplate(NewTemplate);
7395     }
7396 
7397     // If this decl has an auto type in need of deduction, make a note of the
7398     // Decl so we can diagnose uses of it in its own initializer.
7399     if (R->getContainedDeducedType())
7400       ParsingInitForAutoVars.insert(NewVD);
7401 
7402     if (D.isInvalidType() || Invalid) {
7403       NewVD->setInvalidDecl();
7404       if (NewTemplate)
7405         NewTemplate->setInvalidDecl();
7406     }
7407 
7408     SetNestedNameSpecifier(*this, NewVD, D);
7409 
7410     // If we have any template parameter lists that don't directly belong to
7411     // the variable (matching the scope specifier), store them.
7412     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7413     if (TemplateParamLists.size() > VDTemplateParamLists)
7414       NewVD->setTemplateParameterListsInfo(
7415           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7416   }
7417 
7418   if (D.getDeclSpec().isInlineSpecified()) {
7419     if (!getLangOpts().CPlusPlus) {
7420       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7421           << 0;
7422     } else if (CurContext->isFunctionOrMethod()) {
7423       // 'inline' is not allowed on block scope variable declaration.
7424       Diag(D.getDeclSpec().getInlineSpecLoc(),
7425            diag::err_inline_declaration_block_scope) << Name
7426         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7427     } else {
7428       Diag(D.getDeclSpec().getInlineSpecLoc(),
7429            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7430                                      : diag::ext_inline_variable);
7431       NewVD->setInlineSpecified();
7432     }
7433   }
7434 
7435   // Set the lexical context. If the declarator has a C++ scope specifier, the
7436   // lexical context will be different from the semantic context.
7437   NewVD->setLexicalDeclContext(CurContext);
7438   if (NewTemplate)
7439     NewTemplate->setLexicalDeclContext(CurContext);
7440 
7441   if (IsLocalExternDecl) {
7442     if (D.isDecompositionDeclarator())
7443       for (auto *B : Bindings)
7444         B->setLocalExternDecl();
7445     else
7446       NewVD->setLocalExternDecl();
7447   }
7448 
7449   bool EmitTLSUnsupportedError = false;
7450   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7451     // C++11 [dcl.stc]p4:
7452     //   When thread_local is applied to a variable of block scope the
7453     //   storage-class-specifier static is implied if it does not appear
7454     //   explicitly.
7455     // Core issue: 'static' is not implied if the variable is declared
7456     //   'extern'.
7457     if (NewVD->hasLocalStorage() &&
7458         (SCSpec != DeclSpec::SCS_unspecified ||
7459          TSCS != DeclSpec::TSCS_thread_local ||
7460          !DC->isFunctionOrMethod()))
7461       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7462            diag::err_thread_non_global)
7463         << DeclSpec::getSpecifierName(TSCS);
7464     else if (!Context.getTargetInfo().isTLSSupported()) {
7465       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7466           getLangOpts().SYCLIsDevice) {
7467         // Postpone error emission until we've collected attributes required to
7468         // figure out whether it's a host or device variable and whether the
7469         // error should be ignored.
7470         EmitTLSUnsupportedError = true;
7471         // We still need to mark the variable as TLS so it shows up in AST with
7472         // proper storage class for other tools to use even if we're not going
7473         // to emit any code for it.
7474         NewVD->setTSCSpec(TSCS);
7475       } else
7476         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7477              diag::err_thread_unsupported);
7478     } else
7479       NewVD->setTSCSpec(TSCS);
7480   }
7481 
7482   switch (D.getDeclSpec().getConstexprSpecifier()) {
7483   case ConstexprSpecKind::Unspecified:
7484     break;
7485 
7486   case ConstexprSpecKind::Consteval:
7487     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7488          diag::err_constexpr_wrong_decl_kind)
7489         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7490     LLVM_FALLTHROUGH;
7491 
7492   case ConstexprSpecKind::Constexpr:
7493     NewVD->setConstexpr(true);
7494     // C++1z [dcl.spec.constexpr]p1:
7495     //   A static data member declared with the constexpr specifier is
7496     //   implicitly an inline variable.
7497     if (NewVD->isStaticDataMember() &&
7498         (getLangOpts().CPlusPlus17 ||
7499          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7500       NewVD->setImplicitlyInline();
7501     break;
7502 
7503   case ConstexprSpecKind::Constinit:
7504     if (!NewVD->hasGlobalStorage())
7505       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7506            diag::err_constinit_local_variable);
7507     else
7508       NewVD->addAttr(ConstInitAttr::Create(
7509           Context, D.getDeclSpec().getConstexprSpecLoc(),
7510           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7511     break;
7512   }
7513 
7514   // C99 6.7.4p3
7515   //   An inline definition of a function with external linkage shall
7516   //   not contain a definition of a modifiable object with static or
7517   //   thread storage duration...
7518   // We only apply this when the function is required to be defined
7519   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7520   // that a local variable with thread storage duration still has to
7521   // be marked 'static'.  Also note that it's possible to get these
7522   // semantics in C++ using __attribute__((gnu_inline)).
7523   if (SC == SC_Static && S->getFnParent() != nullptr &&
7524       !NewVD->getType().isConstQualified()) {
7525     FunctionDecl *CurFD = getCurFunctionDecl();
7526     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7527       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7528            diag::warn_static_local_in_extern_inline);
7529       MaybeSuggestAddingStaticToDecl(CurFD);
7530     }
7531   }
7532 
7533   if (D.getDeclSpec().isModulePrivateSpecified()) {
7534     if (IsVariableTemplateSpecialization)
7535       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7536           << (IsPartialSpecialization ? 1 : 0)
7537           << FixItHint::CreateRemoval(
7538                  D.getDeclSpec().getModulePrivateSpecLoc());
7539     else if (IsMemberSpecialization)
7540       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7541         << 2
7542         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7543     else if (NewVD->hasLocalStorage())
7544       Diag(NewVD->getLocation(), diag::err_module_private_local)
7545           << 0 << NewVD
7546           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7547           << FixItHint::CreateRemoval(
7548                  D.getDeclSpec().getModulePrivateSpecLoc());
7549     else {
7550       NewVD->setModulePrivate();
7551       if (NewTemplate)
7552         NewTemplate->setModulePrivate();
7553       for (auto *B : Bindings)
7554         B->setModulePrivate();
7555     }
7556   }
7557 
7558   if (getLangOpts().OpenCL) {
7559     deduceOpenCLAddressSpace(NewVD);
7560 
7561     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7562     if (TSC != TSCS_unspecified) {
7563       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7564            diag::err_opencl_unknown_type_specifier)
7565           << getLangOpts().getOpenCLVersionString()
7566           << DeclSpec::getSpecifierName(TSC) << 1;
7567       NewVD->setInvalidDecl();
7568     }
7569   }
7570 
7571   // Handle attributes prior to checking for duplicates in MergeVarDecl
7572   ProcessDeclAttributes(S, NewVD, D);
7573 
7574   // FIXME: This is probably the wrong location to be doing this and we should
7575   // probably be doing this for more attributes (especially for function
7576   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7577   // the code to copy attributes would be generated by TableGen.
7578   if (R->isFunctionPointerType())
7579     if (const auto *TT = R->getAs<TypedefType>())
7580       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7581 
7582   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7583       getLangOpts().SYCLIsDevice) {
7584     if (EmitTLSUnsupportedError &&
7585         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7586          (getLangOpts().OpenMPIsDevice &&
7587           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7588       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7589            diag::err_thread_unsupported);
7590 
7591     if (EmitTLSUnsupportedError &&
7592         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7593       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7594     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7595     // storage [duration]."
7596     if (SC == SC_None && S->getFnParent() != nullptr &&
7597         (NewVD->hasAttr<CUDASharedAttr>() ||
7598          NewVD->hasAttr<CUDAConstantAttr>())) {
7599       NewVD->setStorageClass(SC_Static);
7600     }
7601   }
7602 
7603   // Ensure that dllimport globals without explicit storage class are treated as
7604   // extern. The storage class is set above using parsed attributes. Now we can
7605   // check the VarDecl itself.
7606   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7607          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7608          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7609 
7610   // In auto-retain/release, infer strong retension for variables of
7611   // retainable type.
7612   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7613     NewVD->setInvalidDecl();
7614 
7615   // Handle GNU asm-label extension (encoded as an attribute).
7616   if (Expr *E = (Expr*)D.getAsmLabel()) {
7617     // The parser guarantees this is a string.
7618     StringLiteral *SE = cast<StringLiteral>(E);
7619     StringRef Label = SE->getString();
7620     if (S->getFnParent() != nullptr) {
7621       switch (SC) {
7622       case SC_None:
7623       case SC_Auto:
7624         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7625         break;
7626       case SC_Register:
7627         // Local Named register
7628         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7629             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7630           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7631         break;
7632       case SC_Static:
7633       case SC_Extern:
7634       case SC_PrivateExtern:
7635         break;
7636       }
7637     } else if (SC == SC_Register) {
7638       // Global Named register
7639       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7640         const auto &TI = Context.getTargetInfo();
7641         bool HasSizeMismatch;
7642 
7643         if (!TI.isValidGCCRegisterName(Label))
7644           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7645         else if (!TI.validateGlobalRegisterVariable(Label,
7646                                                     Context.getTypeSize(R),
7647                                                     HasSizeMismatch))
7648           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7649         else if (HasSizeMismatch)
7650           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7651       }
7652 
7653       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7654         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7655         NewVD->setInvalidDecl(true);
7656       }
7657     }
7658 
7659     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7660                                         /*IsLiteralLabel=*/true,
7661                                         SE->getStrTokenLoc(0)));
7662   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7663     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7664       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7665     if (I != ExtnameUndeclaredIdentifiers.end()) {
7666       if (isDeclExternC(NewVD)) {
7667         NewVD->addAttr(I->second);
7668         ExtnameUndeclaredIdentifiers.erase(I);
7669       } else
7670         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7671             << /*Variable*/1 << NewVD;
7672     }
7673   }
7674 
7675   // Find the shadowed declaration before filtering for scope.
7676   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7677                                 ? getShadowedDeclaration(NewVD, Previous)
7678                                 : nullptr;
7679 
7680   // Don't consider existing declarations that are in a different
7681   // scope and are out-of-semantic-context declarations (if the new
7682   // declaration has linkage).
7683   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7684                        D.getCXXScopeSpec().isNotEmpty() ||
7685                        IsMemberSpecialization ||
7686                        IsVariableTemplateSpecialization);
7687 
7688   // Check whether the previous declaration is in the same block scope. This
7689   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7690   if (getLangOpts().CPlusPlus &&
7691       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7692     NewVD->setPreviousDeclInSameBlockScope(
7693         Previous.isSingleResult() && !Previous.isShadowed() &&
7694         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7695 
7696   if (!getLangOpts().CPlusPlus) {
7697     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7698   } else {
7699     // If this is an explicit specialization of a static data member, check it.
7700     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7701         CheckMemberSpecialization(NewVD, Previous))
7702       NewVD->setInvalidDecl();
7703 
7704     // Merge the decl with the existing one if appropriate.
7705     if (!Previous.empty()) {
7706       if (Previous.isSingleResult() &&
7707           isa<FieldDecl>(Previous.getFoundDecl()) &&
7708           D.getCXXScopeSpec().isSet()) {
7709         // The user tried to define a non-static data member
7710         // out-of-line (C++ [dcl.meaning]p1).
7711         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7712           << D.getCXXScopeSpec().getRange();
7713         Previous.clear();
7714         NewVD->setInvalidDecl();
7715       }
7716     } else if (D.getCXXScopeSpec().isSet()) {
7717       // No previous declaration in the qualifying scope.
7718       Diag(D.getIdentifierLoc(), diag::err_no_member)
7719         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7720         << D.getCXXScopeSpec().getRange();
7721       NewVD->setInvalidDecl();
7722     }
7723 
7724     if (!IsVariableTemplateSpecialization)
7725       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7726 
7727     if (NewTemplate) {
7728       VarTemplateDecl *PrevVarTemplate =
7729           NewVD->getPreviousDecl()
7730               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7731               : nullptr;
7732 
7733       // Check the template parameter list of this declaration, possibly
7734       // merging in the template parameter list from the previous variable
7735       // template declaration.
7736       if (CheckTemplateParameterList(
7737               TemplateParams,
7738               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7739                               : nullptr,
7740               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7741                DC->isDependentContext())
7742                   ? TPC_ClassTemplateMember
7743                   : TPC_VarTemplate))
7744         NewVD->setInvalidDecl();
7745 
7746       // If we are providing an explicit specialization of a static variable
7747       // template, make a note of that.
7748       if (PrevVarTemplate &&
7749           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7750         PrevVarTemplate->setMemberSpecialization();
7751     }
7752   }
7753 
7754   // Diagnose shadowed variables iff this isn't a redeclaration.
7755   if (ShadowedDecl && !D.isRedeclaration())
7756     CheckShadow(NewVD, ShadowedDecl, Previous);
7757 
7758   ProcessPragmaWeak(S, NewVD);
7759 
7760   // If this is the first declaration of an extern C variable, update
7761   // the map of such variables.
7762   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7763       isIncompleteDeclExternC(*this, NewVD))
7764     RegisterLocallyScopedExternCDecl(NewVD, S);
7765 
7766   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7767     MangleNumberingContext *MCtx;
7768     Decl *ManglingContextDecl;
7769     std::tie(MCtx, ManglingContextDecl) =
7770         getCurrentMangleNumberContext(NewVD->getDeclContext());
7771     if (MCtx) {
7772       Context.setManglingNumber(
7773           NewVD, MCtx->getManglingNumber(
7774                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7775       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7776     }
7777   }
7778 
7779   // Special handling of variable named 'main'.
7780   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7781       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7782       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7783 
7784     // C++ [basic.start.main]p3
7785     // A program that declares a variable main at global scope is ill-formed.
7786     if (getLangOpts().CPlusPlus)
7787       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7788 
7789     // In C, and external-linkage variable named main results in undefined
7790     // behavior.
7791     else if (NewVD->hasExternalFormalLinkage())
7792       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7793   }
7794 
7795   if (D.isRedeclaration() && !Previous.empty()) {
7796     NamedDecl *Prev = Previous.getRepresentativeDecl();
7797     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7798                                    D.isFunctionDefinition());
7799   }
7800 
7801   if (NewTemplate) {
7802     if (NewVD->isInvalidDecl())
7803       NewTemplate->setInvalidDecl();
7804     ActOnDocumentableDecl(NewTemplate);
7805     return NewTemplate;
7806   }
7807 
7808   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7809     CompleteMemberSpecialization(NewVD, Previous);
7810 
7811   return NewVD;
7812 }
7813 
7814 /// Enum describing the %select options in diag::warn_decl_shadow.
7815 enum ShadowedDeclKind {
7816   SDK_Local,
7817   SDK_Global,
7818   SDK_StaticMember,
7819   SDK_Field,
7820   SDK_Typedef,
7821   SDK_Using,
7822   SDK_StructuredBinding
7823 };
7824 
7825 /// Determine what kind of declaration we're shadowing.
7826 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7827                                                 const DeclContext *OldDC) {
7828   if (isa<TypeAliasDecl>(ShadowedDecl))
7829     return SDK_Using;
7830   else if (isa<TypedefDecl>(ShadowedDecl))
7831     return SDK_Typedef;
7832   else if (isa<BindingDecl>(ShadowedDecl))
7833     return SDK_StructuredBinding;
7834   else if (isa<RecordDecl>(OldDC))
7835     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7836 
7837   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7838 }
7839 
7840 /// Return the location of the capture if the given lambda captures the given
7841 /// variable \p VD, or an invalid source location otherwise.
7842 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7843                                          const VarDecl *VD) {
7844   for (const Capture &Capture : LSI->Captures) {
7845     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7846       return Capture.getLocation();
7847   }
7848   return SourceLocation();
7849 }
7850 
7851 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7852                                      const LookupResult &R) {
7853   // Only diagnose if we're shadowing an unambiguous field or variable.
7854   if (R.getResultKind() != LookupResult::Found)
7855     return false;
7856 
7857   // Return false if warning is ignored.
7858   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7859 }
7860 
7861 /// Return the declaration shadowed by the given variable \p D, or null
7862 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7863 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7864                                         const LookupResult &R) {
7865   if (!shouldWarnIfShadowedDecl(Diags, R))
7866     return nullptr;
7867 
7868   // Don't diagnose declarations at file scope.
7869   if (D->hasGlobalStorage())
7870     return nullptr;
7871 
7872   NamedDecl *ShadowedDecl = R.getFoundDecl();
7873   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7874                                                             : nullptr;
7875 }
7876 
7877 /// Return the declaration shadowed by the given typedef \p D, or null
7878 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7879 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7880                                         const LookupResult &R) {
7881   // Don't warn if typedef declaration is part of a class
7882   if (D->getDeclContext()->isRecord())
7883     return nullptr;
7884 
7885   if (!shouldWarnIfShadowedDecl(Diags, R))
7886     return nullptr;
7887 
7888   NamedDecl *ShadowedDecl = R.getFoundDecl();
7889   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7890 }
7891 
7892 /// Return the declaration shadowed by the given variable \p D, or null
7893 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7894 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7895                                         const LookupResult &R) {
7896   if (!shouldWarnIfShadowedDecl(Diags, R))
7897     return nullptr;
7898 
7899   NamedDecl *ShadowedDecl = R.getFoundDecl();
7900   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7901                                                             : nullptr;
7902 }
7903 
7904 /// Diagnose variable or built-in function shadowing.  Implements
7905 /// -Wshadow.
7906 ///
7907 /// This method is called whenever a VarDecl is added to a "useful"
7908 /// scope.
7909 ///
7910 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7911 /// \param R the lookup of the name
7912 ///
7913 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7914                        const LookupResult &R) {
7915   DeclContext *NewDC = D->getDeclContext();
7916 
7917   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7918     // Fields are not shadowed by variables in C++ static methods.
7919     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7920       if (MD->isStatic())
7921         return;
7922 
7923     // Fields shadowed by constructor parameters are a special case. Usually
7924     // the constructor initializes the field with the parameter.
7925     if (isa<CXXConstructorDecl>(NewDC))
7926       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7927         // Remember that this was shadowed so we can either warn about its
7928         // modification or its existence depending on warning settings.
7929         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7930         return;
7931       }
7932   }
7933 
7934   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7935     if (shadowedVar->isExternC()) {
7936       // For shadowing external vars, make sure that we point to the global
7937       // declaration, not a locally scoped extern declaration.
7938       for (auto I : shadowedVar->redecls())
7939         if (I->isFileVarDecl()) {
7940           ShadowedDecl = I;
7941           break;
7942         }
7943     }
7944 
7945   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7946 
7947   unsigned WarningDiag = diag::warn_decl_shadow;
7948   SourceLocation CaptureLoc;
7949   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7950       isa<CXXMethodDecl>(NewDC)) {
7951     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7952       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7953         if (RD->getLambdaCaptureDefault() == LCD_None) {
7954           // Try to avoid warnings for lambdas with an explicit capture list.
7955           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7956           // Warn only when the lambda captures the shadowed decl explicitly.
7957           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7958           if (CaptureLoc.isInvalid())
7959             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7960         } else {
7961           // Remember that this was shadowed so we can avoid the warning if the
7962           // shadowed decl isn't captured and the warning settings allow it.
7963           cast<LambdaScopeInfo>(getCurFunction())
7964               ->ShadowingDecls.push_back(
7965                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7966           return;
7967         }
7968       }
7969 
7970       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7971         // A variable can't shadow a local variable in an enclosing scope, if
7972         // they are separated by a non-capturing declaration context.
7973         for (DeclContext *ParentDC = NewDC;
7974              ParentDC && !ParentDC->Equals(OldDC);
7975              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7976           // Only block literals, captured statements, and lambda expressions
7977           // can capture; other scopes don't.
7978           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7979               !isLambdaCallOperator(ParentDC)) {
7980             return;
7981           }
7982         }
7983       }
7984     }
7985   }
7986 
7987   // Only warn about certain kinds of shadowing for class members.
7988   if (NewDC && NewDC->isRecord()) {
7989     // In particular, don't warn about shadowing non-class members.
7990     if (!OldDC->isRecord())
7991       return;
7992 
7993     // TODO: should we warn about static data members shadowing
7994     // static data members from base classes?
7995 
7996     // TODO: don't diagnose for inaccessible shadowed members.
7997     // This is hard to do perfectly because we might friend the
7998     // shadowing context, but that's just a false negative.
7999   }
8000 
8001 
8002   DeclarationName Name = R.getLookupName();
8003 
8004   // Emit warning and note.
8005   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8006   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8007   if (!CaptureLoc.isInvalid())
8008     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8009         << Name << /*explicitly*/ 1;
8010   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8011 }
8012 
8013 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8014 /// when these variables are captured by the lambda.
8015 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8016   for (const auto &Shadow : LSI->ShadowingDecls) {
8017     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8018     // Try to avoid the warning when the shadowed decl isn't captured.
8019     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8020     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8021     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8022                                        ? diag::warn_decl_shadow_uncaptured_local
8023                                        : diag::warn_decl_shadow)
8024         << Shadow.VD->getDeclName()
8025         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8026     if (!CaptureLoc.isInvalid())
8027       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8028           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8029     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8030   }
8031 }
8032 
8033 /// Check -Wshadow without the advantage of a previous lookup.
8034 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8035   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8036     return;
8037 
8038   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8039                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8040   LookupName(R, S);
8041   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8042     CheckShadow(D, ShadowedDecl, R);
8043 }
8044 
8045 /// Check if 'E', which is an expression that is about to be modified, refers
8046 /// to a constructor parameter that shadows a field.
8047 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8048   // Quickly ignore expressions that can't be shadowing ctor parameters.
8049   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8050     return;
8051   E = E->IgnoreParenImpCasts();
8052   auto *DRE = dyn_cast<DeclRefExpr>(E);
8053   if (!DRE)
8054     return;
8055   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8056   auto I = ShadowingDecls.find(D);
8057   if (I == ShadowingDecls.end())
8058     return;
8059   const NamedDecl *ShadowedDecl = I->second;
8060   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8061   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8062   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8063   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8064 
8065   // Avoid issuing multiple warnings about the same decl.
8066   ShadowingDecls.erase(I);
8067 }
8068 
8069 /// Check for conflict between this global or extern "C" declaration and
8070 /// previous global or extern "C" declarations. This is only used in C++.
8071 template<typename T>
8072 static bool checkGlobalOrExternCConflict(
8073     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8074   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8075   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8076 
8077   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8078     // The common case: this global doesn't conflict with any extern "C"
8079     // declaration.
8080     return false;
8081   }
8082 
8083   if (Prev) {
8084     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8085       // Both the old and new declarations have C language linkage. This is a
8086       // redeclaration.
8087       Previous.clear();
8088       Previous.addDecl(Prev);
8089       return true;
8090     }
8091 
8092     // This is a global, non-extern "C" declaration, and there is a previous
8093     // non-global extern "C" declaration. Diagnose if this is a variable
8094     // declaration.
8095     if (!isa<VarDecl>(ND))
8096       return false;
8097   } else {
8098     // The declaration is extern "C". Check for any declaration in the
8099     // translation unit which might conflict.
8100     if (IsGlobal) {
8101       // We have already performed the lookup into the translation unit.
8102       IsGlobal = false;
8103       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8104            I != E; ++I) {
8105         if (isa<VarDecl>(*I)) {
8106           Prev = *I;
8107           break;
8108         }
8109       }
8110     } else {
8111       DeclContext::lookup_result R =
8112           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8113       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8114            I != E; ++I) {
8115         if (isa<VarDecl>(*I)) {
8116           Prev = *I;
8117           break;
8118         }
8119         // FIXME: If we have any other entity with this name in global scope,
8120         // the declaration is ill-formed, but that is a defect: it breaks the
8121         // 'stat' hack, for instance. Only variables can have mangled name
8122         // clashes with extern "C" declarations, so only they deserve a
8123         // diagnostic.
8124       }
8125     }
8126 
8127     if (!Prev)
8128       return false;
8129   }
8130 
8131   // Use the first declaration's location to ensure we point at something which
8132   // is lexically inside an extern "C" linkage-spec.
8133   assert(Prev && "should have found a previous declaration to diagnose");
8134   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8135     Prev = FD->getFirstDecl();
8136   else
8137     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8138 
8139   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8140     << IsGlobal << ND;
8141   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8142     << IsGlobal;
8143   return false;
8144 }
8145 
8146 /// Apply special rules for handling extern "C" declarations. Returns \c true
8147 /// if we have found that this is a redeclaration of some prior entity.
8148 ///
8149 /// Per C++ [dcl.link]p6:
8150 ///   Two declarations [for a function or variable] with C language linkage
8151 ///   with the same name that appear in different scopes refer to the same
8152 ///   [entity]. An entity with C language linkage shall not be declared with
8153 ///   the same name as an entity in global scope.
8154 template<typename T>
8155 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8156                                                   LookupResult &Previous) {
8157   if (!S.getLangOpts().CPlusPlus) {
8158     // In C, when declaring a global variable, look for a corresponding 'extern'
8159     // variable declared in function scope. We don't need this in C++, because
8160     // we find local extern decls in the surrounding file-scope DeclContext.
8161     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8162       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8163         Previous.clear();
8164         Previous.addDecl(Prev);
8165         return true;
8166       }
8167     }
8168     return false;
8169   }
8170 
8171   // A declaration in the translation unit can conflict with an extern "C"
8172   // declaration.
8173   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8174     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8175 
8176   // An extern "C" declaration can conflict with a declaration in the
8177   // translation unit or can be a redeclaration of an extern "C" declaration
8178   // in another scope.
8179   if (isIncompleteDeclExternC(S,ND))
8180     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8181 
8182   // Neither global nor extern "C": nothing to do.
8183   return false;
8184 }
8185 
8186 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8187   // If the decl is already known invalid, don't check it.
8188   if (NewVD->isInvalidDecl())
8189     return;
8190 
8191   QualType T = NewVD->getType();
8192 
8193   // Defer checking an 'auto' type until its initializer is attached.
8194   if (T->isUndeducedType())
8195     return;
8196 
8197   if (NewVD->hasAttrs())
8198     CheckAlignasUnderalignment(NewVD);
8199 
8200   if (T->isObjCObjectType()) {
8201     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8202       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8203     T = Context.getObjCObjectPointerType(T);
8204     NewVD->setType(T);
8205   }
8206 
8207   // Emit an error if an address space was applied to decl with local storage.
8208   // This includes arrays of objects with address space qualifiers, but not
8209   // automatic variables that point to other address spaces.
8210   // ISO/IEC TR 18037 S5.1.2
8211   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8212       T.getAddressSpace() != LangAS::Default) {
8213     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8214     NewVD->setInvalidDecl();
8215     return;
8216   }
8217 
8218   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8219   // scope.
8220   if (getLangOpts().OpenCLVersion == 120 &&
8221       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8222                                             getLangOpts()) &&
8223       NewVD->isStaticLocal()) {
8224     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8225     NewVD->setInvalidDecl();
8226     return;
8227   }
8228 
8229   if (getLangOpts().OpenCL) {
8230     if (!diagnoseOpenCLTypes(*this, NewVD))
8231       return;
8232 
8233     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8234     if (NewVD->hasAttr<BlocksAttr>()) {
8235       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8236       return;
8237     }
8238 
8239     if (T->isBlockPointerType()) {
8240       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8241       // can't use 'extern' storage class.
8242       if (!T.isConstQualified()) {
8243         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8244             << 0 /*const*/;
8245         NewVD->setInvalidDecl();
8246         return;
8247       }
8248       if (NewVD->hasExternalStorage()) {
8249         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8250         NewVD->setInvalidDecl();
8251         return;
8252       }
8253     }
8254 
8255     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8256     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8257         NewVD->hasExternalStorage()) {
8258       if (!T->isSamplerT() && !T->isDependentType() &&
8259           !(T.getAddressSpace() == LangAS::opencl_constant ||
8260             (T.getAddressSpace() == LangAS::opencl_global &&
8261              getOpenCLOptions().areProgramScopeVariablesSupported(
8262                  getLangOpts())))) {
8263         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8264         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8265           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8266               << Scope << "global or constant";
8267         else
8268           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8269               << Scope << "constant";
8270         NewVD->setInvalidDecl();
8271         return;
8272       }
8273     } else {
8274       if (T.getAddressSpace() == LangAS::opencl_global) {
8275         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8276             << 1 /*is any function*/ << "global";
8277         NewVD->setInvalidDecl();
8278         return;
8279       }
8280       if (T.getAddressSpace() == LangAS::opencl_constant ||
8281           T.getAddressSpace() == LangAS::opencl_local) {
8282         FunctionDecl *FD = getCurFunctionDecl();
8283         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8284         // in functions.
8285         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8286           if (T.getAddressSpace() == LangAS::opencl_constant)
8287             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8288                 << 0 /*non-kernel only*/ << "constant";
8289           else
8290             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8291                 << 0 /*non-kernel only*/ << "local";
8292           NewVD->setInvalidDecl();
8293           return;
8294         }
8295         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8296         // in the outermost scope of a kernel function.
8297         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8298           if (!getCurScope()->isFunctionScope()) {
8299             if (T.getAddressSpace() == LangAS::opencl_constant)
8300               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8301                   << "constant";
8302             else
8303               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8304                   << "local";
8305             NewVD->setInvalidDecl();
8306             return;
8307           }
8308         }
8309       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8310                  // If we are parsing a template we didn't deduce an addr
8311                  // space yet.
8312                  T.getAddressSpace() != LangAS::Default) {
8313         // Do not allow other address spaces on automatic variable.
8314         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8315         NewVD->setInvalidDecl();
8316         return;
8317       }
8318     }
8319   }
8320 
8321   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8322       && !NewVD->hasAttr<BlocksAttr>()) {
8323     if (getLangOpts().getGC() != LangOptions::NonGC)
8324       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8325     else {
8326       assert(!getLangOpts().ObjCAutoRefCount);
8327       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8328     }
8329   }
8330 
8331   bool isVM = T->isVariablyModifiedType();
8332   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8333       NewVD->hasAttr<BlocksAttr>())
8334     setFunctionHasBranchProtectedScope();
8335 
8336   if ((isVM && NewVD->hasLinkage()) ||
8337       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8338     bool SizeIsNegative;
8339     llvm::APSInt Oversized;
8340     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8341         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8342     QualType FixedT;
8343     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8344       FixedT = FixedTInfo->getType();
8345     else if (FixedTInfo) {
8346       // Type and type-as-written are canonically different. We need to fix up
8347       // both types separately.
8348       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8349                                                    Oversized);
8350     }
8351     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8352       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8353       // FIXME: This won't give the correct result for
8354       // int a[10][n];
8355       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8356 
8357       if (NewVD->isFileVarDecl())
8358         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8359         << SizeRange;
8360       else if (NewVD->isStaticLocal())
8361         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8362         << SizeRange;
8363       else
8364         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8365         << SizeRange;
8366       NewVD->setInvalidDecl();
8367       return;
8368     }
8369 
8370     if (!FixedTInfo) {
8371       if (NewVD->isFileVarDecl())
8372         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8373       else
8374         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8375       NewVD->setInvalidDecl();
8376       return;
8377     }
8378 
8379     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8380     NewVD->setType(FixedT);
8381     NewVD->setTypeSourceInfo(FixedTInfo);
8382   }
8383 
8384   if (T->isVoidType()) {
8385     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8386     //                    of objects and functions.
8387     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8388       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8389         << T;
8390       NewVD->setInvalidDecl();
8391       return;
8392     }
8393   }
8394 
8395   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8396     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8397     NewVD->setInvalidDecl();
8398     return;
8399   }
8400 
8401   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8402     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8403     NewVD->setInvalidDecl();
8404     return;
8405   }
8406 
8407   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8408     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8409     NewVD->setInvalidDecl();
8410     return;
8411   }
8412 
8413   if (NewVD->isConstexpr() && !T->isDependentType() &&
8414       RequireLiteralType(NewVD->getLocation(), T,
8415                          diag::err_constexpr_var_non_literal)) {
8416     NewVD->setInvalidDecl();
8417     return;
8418   }
8419 
8420   // PPC MMA non-pointer types are not allowed as non-local variable types.
8421   if (Context.getTargetInfo().getTriple().isPPC64() &&
8422       !NewVD->isLocalVarDecl() &&
8423       CheckPPCMMAType(T, NewVD->getLocation())) {
8424     NewVD->setInvalidDecl();
8425     return;
8426   }
8427 }
8428 
8429 /// Perform semantic checking on a newly-created variable
8430 /// declaration.
8431 ///
8432 /// This routine performs all of the type-checking required for a
8433 /// variable declaration once it has been built. It is used both to
8434 /// check variables after they have been parsed and their declarators
8435 /// have been translated into a declaration, and to check variables
8436 /// that have been instantiated from a template.
8437 ///
8438 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8439 ///
8440 /// Returns true if the variable declaration is a redeclaration.
8441 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8442   CheckVariableDeclarationType(NewVD);
8443 
8444   // If the decl is already known invalid, don't check it.
8445   if (NewVD->isInvalidDecl())
8446     return false;
8447 
8448   // If we did not find anything by this name, look for a non-visible
8449   // extern "C" declaration with the same name.
8450   if (Previous.empty() &&
8451       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8452     Previous.setShadowed();
8453 
8454   if (!Previous.empty()) {
8455     MergeVarDecl(NewVD, Previous);
8456     return true;
8457   }
8458   return false;
8459 }
8460 
8461 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8462 /// and if so, check that it's a valid override and remember it.
8463 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8464   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8465 
8466   // Look for methods in base classes that this method might override.
8467   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8468                      /*DetectVirtual=*/false);
8469   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8470     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8471     DeclarationName Name = MD->getDeclName();
8472 
8473     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8474       // We really want to find the base class destructor here.
8475       QualType T = Context.getTypeDeclType(BaseRecord);
8476       CanQualType CT = Context.getCanonicalType(T);
8477       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8478     }
8479 
8480     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8481       CXXMethodDecl *BaseMD =
8482           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8483       if (!BaseMD || !BaseMD->isVirtual() ||
8484           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8485                      /*ConsiderCudaAttrs=*/true,
8486                      // C++2a [class.virtual]p2 does not consider requires
8487                      // clauses when overriding.
8488                      /*ConsiderRequiresClauses=*/false))
8489         continue;
8490 
8491       if (Overridden.insert(BaseMD).second) {
8492         MD->addOverriddenMethod(BaseMD);
8493         CheckOverridingFunctionReturnType(MD, BaseMD);
8494         CheckOverridingFunctionAttributes(MD, BaseMD);
8495         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8496         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8497       }
8498 
8499       // A method can only override one function from each base class. We
8500       // don't track indirectly overridden methods from bases of bases.
8501       return true;
8502     }
8503 
8504     return false;
8505   };
8506 
8507   DC->lookupInBases(VisitBase, Paths);
8508   return !Overridden.empty();
8509 }
8510 
8511 namespace {
8512   // Struct for holding all of the extra arguments needed by
8513   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8514   struct ActOnFDArgs {
8515     Scope *S;
8516     Declarator &D;
8517     MultiTemplateParamsArg TemplateParamLists;
8518     bool AddToScope;
8519   };
8520 } // end anonymous namespace
8521 
8522 namespace {
8523 
8524 // Callback to only accept typo corrections that have a non-zero edit distance.
8525 // Also only accept corrections that have the same parent decl.
8526 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8527  public:
8528   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8529                             CXXRecordDecl *Parent)
8530       : Context(Context), OriginalFD(TypoFD),
8531         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8532 
8533   bool ValidateCandidate(const TypoCorrection &candidate) override {
8534     if (candidate.getEditDistance() == 0)
8535       return false;
8536 
8537     SmallVector<unsigned, 1> MismatchedParams;
8538     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8539                                           CDeclEnd = candidate.end();
8540          CDecl != CDeclEnd; ++CDecl) {
8541       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8542 
8543       if (FD && !FD->hasBody() &&
8544           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8545         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8546           CXXRecordDecl *Parent = MD->getParent();
8547           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8548             return true;
8549         } else if (!ExpectedParent) {
8550           return true;
8551         }
8552       }
8553     }
8554 
8555     return false;
8556   }
8557 
8558   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8559     return std::make_unique<DifferentNameValidatorCCC>(*this);
8560   }
8561 
8562  private:
8563   ASTContext &Context;
8564   FunctionDecl *OriginalFD;
8565   CXXRecordDecl *ExpectedParent;
8566 };
8567 
8568 } // end anonymous namespace
8569 
8570 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8571   TypoCorrectedFunctionDefinitions.insert(F);
8572 }
8573 
8574 /// Generate diagnostics for an invalid function redeclaration.
8575 ///
8576 /// This routine handles generating the diagnostic messages for an invalid
8577 /// function redeclaration, including finding possible similar declarations
8578 /// or performing typo correction if there are no previous declarations with
8579 /// the same name.
8580 ///
8581 /// Returns a NamedDecl iff typo correction was performed and substituting in
8582 /// the new declaration name does not cause new errors.
8583 static NamedDecl *DiagnoseInvalidRedeclaration(
8584     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8585     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8586   DeclarationName Name = NewFD->getDeclName();
8587   DeclContext *NewDC = NewFD->getDeclContext();
8588   SmallVector<unsigned, 1> MismatchedParams;
8589   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8590   TypoCorrection Correction;
8591   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8592   unsigned DiagMsg =
8593     IsLocalFriend ? diag::err_no_matching_local_friend :
8594     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8595     diag::err_member_decl_does_not_match;
8596   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8597                     IsLocalFriend ? Sema::LookupLocalFriendName
8598                                   : Sema::LookupOrdinaryName,
8599                     Sema::ForVisibleRedeclaration);
8600 
8601   NewFD->setInvalidDecl();
8602   if (IsLocalFriend)
8603     SemaRef.LookupName(Prev, S);
8604   else
8605     SemaRef.LookupQualifiedName(Prev, NewDC);
8606   assert(!Prev.isAmbiguous() &&
8607          "Cannot have an ambiguity in previous-declaration lookup");
8608   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8609   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8610                                 MD ? MD->getParent() : nullptr);
8611   if (!Prev.empty()) {
8612     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8613          Func != FuncEnd; ++Func) {
8614       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8615       if (FD &&
8616           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8617         // Add 1 to the index so that 0 can mean the mismatch didn't
8618         // involve a parameter
8619         unsigned ParamNum =
8620             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8621         NearMatches.push_back(std::make_pair(FD, ParamNum));
8622       }
8623     }
8624   // If the qualified name lookup yielded nothing, try typo correction
8625   } else if ((Correction = SemaRef.CorrectTypo(
8626                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8627                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8628                   IsLocalFriend ? nullptr : NewDC))) {
8629     // Set up everything for the call to ActOnFunctionDeclarator
8630     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8631                               ExtraArgs.D.getIdentifierLoc());
8632     Previous.clear();
8633     Previous.setLookupName(Correction.getCorrection());
8634     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8635                                     CDeclEnd = Correction.end();
8636          CDecl != CDeclEnd; ++CDecl) {
8637       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8638       if (FD && !FD->hasBody() &&
8639           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8640         Previous.addDecl(FD);
8641       }
8642     }
8643     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8644 
8645     NamedDecl *Result;
8646     // Retry building the function declaration with the new previous
8647     // declarations, and with errors suppressed.
8648     {
8649       // Trap errors.
8650       Sema::SFINAETrap Trap(SemaRef);
8651 
8652       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8653       // pieces need to verify the typo-corrected C++ declaration and hopefully
8654       // eliminate the need for the parameter pack ExtraArgs.
8655       Result = SemaRef.ActOnFunctionDeclarator(
8656           ExtraArgs.S, ExtraArgs.D,
8657           Correction.getCorrectionDecl()->getDeclContext(),
8658           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8659           ExtraArgs.AddToScope);
8660 
8661       if (Trap.hasErrorOccurred())
8662         Result = nullptr;
8663     }
8664 
8665     if (Result) {
8666       // Determine which correction we picked.
8667       Decl *Canonical = Result->getCanonicalDecl();
8668       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8669            I != E; ++I)
8670         if ((*I)->getCanonicalDecl() == Canonical)
8671           Correction.setCorrectionDecl(*I);
8672 
8673       // Let Sema know about the correction.
8674       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8675       SemaRef.diagnoseTypo(
8676           Correction,
8677           SemaRef.PDiag(IsLocalFriend
8678                           ? diag::err_no_matching_local_friend_suggest
8679                           : diag::err_member_decl_does_not_match_suggest)
8680             << Name << NewDC << IsDefinition);
8681       return Result;
8682     }
8683 
8684     // Pretend the typo correction never occurred
8685     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8686                               ExtraArgs.D.getIdentifierLoc());
8687     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8688     Previous.clear();
8689     Previous.setLookupName(Name);
8690   }
8691 
8692   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8693       << Name << NewDC << IsDefinition << NewFD->getLocation();
8694 
8695   bool NewFDisConst = false;
8696   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8697     NewFDisConst = NewMD->isConst();
8698 
8699   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8700        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8701        NearMatch != NearMatchEnd; ++NearMatch) {
8702     FunctionDecl *FD = NearMatch->first;
8703     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8704     bool FDisConst = MD && MD->isConst();
8705     bool IsMember = MD || !IsLocalFriend;
8706 
8707     // FIXME: These notes are poorly worded for the local friend case.
8708     if (unsigned Idx = NearMatch->second) {
8709       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8710       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8711       if (Loc.isInvalid()) Loc = FD->getLocation();
8712       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8713                                  : diag::note_local_decl_close_param_match)
8714         << Idx << FDParam->getType()
8715         << NewFD->getParamDecl(Idx - 1)->getType();
8716     } else if (FDisConst != NewFDisConst) {
8717       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8718           << NewFDisConst << FD->getSourceRange().getEnd()
8719           << (NewFDisConst
8720                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8721                                                  .getConstQualifierLoc())
8722                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8723                                                    .getRParenLoc()
8724                                                    .getLocWithOffset(1),
8725                                                " const"));
8726     } else
8727       SemaRef.Diag(FD->getLocation(),
8728                    IsMember ? diag::note_member_def_close_match
8729                             : diag::note_local_decl_close_match);
8730   }
8731   return nullptr;
8732 }
8733 
8734 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8735   switch (D.getDeclSpec().getStorageClassSpec()) {
8736   default: llvm_unreachable("Unknown storage class!");
8737   case DeclSpec::SCS_auto:
8738   case DeclSpec::SCS_register:
8739   case DeclSpec::SCS_mutable:
8740     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8741                  diag::err_typecheck_sclass_func);
8742     D.getMutableDeclSpec().ClearStorageClassSpecs();
8743     D.setInvalidType();
8744     break;
8745   case DeclSpec::SCS_unspecified: break;
8746   case DeclSpec::SCS_extern:
8747     if (D.getDeclSpec().isExternInLinkageSpec())
8748       return SC_None;
8749     return SC_Extern;
8750   case DeclSpec::SCS_static: {
8751     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8752       // C99 6.7.1p5:
8753       //   The declaration of an identifier for a function that has
8754       //   block scope shall have no explicit storage-class specifier
8755       //   other than extern
8756       // See also (C++ [dcl.stc]p4).
8757       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8758                    diag::err_static_block_func);
8759       break;
8760     } else
8761       return SC_Static;
8762   }
8763   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8764   }
8765 
8766   // No explicit storage class has already been returned
8767   return SC_None;
8768 }
8769 
8770 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8771                                            DeclContext *DC, QualType &R,
8772                                            TypeSourceInfo *TInfo,
8773                                            StorageClass SC,
8774                                            bool &IsVirtualOkay) {
8775   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8776   DeclarationName Name = NameInfo.getName();
8777 
8778   FunctionDecl *NewFD = nullptr;
8779   bool isInline = D.getDeclSpec().isInlineSpecified();
8780 
8781   if (!SemaRef.getLangOpts().CPlusPlus) {
8782     // Determine whether the function was written with a prototype. This is
8783     // true when:
8784     //   - there is a prototype in the declarator, or
8785     //   - the type R of the function is some kind of typedef or other non-
8786     //     attributed reference to a type name (which eventually refers to a
8787     //     function type). Note, we can't always look at the adjusted type to
8788     //     check this case because attributes may cause a non-function
8789     //     declarator to still have a function type. e.g.,
8790     //       typedef void func(int a);
8791     //       __attribute__((noreturn)) func other_func; // This has a prototype
8792     bool HasPrototype =
8793         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8794         (D.getDeclSpec().isTypeRep() &&
8795          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8796         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8797     assert(
8798         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8799         "Strict prototypes are required");
8800 
8801     NewFD = FunctionDecl::Create(
8802         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8803         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8804         ConstexprSpecKind::Unspecified,
8805         /*TrailingRequiresClause=*/nullptr);
8806     if (D.isInvalidType())
8807       NewFD->setInvalidDecl();
8808 
8809     return NewFD;
8810   }
8811 
8812   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8813 
8814   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8815   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8816     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8817                  diag::err_constexpr_wrong_decl_kind)
8818         << static_cast<int>(ConstexprKind);
8819     ConstexprKind = ConstexprSpecKind::Unspecified;
8820     D.getMutableDeclSpec().ClearConstexprSpec();
8821   }
8822   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8823 
8824   // Check that the return type is not an abstract class type.
8825   // For record types, this is done by the AbstractClassUsageDiagnoser once
8826   // the class has been completely parsed.
8827   if (!DC->isRecord() &&
8828       SemaRef.RequireNonAbstractType(
8829           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8830           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8831     D.setInvalidType();
8832 
8833   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8834     // This is a C++ constructor declaration.
8835     assert(DC->isRecord() &&
8836            "Constructors can only be declared in a member context");
8837 
8838     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8839     return CXXConstructorDecl::Create(
8840         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8841         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8842         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8843         InheritedConstructor(), TrailingRequiresClause);
8844 
8845   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8846     // This is a C++ destructor declaration.
8847     if (DC->isRecord()) {
8848       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8849       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8850       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8851           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8852           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8853           /*isImplicitlyDeclared=*/false, ConstexprKind,
8854           TrailingRequiresClause);
8855       // User defined destructors start as not selected if the class definition is still
8856       // not done.
8857       if (Record->isBeingDefined())
8858         NewDD->setIneligibleOrNotSelected(true);
8859 
8860       // If the destructor needs an implicit exception specification, set it
8861       // now. FIXME: It'd be nice to be able to create the right type to start
8862       // with, but the type needs to reference the destructor declaration.
8863       if (SemaRef.getLangOpts().CPlusPlus11)
8864         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8865 
8866       IsVirtualOkay = true;
8867       return NewDD;
8868 
8869     } else {
8870       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8871       D.setInvalidType();
8872 
8873       // Create a FunctionDecl to satisfy the function definition parsing
8874       // code path.
8875       return FunctionDecl::Create(
8876           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8877           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8878           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8879     }
8880 
8881   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8882     if (!DC->isRecord()) {
8883       SemaRef.Diag(D.getIdentifierLoc(),
8884            diag::err_conv_function_not_member);
8885       return nullptr;
8886     }
8887 
8888     SemaRef.CheckConversionDeclarator(D, R, SC);
8889     if (D.isInvalidType())
8890       return nullptr;
8891 
8892     IsVirtualOkay = true;
8893     return CXXConversionDecl::Create(
8894         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8895         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8896         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8897         TrailingRequiresClause);
8898 
8899   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8900     if (TrailingRequiresClause)
8901       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8902                    diag::err_trailing_requires_clause_on_deduction_guide)
8903           << TrailingRequiresClause->getSourceRange();
8904     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8905 
8906     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8907                                          ExplicitSpecifier, NameInfo, R, TInfo,
8908                                          D.getEndLoc());
8909   } else if (DC->isRecord()) {
8910     // If the name of the function is the same as the name of the record,
8911     // then this must be an invalid constructor that has a return type.
8912     // (The parser checks for a return type and makes the declarator a
8913     // constructor if it has no return type).
8914     if (Name.getAsIdentifierInfo() &&
8915         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8916       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8917         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8918         << SourceRange(D.getIdentifierLoc());
8919       return nullptr;
8920     }
8921 
8922     // This is a C++ method declaration.
8923     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8924         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8925         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8926         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8927     IsVirtualOkay = !Ret->isStatic();
8928     return Ret;
8929   } else {
8930     bool isFriend =
8931         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8932     if (!isFriend && SemaRef.CurContext->isRecord())
8933       return nullptr;
8934 
8935     // Determine whether the function was written with a
8936     // prototype. This true when:
8937     //   - we're in C++ (where every function has a prototype),
8938     return FunctionDecl::Create(
8939         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8940         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8941         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8942   }
8943 }
8944 
8945 enum OpenCLParamType {
8946   ValidKernelParam,
8947   PtrPtrKernelParam,
8948   PtrKernelParam,
8949   InvalidAddrSpacePtrKernelParam,
8950   InvalidKernelParam,
8951   RecordKernelParam
8952 };
8953 
8954 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8955   // Size dependent types are just typedefs to normal integer types
8956   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8957   // integers other than by their names.
8958   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8959 
8960   // Remove typedefs one by one until we reach a typedef
8961   // for a size dependent type.
8962   QualType DesugaredTy = Ty;
8963   do {
8964     ArrayRef<StringRef> Names(SizeTypeNames);
8965     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8966     if (Names.end() != Match)
8967       return true;
8968 
8969     Ty = DesugaredTy;
8970     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8971   } while (DesugaredTy != Ty);
8972 
8973   return false;
8974 }
8975 
8976 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8977   if (PT->isDependentType())
8978     return InvalidKernelParam;
8979 
8980   if (PT->isPointerType() || PT->isReferenceType()) {
8981     QualType PointeeType = PT->getPointeeType();
8982     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8983         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8984         PointeeType.getAddressSpace() == LangAS::Default)
8985       return InvalidAddrSpacePtrKernelParam;
8986 
8987     if (PointeeType->isPointerType()) {
8988       // This is a pointer to pointer parameter.
8989       // Recursively check inner type.
8990       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8991       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8992           ParamKind == InvalidKernelParam)
8993         return ParamKind;
8994 
8995       return PtrPtrKernelParam;
8996     }
8997 
8998     // C++ for OpenCL v1.0 s2.4:
8999     // Moreover the types used in parameters of the kernel functions must be:
9000     // Standard layout types for pointer parameters. The same applies to
9001     // reference if an implementation supports them in kernel parameters.
9002     if (S.getLangOpts().OpenCLCPlusPlus &&
9003         !S.getOpenCLOptions().isAvailableOption(
9004             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9005         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9006         !PointeeType->isStandardLayoutType())
9007       return InvalidKernelParam;
9008 
9009     return PtrKernelParam;
9010   }
9011 
9012   // OpenCL v1.2 s6.9.k:
9013   // Arguments to kernel functions in a program cannot be declared with the
9014   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9015   // uintptr_t or a struct and/or union that contain fields declared to be one
9016   // of these built-in scalar types.
9017   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9018     return InvalidKernelParam;
9019 
9020   if (PT->isImageType())
9021     return PtrKernelParam;
9022 
9023   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9024     return InvalidKernelParam;
9025 
9026   // OpenCL extension spec v1.2 s9.5:
9027   // This extension adds support for half scalar and vector types as built-in
9028   // types that can be used for arithmetic operations, conversions etc.
9029   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9030       PT->isHalfType())
9031     return InvalidKernelParam;
9032 
9033   // Look into an array argument to check if it has a forbidden type.
9034   if (PT->isArrayType()) {
9035     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9036     // Call ourself to check an underlying type of an array. Since the
9037     // getPointeeOrArrayElementType returns an innermost type which is not an
9038     // array, this recursive call only happens once.
9039     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9040   }
9041 
9042   // C++ for OpenCL v1.0 s2.4:
9043   // Moreover the types used in parameters of the kernel functions must be:
9044   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9045   // types) for parameters passed by value;
9046   if (S.getLangOpts().OpenCLCPlusPlus &&
9047       !S.getOpenCLOptions().isAvailableOption(
9048           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9049       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9050     return InvalidKernelParam;
9051 
9052   if (PT->isRecordType())
9053     return RecordKernelParam;
9054 
9055   return ValidKernelParam;
9056 }
9057 
9058 static void checkIsValidOpenCLKernelParameter(
9059   Sema &S,
9060   Declarator &D,
9061   ParmVarDecl *Param,
9062   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9063   QualType PT = Param->getType();
9064 
9065   // Cache the valid types we encounter to avoid rechecking structs that are
9066   // used again
9067   if (ValidTypes.count(PT.getTypePtr()))
9068     return;
9069 
9070   switch (getOpenCLKernelParameterType(S, PT)) {
9071   case PtrPtrKernelParam:
9072     // OpenCL v3.0 s6.11.a:
9073     // A kernel function argument cannot be declared as a pointer to a pointer
9074     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9075     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9076       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9077       D.setInvalidType();
9078       return;
9079     }
9080 
9081     ValidTypes.insert(PT.getTypePtr());
9082     return;
9083 
9084   case InvalidAddrSpacePtrKernelParam:
9085     // OpenCL v1.0 s6.5:
9086     // __kernel function arguments declared to be a pointer of a type can point
9087     // to one of the following address spaces only : __global, __local or
9088     // __constant.
9089     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9090     D.setInvalidType();
9091     return;
9092 
9093     // OpenCL v1.2 s6.9.k:
9094     // Arguments to kernel functions in a program cannot be declared with the
9095     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9096     // uintptr_t or a struct and/or union that contain fields declared to be
9097     // one of these built-in scalar types.
9098 
9099   case InvalidKernelParam:
9100     // OpenCL v1.2 s6.8 n:
9101     // A kernel function argument cannot be declared
9102     // of event_t type.
9103     // Do not diagnose half type since it is diagnosed as invalid argument
9104     // type for any function elsewhere.
9105     if (!PT->isHalfType()) {
9106       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9107 
9108       // Explain what typedefs are involved.
9109       const TypedefType *Typedef = nullptr;
9110       while ((Typedef = PT->getAs<TypedefType>())) {
9111         SourceLocation Loc = Typedef->getDecl()->getLocation();
9112         // SourceLocation may be invalid for a built-in type.
9113         if (Loc.isValid())
9114           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9115         PT = Typedef->desugar();
9116       }
9117     }
9118 
9119     D.setInvalidType();
9120     return;
9121 
9122   case PtrKernelParam:
9123   case ValidKernelParam:
9124     ValidTypes.insert(PT.getTypePtr());
9125     return;
9126 
9127   case RecordKernelParam:
9128     break;
9129   }
9130 
9131   // Track nested structs we will inspect
9132   SmallVector<const Decl *, 4> VisitStack;
9133 
9134   // Track where we are in the nested structs. Items will migrate from
9135   // VisitStack to HistoryStack as we do the DFS for bad field.
9136   SmallVector<const FieldDecl *, 4> HistoryStack;
9137   HistoryStack.push_back(nullptr);
9138 
9139   // At this point we already handled everything except of a RecordType or
9140   // an ArrayType of a RecordType.
9141   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9142   const RecordType *RecTy =
9143       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9144   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9145 
9146   VisitStack.push_back(RecTy->getDecl());
9147   assert(VisitStack.back() && "First decl null?");
9148 
9149   do {
9150     const Decl *Next = VisitStack.pop_back_val();
9151     if (!Next) {
9152       assert(!HistoryStack.empty());
9153       // Found a marker, we have gone up a level
9154       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9155         ValidTypes.insert(Hist->getType().getTypePtr());
9156 
9157       continue;
9158     }
9159 
9160     // Adds everything except the original parameter declaration (which is not a
9161     // field itself) to the history stack.
9162     const RecordDecl *RD;
9163     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9164       HistoryStack.push_back(Field);
9165 
9166       QualType FieldTy = Field->getType();
9167       // Other field types (known to be valid or invalid) are handled while we
9168       // walk around RecordDecl::fields().
9169       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9170              "Unexpected type.");
9171       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9172 
9173       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9174     } else {
9175       RD = cast<RecordDecl>(Next);
9176     }
9177 
9178     // Add a null marker so we know when we've gone back up a level
9179     VisitStack.push_back(nullptr);
9180 
9181     for (const auto *FD : RD->fields()) {
9182       QualType QT = FD->getType();
9183 
9184       if (ValidTypes.count(QT.getTypePtr()))
9185         continue;
9186 
9187       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9188       if (ParamType == ValidKernelParam)
9189         continue;
9190 
9191       if (ParamType == RecordKernelParam) {
9192         VisitStack.push_back(FD);
9193         continue;
9194       }
9195 
9196       // OpenCL v1.2 s6.9.p:
9197       // Arguments to kernel functions that are declared to be a struct or union
9198       // do not allow OpenCL objects to be passed as elements of the struct or
9199       // union.
9200       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9201           ParamType == InvalidAddrSpacePtrKernelParam) {
9202         S.Diag(Param->getLocation(),
9203                diag::err_record_with_pointers_kernel_param)
9204           << PT->isUnionType()
9205           << PT;
9206       } else {
9207         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9208       }
9209 
9210       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9211           << OrigRecDecl->getDeclName();
9212 
9213       // We have an error, now let's go back up through history and show where
9214       // the offending field came from
9215       for (ArrayRef<const FieldDecl *>::const_iterator
9216                I = HistoryStack.begin() + 1,
9217                E = HistoryStack.end();
9218            I != E; ++I) {
9219         const FieldDecl *OuterField = *I;
9220         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9221           << OuterField->getType();
9222       }
9223 
9224       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9225         << QT->isPointerType()
9226         << QT;
9227       D.setInvalidType();
9228       return;
9229     }
9230   } while (!VisitStack.empty());
9231 }
9232 
9233 /// Find the DeclContext in which a tag is implicitly declared if we see an
9234 /// elaborated type specifier in the specified context, and lookup finds
9235 /// nothing.
9236 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9237   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9238     DC = DC->getParent();
9239   return DC;
9240 }
9241 
9242 /// Find the Scope in which a tag is implicitly declared if we see an
9243 /// elaborated type specifier in the specified context, and lookup finds
9244 /// nothing.
9245 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9246   while (S->isClassScope() ||
9247          (LangOpts.CPlusPlus &&
9248           S->isFunctionPrototypeScope()) ||
9249          ((S->getFlags() & Scope::DeclScope) == 0) ||
9250          (S->getEntity() && S->getEntity()->isTransparentContext()))
9251     S = S->getParent();
9252   return S;
9253 }
9254 
9255 /// Determine whether a declaration matches a known function in namespace std.
9256 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9257                          unsigned BuiltinID) {
9258   switch (BuiltinID) {
9259   case Builtin::BI__GetExceptionInfo:
9260     // No type checking whatsoever.
9261     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9262 
9263   case Builtin::BIaddressof:
9264   case Builtin::BI__addressof:
9265   case Builtin::BIforward:
9266   case Builtin::BImove:
9267   case Builtin::BImove_if_noexcept:
9268   case Builtin::BIas_const: {
9269     // Ensure that we don't treat the algorithm
9270     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9271     // as the builtin std::move.
9272     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9273     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9274   }
9275 
9276   default:
9277     return false;
9278   }
9279 }
9280 
9281 NamedDecl*
9282 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9283                               TypeSourceInfo *TInfo, LookupResult &Previous,
9284                               MultiTemplateParamsArg TemplateParamListsRef,
9285                               bool &AddToScope) {
9286   QualType R = TInfo->getType();
9287 
9288   assert(R->isFunctionType());
9289   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9290     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9291 
9292   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9293   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9294   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9295     if (!TemplateParamLists.empty() &&
9296         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9297       TemplateParamLists.back() = Invented;
9298     else
9299       TemplateParamLists.push_back(Invented);
9300   }
9301 
9302   // TODO: consider using NameInfo for diagnostic.
9303   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9304   DeclarationName Name = NameInfo.getName();
9305   StorageClass SC = getFunctionStorageClass(*this, D);
9306 
9307   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9308     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9309          diag::err_invalid_thread)
9310       << DeclSpec::getSpecifierName(TSCS);
9311 
9312   if (D.isFirstDeclarationOfMember())
9313     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9314                            D.getIdentifierLoc());
9315 
9316   bool isFriend = false;
9317   FunctionTemplateDecl *FunctionTemplate = nullptr;
9318   bool isMemberSpecialization = false;
9319   bool isFunctionTemplateSpecialization = false;
9320 
9321   bool isDependentClassScopeExplicitSpecialization = false;
9322   bool HasExplicitTemplateArgs = false;
9323   TemplateArgumentListInfo TemplateArgs;
9324 
9325   bool isVirtualOkay = false;
9326 
9327   DeclContext *OriginalDC = DC;
9328   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9329 
9330   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9331                                               isVirtualOkay);
9332   if (!NewFD) return nullptr;
9333 
9334   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9335     NewFD->setTopLevelDeclInObjCContainer();
9336 
9337   // Set the lexical context. If this is a function-scope declaration, or has a
9338   // C++ scope specifier, or is the object of a friend declaration, the lexical
9339   // context will be different from the semantic context.
9340   NewFD->setLexicalDeclContext(CurContext);
9341 
9342   if (IsLocalExternDecl)
9343     NewFD->setLocalExternDecl();
9344 
9345   if (getLangOpts().CPlusPlus) {
9346     bool isInline = D.getDeclSpec().isInlineSpecified();
9347     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9348     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9349     isFriend = D.getDeclSpec().isFriendSpecified();
9350     if (isFriend && !isInline && D.isFunctionDefinition()) {
9351       // C++ [class.friend]p5
9352       //   A function can be defined in a friend declaration of a
9353       //   class . . . . Such a function is implicitly inline.
9354       NewFD->setImplicitlyInline();
9355     }
9356 
9357     // If this is a method defined in an __interface, and is not a constructor
9358     // or an overloaded operator, then set the pure flag (isVirtual will already
9359     // return true).
9360     if (const CXXRecordDecl *Parent =
9361           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9362       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9363         NewFD->setPure(true);
9364 
9365       // C++ [class.union]p2
9366       //   A union can have member functions, but not virtual functions.
9367       if (isVirtual && Parent->isUnion()) {
9368         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9369         NewFD->setInvalidDecl();
9370       }
9371       if ((Parent->isClass() || Parent->isStruct()) &&
9372           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9373           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9374           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9375         if (auto *Def = Parent->getDefinition())
9376           Def->setInitMethod(true);
9377       }
9378     }
9379 
9380     SetNestedNameSpecifier(*this, NewFD, D);
9381     isMemberSpecialization = false;
9382     isFunctionTemplateSpecialization = false;
9383     if (D.isInvalidType())
9384       NewFD->setInvalidDecl();
9385 
9386     // Match up the template parameter lists with the scope specifier, then
9387     // determine whether we have a template or a template specialization.
9388     bool Invalid = false;
9389     TemplateParameterList *TemplateParams =
9390         MatchTemplateParametersToScopeSpecifier(
9391             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9392             D.getCXXScopeSpec(),
9393             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9394                 ? D.getName().TemplateId
9395                 : nullptr,
9396             TemplateParamLists, isFriend, isMemberSpecialization,
9397             Invalid);
9398     if (TemplateParams) {
9399       // Check that we can declare a template here.
9400       if (CheckTemplateDeclScope(S, TemplateParams))
9401         NewFD->setInvalidDecl();
9402 
9403       if (TemplateParams->size() > 0) {
9404         // This is a function template
9405 
9406         // A destructor cannot be a template.
9407         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9408           Diag(NewFD->getLocation(), diag::err_destructor_template);
9409           NewFD->setInvalidDecl();
9410         }
9411 
9412         // If we're adding a template to a dependent context, we may need to
9413         // rebuilding some of the types used within the template parameter list,
9414         // now that we know what the current instantiation is.
9415         if (DC->isDependentContext()) {
9416           ContextRAII SavedContext(*this, DC);
9417           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9418             Invalid = true;
9419         }
9420 
9421         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9422                                                         NewFD->getLocation(),
9423                                                         Name, TemplateParams,
9424                                                         NewFD);
9425         FunctionTemplate->setLexicalDeclContext(CurContext);
9426         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9427 
9428         // For source fidelity, store the other template param lists.
9429         if (TemplateParamLists.size() > 1) {
9430           NewFD->setTemplateParameterListsInfo(Context,
9431               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9432                   .drop_back(1));
9433         }
9434       } else {
9435         // This is a function template specialization.
9436         isFunctionTemplateSpecialization = true;
9437         // For source fidelity, store all the template param lists.
9438         if (TemplateParamLists.size() > 0)
9439           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9440 
9441         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9442         if (isFriend) {
9443           // We want to remove the "template<>", found here.
9444           SourceRange RemoveRange = TemplateParams->getSourceRange();
9445 
9446           // If we remove the template<> and the name is not a
9447           // template-id, we're actually silently creating a problem:
9448           // the friend declaration will refer to an untemplated decl,
9449           // and clearly the user wants a template specialization.  So
9450           // we need to insert '<>' after the name.
9451           SourceLocation InsertLoc;
9452           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9453             InsertLoc = D.getName().getSourceRange().getEnd();
9454             InsertLoc = getLocForEndOfToken(InsertLoc);
9455           }
9456 
9457           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9458             << Name << RemoveRange
9459             << FixItHint::CreateRemoval(RemoveRange)
9460             << FixItHint::CreateInsertion(InsertLoc, "<>");
9461           Invalid = true;
9462         }
9463       }
9464     } else {
9465       // Check that we can declare a template here.
9466       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9467           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9468         NewFD->setInvalidDecl();
9469 
9470       // All template param lists were matched against the scope specifier:
9471       // this is NOT (an explicit specialization of) a template.
9472       if (TemplateParamLists.size() > 0)
9473         // For source fidelity, store all the template param lists.
9474         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9475     }
9476 
9477     if (Invalid) {
9478       NewFD->setInvalidDecl();
9479       if (FunctionTemplate)
9480         FunctionTemplate->setInvalidDecl();
9481     }
9482 
9483     // C++ [dcl.fct.spec]p5:
9484     //   The virtual specifier shall only be used in declarations of
9485     //   nonstatic class member functions that appear within a
9486     //   member-specification of a class declaration; see 10.3.
9487     //
9488     if (isVirtual && !NewFD->isInvalidDecl()) {
9489       if (!isVirtualOkay) {
9490         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9491              diag::err_virtual_non_function);
9492       } else if (!CurContext->isRecord()) {
9493         // 'virtual' was specified outside of the class.
9494         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9495              diag::err_virtual_out_of_class)
9496           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9497       } else if (NewFD->getDescribedFunctionTemplate()) {
9498         // C++ [temp.mem]p3:
9499         //  A member function template shall not be virtual.
9500         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9501              diag::err_virtual_member_function_template)
9502           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9503       } else {
9504         // Okay: Add virtual to the method.
9505         NewFD->setVirtualAsWritten(true);
9506       }
9507 
9508       if (getLangOpts().CPlusPlus14 &&
9509           NewFD->getReturnType()->isUndeducedType())
9510         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9511     }
9512 
9513     if (getLangOpts().CPlusPlus14 &&
9514         (NewFD->isDependentContext() ||
9515          (isFriend && CurContext->isDependentContext())) &&
9516         NewFD->getReturnType()->isUndeducedType()) {
9517       // If the function template is referenced directly (for instance, as a
9518       // member of the current instantiation), pretend it has a dependent type.
9519       // This is not really justified by the standard, but is the only sane
9520       // thing to do.
9521       // FIXME: For a friend function, we have not marked the function as being
9522       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9523       const FunctionProtoType *FPT =
9524           NewFD->getType()->castAs<FunctionProtoType>();
9525       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9526       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9527                                              FPT->getExtProtoInfo()));
9528     }
9529 
9530     // C++ [dcl.fct.spec]p3:
9531     //  The inline specifier shall not appear on a block scope function
9532     //  declaration.
9533     if (isInline && !NewFD->isInvalidDecl()) {
9534       if (CurContext->isFunctionOrMethod()) {
9535         // 'inline' is not allowed on block scope function declaration.
9536         Diag(D.getDeclSpec().getInlineSpecLoc(),
9537              diag::err_inline_declaration_block_scope) << Name
9538           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9539       }
9540     }
9541 
9542     // C++ [dcl.fct.spec]p6:
9543     //  The explicit specifier shall be used only in the declaration of a
9544     //  constructor or conversion function within its class definition;
9545     //  see 12.3.1 and 12.3.2.
9546     if (hasExplicit && !NewFD->isInvalidDecl() &&
9547         !isa<CXXDeductionGuideDecl>(NewFD)) {
9548       if (!CurContext->isRecord()) {
9549         // 'explicit' was specified outside of the class.
9550         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9551              diag::err_explicit_out_of_class)
9552             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9553       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9554                  !isa<CXXConversionDecl>(NewFD)) {
9555         // 'explicit' was specified on a function that wasn't a constructor
9556         // or conversion function.
9557         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9558              diag::err_explicit_non_ctor_or_conv_function)
9559             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9560       }
9561     }
9562 
9563     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9564     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9565       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9566       // are implicitly inline.
9567       NewFD->setImplicitlyInline();
9568 
9569       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9570       // be either constructors or to return a literal type. Therefore,
9571       // destructors cannot be declared constexpr.
9572       if (isa<CXXDestructorDecl>(NewFD) &&
9573           (!getLangOpts().CPlusPlus20 ||
9574            ConstexprKind == ConstexprSpecKind::Consteval)) {
9575         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9576             << static_cast<int>(ConstexprKind);
9577         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9578                                     ? ConstexprSpecKind::Unspecified
9579                                     : ConstexprSpecKind::Constexpr);
9580       }
9581       // C++20 [dcl.constexpr]p2: An allocation function, or a
9582       // deallocation function shall not be declared with the consteval
9583       // specifier.
9584       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9585           (NewFD->getOverloadedOperator() == OO_New ||
9586            NewFD->getOverloadedOperator() == OO_Array_New ||
9587            NewFD->getOverloadedOperator() == OO_Delete ||
9588            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9589         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9590              diag::err_invalid_consteval_decl_kind)
9591             << NewFD;
9592         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9593       }
9594     }
9595 
9596     // If __module_private__ was specified, mark the function accordingly.
9597     if (D.getDeclSpec().isModulePrivateSpecified()) {
9598       if (isFunctionTemplateSpecialization) {
9599         SourceLocation ModulePrivateLoc
9600           = D.getDeclSpec().getModulePrivateSpecLoc();
9601         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9602           << 0
9603           << FixItHint::CreateRemoval(ModulePrivateLoc);
9604       } else {
9605         NewFD->setModulePrivate();
9606         if (FunctionTemplate)
9607           FunctionTemplate->setModulePrivate();
9608       }
9609     }
9610 
9611     if (isFriend) {
9612       if (FunctionTemplate) {
9613         FunctionTemplate->setObjectOfFriendDecl();
9614         FunctionTemplate->setAccess(AS_public);
9615       }
9616       NewFD->setObjectOfFriendDecl();
9617       NewFD->setAccess(AS_public);
9618     }
9619 
9620     // If a function is defined as defaulted or deleted, mark it as such now.
9621     // We'll do the relevant checks on defaulted / deleted functions later.
9622     switch (D.getFunctionDefinitionKind()) {
9623     case FunctionDefinitionKind::Declaration:
9624     case FunctionDefinitionKind::Definition:
9625       break;
9626 
9627     case FunctionDefinitionKind::Defaulted:
9628       NewFD->setDefaulted();
9629       break;
9630 
9631     case FunctionDefinitionKind::Deleted:
9632       NewFD->setDeletedAsWritten();
9633       break;
9634     }
9635 
9636     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9637         D.isFunctionDefinition()) {
9638       // C++ [class.mfct]p2:
9639       //   A member function may be defined (8.4) in its class definition, in
9640       //   which case it is an inline member function (7.1.2)
9641       NewFD->setImplicitlyInline();
9642     }
9643 
9644     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9645         !CurContext->isRecord()) {
9646       // C++ [class.static]p1:
9647       //   A data or function member of a class may be declared static
9648       //   in a class definition, in which case it is a static member of
9649       //   the class.
9650 
9651       // Complain about the 'static' specifier if it's on an out-of-line
9652       // member function definition.
9653 
9654       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9655       // member function template declaration and class member template
9656       // declaration (MSVC versions before 2015), warn about this.
9657       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9658            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9659              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9660            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9661            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9662         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9663     }
9664 
9665     // C++11 [except.spec]p15:
9666     //   A deallocation function with no exception-specification is treated
9667     //   as if it were specified with noexcept(true).
9668     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9669     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9670          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9671         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9672       NewFD->setType(Context.getFunctionType(
9673           FPT->getReturnType(), FPT->getParamTypes(),
9674           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9675   }
9676 
9677   // Filter out previous declarations that don't match the scope.
9678   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9679                        D.getCXXScopeSpec().isNotEmpty() ||
9680                        isMemberSpecialization ||
9681                        isFunctionTemplateSpecialization);
9682 
9683   // Handle GNU asm-label extension (encoded as an attribute).
9684   if (Expr *E = (Expr*) D.getAsmLabel()) {
9685     // The parser guarantees this is a string.
9686     StringLiteral *SE = cast<StringLiteral>(E);
9687     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9688                                         /*IsLiteralLabel=*/true,
9689                                         SE->getStrTokenLoc(0)));
9690   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9691     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9692       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9693     if (I != ExtnameUndeclaredIdentifiers.end()) {
9694       if (isDeclExternC(NewFD)) {
9695         NewFD->addAttr(I->second);
9696         ExtnameUndeclaredIdentifiers.erase(I);
9697       } else
9698         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9699             << /*Variable*/0 << NewFD;
9700     }
9701   }
9702 
9703   // Copy the parameter declarations from the declarator D to the function
9704   // declaration NewFD, if they are available.  First scavenge them into Params.
9705   SmallVector<ParmVarDecl*, 16> Params;
9706   unsigned FTIIdx;
9707   if (D.isFunctionDeclarator(FTIIdx)) {
9708     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9709 
9710     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9711     // function that takes no arguments, not a function that takes a
9712     // single void argument.
9713     // We let through "const void" here because Sema::GetTypeForDeclarator
9714     // already checks for that case.
9715     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9716       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9717         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9718         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9719         Param->setDeclContext(NewFD);
9720         Params.push_back(Param);
9721 
9722         if (Param->isInvalidDecl())
9723           NewFD->setInvalidDecl();
9724       }
9725     }
9726 
9727     if (!getLangOpts().CPlusPlus) {
9728       // In C, find all the tag declarations from the prototype and move them
9729       // into the function DeclContext. Remove them from the surrounding tag
9730       // injection context of the function, which is typically but not always
9731       // the TU.
9732       DeclContext *PrototypeTagContext =
9733           getTagInjectionContext(NewFD->getLexicalDeclContext());
9734       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9735         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9736 
9737         // We don't want to reparent enumerators. Look at their parent enum
9738         // instead.
9739         if (!TD) {
9740           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9741             TD = cast<EnumDecl>(ECD->getDeclContext());
9742         }
9743         if (!TD)
9744           continue;
9745         DeclContext *TagDC = TD->getLexicalDeclContext();
9746         if (!TagDC->containsDecl(TD))
9747           continue;
9748         TagDC->removeDecl(TD);
9749         TD->setDeclContext(NewFD);
9750         NewFD->addDecl(TD);
9751 
9752         // Preserve the lexical DeclContext if it is not the surrounding tag
9753         // injection context of the FD. In this example, the semantic context of
9754         // E will be f and the lexical context will be S, while both the
9755         // semantic and lexical contexts of S will be f:
9756         //   void f(struct S { enum E { a } f; } s);
9757         if (TagDC != PrototypeTagContext)
9758           TD->setLexicalDeclContext(TagDC);
9759       }
9760     }
9761   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9762     // When we're declaring a function with a typedef, typeof, etc as in the
9763     // following example, we'll need to synthesize (unnamed)
9764     // parameters for use in the declaration.
9765     //
9766     // @code
9767     // typedef void fn(int);
9768     // fn f;
9769     // @endcode
9770 
9771     // Synthesize a parameter for each argument type.
9772     for (const auto &AI : FT->param_types()) {
9773       ParmVarDecl *Param =
9774           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9775       Param->setScopeInfo(0, Params.size());
9776       Params.push_back(Param);
9777     }
9778   } else {
9779     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9780            "Should not need args for typedef of non-prototype fn");
9781   }
9782 
9783   // Finally, we know we have the right number of parameters, install them.
9784   NewFD->setParams(Params);
9785 
9786   if (D.getDeclSpec().isNoreturnSpecified())
9787     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9788                                            D.getDeclSpec().getNoreturnSpecLoc(),
9789                                            AttributeCommonInfo::AS_Keyword));
9790 
9791   // Functions returning a variably modified type violate C99 6.7.5.2p2
9792   // because all functions have linkage.
9793   if (!NewFD->isInvalidDecl() &&
9794       NewFD->getReturnType()->isVariablyModifiedType()) {
9795     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9796     NewFD->setInvalidDecl();
9797   }
9798 
9799   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9800   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9801       !NewFD->hasAttr<SectionAttr>())
9802     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9803         Context, PragmaClangTextSection.SectionName,
9804         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9805 
9806   // Apply an implicit SectionAttr if #pragma code_seg is active.
9807   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9808       !NewFD->hasAttr<SectionAttr>()) {
9809     NewFD->addAttr(SectionAttr::CreateImplicit(
9810         Context, CodeSegStack.CurrentValue->getString(),
9811         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9812         SectionAttr::Declspec_allocate));
9813     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9814                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9815                          ASTContext::PSF_Read,
9816                      NewFD))
9817       NewFD->dropAttr<SectionAttr>();
9818   }
9819 
9820   // Apply an implicit CodeSegAttr from class declspec or
9821   // apply an implicit SectionAttr from #pragma code_seg if active.
9822   if (!NewFD->hasAttr<CodeSegAttr>()) {
9823     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9824                                                                  D.isFunctionDefinition())) {
9825       NewFD->addAttr(SAttr);
9826     }
9827   }
9828 
9829   // Handle attributes.
9830   ProcessDeclAttributes(S, NewFD, D);
9831 
9832   if (getLangOpts().OpenCL) {
9833     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9834     // type declaration will generate a compilation error.
9835     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9836     if (AddressSpace != LangAS::Default) {
9837       Diag(NewFD->getLocation(),
9838            diag::err_opencl_return_value_with_address_space);
9839       NewFD->setInvalidDecl();
9840     }
9841   }
9842 
9843   if (!getLangOpts().CPlusPlus) {
9844     // Perform semantic checking on the function declaration.
9845     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9846       CheckMain(NewFD, D.getDeclSpec());
9847 
9848     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9849       CheckMSVCRTEntryPoint(NewFD);
9850 
9851     if (!NewFD->isInvalidDecl())
9852       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9853                                                   isMemberSpecialization,
9854                                                   D.isFunctionDefinition()));
9855     else if (!Previous.empty())
9856       // Recover gracefully from an invalid redeclaration.
9857       D.setRedeclaration(true);
9858     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9859             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9860            "previous declaration set still overloaded");
9861 
9862     // Diagnose no-prototype function declarations with calling conventions that
9863     // don't support variadic calls. Only do this in C and do it after merging
9864     // possibly prototyped redeclarations.
9865     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9866     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9867       CallingConv CC = FT->getExtInfo().getCC();
9868       if (!supportsVariadicCall(CC)) {
9869         // Windows system headers sometimes accidentally use stdcall without
9870         // (void) parameters, so we relax this to a warning.
9871         int DiagID =
9872             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9873         Diag(NewFD->getLocation(), DiagID)
9874             << FunctionType::getNameForCallConv(CC);
9875       }
9876     }
9877 
9878    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9879        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9880      checkNonTrivialCUnion(NewFD->getReturnType(),
9881                            NewFD->getReturnTypeSourceRange().getBegin(),
9882                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9883   } else {
9884     // C++11 [replacement.functions]p3:
9885     //  The program's definitions shall not be specified as inline.
9886     //
9887     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9888     //
9889     // Suppress the diagnostic if the function is __attribute__((used)), since
9890     // that forces an external definition to be emitted.
9891     if (D.getDeclSpec().isInlineSpecified() &&
9892         NewFD->isReplaceableGlobalAllocationFunction() &&
9893         !NewFD->hasAttr<UsedAttr>())
9894       Diag(D.getDeclSpec().getInlineSpecLoc(),
9895            diag::ext_operator_new_delete_declared_inline)
9896         << NewFD->getDeclName();
9897 
9898     // If the declarator is a template-id, translate the parser's template
9899     // argument list into our AST format.
9900     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9901       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9902       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9903       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9904       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9905                                          TemplateId->NumArgs);
9906       translateTemplateArguments(TemplateArgsPtr,
9907                                  TemplateArgs);
9908 
9909       HasExplicitTemplateArgs = true;
9910 
9911       if (NewFD->isInvalidDecl()) {
9912         HasExplicitTemplateArgs = false;
9913       } else if (FunctionTemplate) {
9914         // Function template with explicit template arguments.
9915         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9916           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9917 
9918         HasExplicitTemplateArgs = false;
9919       } else {
9920         assert((isFunctionTemplateSpecialization ||
9921                 D.getDeclSpec().isFriendSpecified()) &&
9922                "should have a 'template<>' for this decl");
9923         // "friend void foo<>(int);" is an implicit specialization decl.
9924         isFunctionTemplateSpecialization = true;
9925       }
9926     } else if (isFriend && isFunctionTemplateSpecialization) {
9927       // This combination is only possible in a recovery case;  the user
9928       // wrote something like:
9929       //   template <> friend void foo(int);
9930       // which we're recovering from as if the user had written:
9931       //   friend void foo<>(int);
9932       // Go ahead and fake up a template id.
9933       HasExplicitTemplateArgs = true;
9934       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9935       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9936     }
9937 
9938     // We do not add HD attributes to specializations here because
9939     // they may have different constexpr-ness compared to their
9940     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9941     // may end up with different effective targets. Instead, a
9942     // specialization inherits its target attributes from its template
9943     // in the CheckFunctionTemplateSpecialization() call below.
9944     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9945       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9946 
9947     // If it's a friend (and only if it's a friend), it's possible
9948     // that either the specialized function type or the specialized
9949     // template is dependent, and therefore matching will fail.  In
9950     // this case, don't check the specialization yet.
9951     if (isFunctionTemplateSpecialization && isFriend &&
9952         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9953          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9954              TemplateArgs.arguments()))) {
9955       assert(HasExplicitTemplateArgs &&
9956              "friend function specialization without template args");
9957       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9958                                                        Previous))
9959         NewFD->setInvalidDecl();
9960     } else if (isFunctionTemplateSpecialization) {
9961       if (CurContext->isDependentContext() && CurContext->isRecord()
9962           && !isFriend) {
9963         isDependentClassScopeExplicitSpecialization = true;
9964       } else if (!NewFD->isInvalidDecl() &&
9965                  CheckFunctionTemplateSpecialization(
9966                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9967                      Previous))
9968         NewFD->setInvalidDecl();
9969 
9970       // C++ [dcl.stc]p1:
9971       //   A storage-class-specifier shall not be specified in an explicit
9972       //   specialization (14.7.3)
9973       FunctionTemplateSpecializationInfo *Info =
9974           NewFD->getTemplateSpecializationInfo();
9975       if (Info && SC != SC_None) {
9976         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9977           Diag(NewFD->getLocation(),
9978                diag::err_explicit_specialization_inconsistent_storage_class)
9979             << SC
9980             << FixItHint::CreateRemoval(
9981                                       D.getDeclSpec().getStorageClassSpecLoc());
9982 
9983         else
9984           Diag(NewFD->getLocation(),
9985                diag::ext_explicit_specialization_storage_class)
9986             << FixItHint::CreateRemoval(
9987                                       D.getDeclSpec().getStorageClassSpecLoc());
9988       }
9989     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9990       if (CheckMemberSpecialization(NewFD, Previous))
9991           NewFD->setInvalidDecl();
9992     }
9993 
9994     // Perform semantic checking on the function declaration.
9995     if (!isDependentClassScopeExplicitSpecialization) {
9996       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9997         CheckMain(NewFD, D.getDeclSpec());
9998 
9999       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10000         CheckMSVCRTEntryPoint(NewFD);
10001 
10002       if (!NewFD->isInvalidDecl())
10003         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10004                                                     isMemberSpecialization,
10005                                                     D.isFunctionDefinition()));
10006       else if (!Previous.empty())
10007         // Recover gracefully from an invalid redeclaration.
10008         D.setRedeclaration(true);
10009     }
10010 
10011     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10012             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10013            "previous declaration set still overloaded");
10014 
10015     NamedDecl *PrincipalDecl = (FunctionTemplate
10016                                 ? cast<NamedDecl>(FunctionTemplate)
10017                                 : NewFD);
10018 
10019     if (isFriend && NewFD->getPreviousDecl()) {
10020       AccessSpecifier Access = AS_public;
10021       if (!NewFD->isInvalidDecl())
10022         Access = NewFD->getPreviousDecl()->getAccess();
10023 
10024       NewFD->setAccess(Access);
10025       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10026     }
10027 
10028     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10029         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10030       PrincipalDecl->setNonMemberOperator();
10031 
10032     // If we have a function template, check the template parameter
10033     // list. This will check and merge default template arguments.
10034     if (FunctionTemplate) {
10035       FunctionTemplateDecl *PrevTemplate =
10036                                      FunctionTemplate->getPreviousDecl();
10037       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10038                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10039                                     : nullptr,
10040                             D.getDeclSpec().isFriendSpecified()
10041                               ? (D.isFunctionDefinition()
10042                                    ? TPC_FriendFunctionTemplateDefinition
10043                                    : TPC_FriendFunctionTemplate)
10044                               : (D.getCXXScopeSpec().isSet() &&
10045                                  DC && DC->isRecord() &&
10046                                  DC->isDependentContext())
10047                                   ? TPC_ClassTemplateMember
10048                                   : TPC_FunctionTemplate);
10049     }
10050 
10051     if (NewFD->isInvalidDecl()) {
10052       // Ignore all the rest of this.
10053     } else if (!D.isRedeclaration()) {
10054       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10055                                        AddToScope };
10056       // Fake up an access specifier if it's supposed to be a class member.
10057       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10058         NewFD->setAccess(AS_public);
10059 
10060       // Qualified decls generally require a previous declaration.
10061       if (D.getCXXScopeSpec().isSet()) {
10062         // ...with the major exception of templated-scope or
10063         // dependent-scope friend declarations.
10064 
10065         // TODO: we currently also suppress this check in dependent
10066         // contexts because (1) the parameter depth will be off when
10067         // matching friend templates and (2) we might actually be
10068         // selecting a friend based on a dependent factor.  But there
10069         // are situations where these conditions don't apply and we
10070         // can actually do this check immediately.
10071         //
10072         // Unless the scope is dependent, it's always an error if qualified
10073         // redeclaration lookup found nothing at all. Diagnose that now;
10074         // nothing will diagnose that error later.
10075         if (isFriend &&
10076             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10077              (!Previous.empty() && CurContext->isDependentContext()))) {
10078           // ignore these
10079         } else if (NewFD->isCPUDispatchMultiVersion() ||
10080                    NewFD->isCPUSpecificMultiVersion()) {
10081           // ignore this, we allow the redeclaration behavior here to create new
10082           // versions of the function.
10083         } else {
10084           // The user tried to provide an out-of-line definition for a
10085           // function that is a member of a class or namespace, but there
10086           // was no such member function declared (C++ [class.mfct]p2,
10087           // C++ [namespace.memdef]p2). For example:
10088           //
10089           // class X {
10090           //   void f() const;
10091           // };
10092           //
10093           // void X::f() { } // ill-formed
10094           //
10095           // Complain about this problem, and attempt to suggest close
10096           // matches (e.g., those that differ only in cv-qualifiers and
10097           // whether the parameter types are references).
10098 
10099           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10100                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10101             AddToScope = ExtraArgs.AddToScope;
10102             return Result;
10103           }
10104         }
10105 
10106         // Unqualified local friend declarations are required to resolve
10107         // to something.
10108       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10109         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10110                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10111           AddToScope = ExtraArgs.AddToScope;
10112           return Result;
10113         }
10114       }
10115     } else if (!D.isFunctionDefinition() &&
10116                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10117                !isFriend && !isFunctionTemplateSpecialization &&
10118                !isMemberSpecialization) {
10119       // An out-of-line member function declaration must also be a
10120       // definition (C++ [class.mfct]p2).
10121       // Note that this is not the case for explicit specializations of
10122       // function templates or member functions of class templates, per
10123       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10124       // extension for compatibility with old SWIG code which likes to
10125       // generate them.
10126       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10127         << D.getCXXScopeSpec().getRange();
10128     }
10129   }
10130 
10131   // If this is the first declaration of a library builtin function, add
10132   // attributes as appropriate.
10133   if (!D.isRedeclaration()) {
10134     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10135       if (unsigned BuiltinID = II->getBuiltinID()) {
10136         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10137         if (!InStdNamespace &&
10138             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10139           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10140             // Validate the type matches unless this builtin is specified as
10141             // matching regardless of its declared type.
10142             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10143               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10144             } else {
10145               ASTContext::GetBuiltinTypeError Error;
10146               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10147               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10148 
10149               if (!Error && !BuiltinType.isNull() &&
10150                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10151                       NewFD->getType(), BuiltinType))
10152                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10153             }
10154           }
10155         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10156                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10157           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10158         }
10159       }
10160     }
10161   }
10162 
10163   ProcessPragmaWeak(S, NewFD);
10164   checkAttributesAfterMerging(*this, *NewFD);
10165 
10166   AddKnownFunctionAttributes(NewFD);
10167 
10168   if (NewFD->hasAttr<OverloadableAttr>() &&
10169       !NewFD->getType()->getAs<FunctionProtoType>()) {
10170     Diag(NewFD->getLocation(),
10171          diag::err_attribute_overloadable_no_prototype)
10172       << NewFD;
10173 
10174     // Turn this into a variadic function with no parameters.
10175     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10176     FunctionProtoType::ExtProtoInfo EPI(
10177         Context.getDefaultCallingConvention(true, false));
10178     EPI.Variadic = true;
10179     EPI.ExtInfo = FT->getExtInfo();
10180 
10181     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10182     NewFD->setType(R);
10183   }
10184 
10185   // If there's a #pragma GCC visibility in scope, and this isn't a class
10186   // member, set the visibility of this function.
10187   if (!DC->isRecord() && NewFD->isExternallyVisible())
10188     AddPushedVisibilityAttribute(NewFD);
10189 
10190   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10191   // marking the function.
10192   AddCFAuditedAttribute(NewFD);
10193 
10194   // If this is a function definition, check if we have to apply any
10195   // attributes (i.e. optnone and no_builtin) due to a pragma.
10196   if (D.isFunctionDefinition()) {
10197     AddRangeBasedOptnone(NewFD);
10198     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10199     AddSectionMSAllocText(NewFD);
10200     ModifyFnAttributesMSPragmaOptimize(NewFD);
10201   }
10202 
10203   // If this is the first declaration of an extern C variable, update
10204   // the map of such variables.
10205   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10206       isIncompleteDeclExternC(*this, NewFD))
10207     RegisterLocallyScopedExternCDecl(NewFD, S);
10208 
10209   // Set this FunctionDecl's range up to the right paren.
10210   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10211 
10212   if (D.isRedeclaration() && !Previous.empty()) {
10213     NamedDecl *Prev = Previous.getRepresentativeDecl();
10214     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10215                                    isMemberSpecialization ||
10216                                        isFunctionTemplateSpecialization,
10217                                    D.isFunctionDefinition());
10218   }
10219 
10220   if (getLangOpts().CUDA) {
10221     IdentifierInfo *II = NewFD->getIdentifier();
10222     if (II && II->isStr(getCudaConfigureFuncName()) &&
10223         !NewFD->isInvalidDecl() &&
10224         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10225       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10226         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10227             << getCudaConfigureFuncName();
10228       Context.setcudaConfigureCallDecl(NewFD);
10229     }
10230 
10231     // Variadic functions, other than a *declaration* of printf, are not allowed
10232     // in device-side CUDA code, unless someone passed
10233     // -fcuda-allow-variadic-functions.
10234     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10235         (NewFD->hasAttr<CUDADeviceAttr>() ||
10236          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10237         !(II && II->isStr("printf") && NewFD->isExternC() &&
10238           !D.isFunctionDefinition())) {
10239       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10240     }
10241   }
10242 
10243   MarkUnusedFileScopedDecl(NewFD);
10244 
10245 
10246 
10247   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10248     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10249     if (SC == SC_Static) {
10250       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10251       D.setInvalidType();
10252     }
10253 
10254     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10255     if (!NewFD->getReturnType()->isVoidType()) {
10256       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10257       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10258           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10259                                 : FixItHint());
10260       D.setInvalidType();
10261     }
10262 
10263     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10264     for (auto Param : NewFD->parameters())
10265       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10266 
10267     if (getLangOpts().OpenCLCPlusPlus) {
10268       if (DC->isRecord()) {
10269         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10270         D.setInvalidType();
10271       }
10272       if (FunctionTemplate) {
10273         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10274         D.setInvalidType();
10275       }
10276     }
10277   }
10278 
10279   if (getLangOpts().CPlusPlus) {
10280     if (FunctionTemplate) {
10281       if (NewFD->isInvalidDecl())
10282         FunctionTemplate->setInvalidDecl();
10283       return FunctionTemplate;
10284     }
10285 
10286     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10287       CompleteMemberSpecialization(NewFD, Previous);
10288   }
10289 
10290   for (const ParmVarDecl *Param : NewFD->parameters()) {
10291     QualType PT = Param->getType();
10292 
10293     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10294     // types.
10295     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10296       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10297         QualType ElemTy = PipeTy->getElementType();
10298           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10299             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10300             D.setInvalidType();
10301           }
10302       }
10303     }
10304   }
10305 
10306   // Here we have an function template explicit specialization at class scope.
10307   // The actual specialization will be postponed to template instatiation
10308   // time via the ClassScopeFunctionSpecializationDecl node.
10309   if (isDependentClassScopeExplicitSpecialization) {
10310     ClassScopeFunctionSpecializationDecl *NewSpec =
10311                          ClassScopeFunctionSpecializationDecl::Create(
10312                                 Context, CurContext, NewFD->getLocation(),
10313                                 cast<CXXMethodDecl>(NewFD),
10314                                 HasExplicitTemplateArgs, TemplateArgs);
10315     CurContext->addDecl(NewSpec);
10316     AddToScope = false;
10317   }
10318 
10319   // Diagnose availability attributes. Availability cannot be used on functions
10320   // that are run during load/unload.
10321   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10322     if (NewFD->hasAttr<ConstructorAttr>()) {
10323       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10324           << 1;
10325       NewFD->dropAttr<AvailabilityAttr>();
10326     }
10327     if (NewFD->hasAttr<DestructorAttr>()) {
10328       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10329           << 2;
10330       NewFD->dropAttr<AvailabilityAttr>();
10331     }
10332   }
10333 
10334   // Diagnose no_builtin attribute on function declaration that are not a
10335   // definition.
10336   // FIXME: We should really be doing this in
10337   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10338   // the FunctionDecl and at this point of the code
10339   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10340   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10341   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10342     switch (D.getFunctionDefinitionKind()) {
10343     case FunctionDefinitionKind::Defaulted:
10344     case FunctionDefinitionKind::Deleted:
10345       Diag(NBA->getLocation(),
10346            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10347           << NBA->getSpelling();
10348       break;
10349     case FunctionDefinitionKind::Declaration:
10350       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10351           << NBA->getSpelling();
10352       break;
10353     case FunctionDefinitionKind::Definition:
10354       break;
10355     }
10356 
10357   return NewFD;
10358 }
10359 
10360 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10361 /// when __declspec(code_seg) "is applied to a class, all member functions of
10362 /// the class and nested classes -- this includes compiler-generated special
10363 /// member functions -- are put in the specified segment."
10364 /// The actual behavior is a little more complicated. The Microsoft compiler
10365 /// won't check outer classes if there is an active value from #pragma code_seg.
10366 /// The CodeSeg is always applied from the direct parent but only from outer
10367 /// classes when the #pragma code_seg stack is empty. See:
10368 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10369 /// available since MS has removed the page.
10370 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10371   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10372   if (!Method)
10373     return nullptr;
10374   const CXXRecordDecl *Parent = Method->getParent();
10375   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10376     Attr *NewAttr = SAttr->clone(S.getASTContext());
10377     NewAttr->setImplicit(true);
10378     return NewAttr;
10379   }
10380 
10381   // The Microsoft compiler won't check outer classes for the CodeSeg
10382   // when the #pragma code_seg stack is active.
10383   if (S.CodeSegStack.CurrentValue)
10384    return nullptr;
10385 
10386   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10387     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10388       Attr *NewAttr = SAttr->clone(S.getASTContext());
10389       NewAttr->setImplicit(true);
10390       return NewAttr;
10391     }
10392   }
10393   return nullptr;
10394 }
10395 
10396 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10397 /// containing class. Otherwise it will return implicit SectionAttr if the
10398 /// function is a definition and there is an active value on CodeSegStack
10399 /// (from the current #pragma code-seg value).
10400 ///
10401 /// \param FD Function being declared.
10402 /// \param IsDefinition Whether it is a definition or just a declarartion.
10403 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10404 ///          nullptr if no attribute should be added.
10405 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10406                                                        bool IsDefinition) {
10407   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10408     return A;
10409   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10410       CodeSegStack.CurrentValue)
10411     return SectionAttr::CreateImplicit(
10412         getASTContext(), CodeSegStack.CurrentValue->getString(),
10413         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10414         SectionAttr::Declspec_allocate);
10415   return nullptr;
10416 }
10417 
10418 /// Determines if we can perform a correct type check for \p D as a
10419 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10420 /// best-effort check.
10421 ///
10422 /// \param NewD The new declaration.
10423 /// \param OldD The old declaration.
10424 /// \param NewT The portion of the type of the new declaration to check.
10425 /// \param OldT The portion of the type of the old declaration to check.
10426 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10427                                           QualType NewT, QualType OldT) {
10428   if (!NewD->getLexicalDeclContext()->isDependentContext())
10429     return true;
10430 
10431   // For dependently-typed local extern declarations and friends, we can't
10432   // perform a correct type check in general until instantiation:
10433   //
10434   //   int f();
10435   //   template<typename T> void g() { T f(); }
10436   //
10437   // (valid if g() is only instantiated with T = int).
10438   if (NewT->isDependentType() &&
10439       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10440     return false;
10441 
10442   // Similarly, if the previous declaration was a dependent local extern
10443   // declaration, we don't really know its type yet.
10444   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10445     return false;
10446 
10447   return true;
10448 }
10449 
10450 /// Checks if the new declaration declared in dependent context must be
10451 /// put in the same redeclaration chain as the specified declaration.
10452 ///
10453 /// \param D Declaration that is checked.
10454 /// \param PrevDecl Previous declaration found with proper lookup method for the
10455 ///                 same declaration name.
10456 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10457 ///          belongs to.
10458 ///
10459 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10460   if (!D->getLexicalDeclContext()->isDependentContext())
10461     return true;
10462 
10463   // Don't chain dependent friend function definitions until instantiation, to
10464   // permit cases like
10465   //
10466   //   void func();
10467   //   template<typename T> class C1 { friend void func() {} };
10468   //   template<typename T> class C2 { friend void func() {} };
10469   //
10470   // ... which is valid if only one of C1 and C2 is ever instantiated.
10471   //
10472   // FIXME: This need only apply to function definitions. For now, we proxy
10473   // this by checking for a file-scope function. We do not want this to apply
10474   // to friend declarations nominating member functions, because that gets in
10475   // the way of access checks.
10476   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10477     return false;
10478 
10479   auto *VD = dyn_cast<ValueDecl>(D);
10480   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10481   return !VD || !PrevVD ||
10482          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10483                                         PrevVD->getType());
10484 }
10485 
10486 /// Check the target attribute of the function for MultiVersion
10487 /// validity.
10488 ///
10489 /// Returns true if there was an error, false otherwise.
10490 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10491   const auto *TA = FD->getAttr<TargetAttr>();
10492   assert(TA && "MultiVersion Candidate requires a target attribute");
10493   ParsedTargetAttr ParseInfo = TA->parse();
10494   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10495   enum ErrType { Feature = 0, Architecture = 1 };
10496 
10497   if (!ParseInfo.Architecture.empty() &&
10498       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10499     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10500         << Architecture << ParseInfo.Architecture;
10501     return true;
10502   }
10503 
10504   for (const auto &Feat : ParseInfo.Features) {
10505     auto BareFeat = StringRef{Feat}.substr(1);
10506     if (Feat[0] == '-') {
10507       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10508           << Feature << ("no-" + BareFeat).str();
10509       return true;
10510     }
10511 
10512     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10513         !TargetInfo.isValidFeatureName(BareFeat)) {
10514       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10515           << Feature << BareFeat;
10516       return true;
10517     }
10518   }
10519   return false;
10520 }
10521 
10522 // Provide a white-list of attributes that are allowed to be combined with
10523 // multiversion functions.
10524 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10525                                            MultiVersionKind MVKind) {
10526   // Note: this list/diagnosis must match the list in
10527   // checkMultiversionAttributesAllSame.
10528   switch (Kind) {
10529   default:
10530     return false;
10531   case attr::Used:
10532     return MVKind == MultiVersionKind::Target;
10533   case attr::NonNull:
10534   case attr::NoThrow:
10535     return true;
10536   }
10537 }
10538 
10539 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10540                                                  const FunctionDecl *FD,
10541                                                  const FunctionDecl *CausedFD,
10542                                                  MultiVersionKind MVKind) {
10543   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10544     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10545         << static_cast<unsigned>(MVKind) << A;
10546     if (CausedFD)
10547       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10548     return true;
10549   };
10550 
10551   for (const Attr *A : FD->attrs()) {
10552     switch (A->getKind()) {
10553     case attr::CPUDispatch:
10554     case attr::CPUSpecific:
10555       if (MVKind != MultiVersionKind::CPUDispatch &&
10556           MVKind != MultiVersionKind::CPUSpecific)
10557         return Diagnose(S, A);
10558       break;
10559     case attr::Target:
10560       if (MVKind != MultiVersionKind::Target)
10561         return Diagnose(S, A);
10562       break;
10563     case attr::TargetClones:
10564       if (MVKind != MultiVersionKind::TargetClones)
10565         return Diagnose(S, A);
10566       break;
10567     default:
10568       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10569         return Diagnose(S, A);
10570       break;
10571     }
10572   }
10573   return false;
10574 }
10575 
10576 bool Sema::areMultiversionVariantFunctionsCompatible(
10577     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10578     const PartialDiagnostic &NoProtoDiagID,
10579     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10580     const PartialDiagnosticAt &NoSupportDiagIDAt,
10581     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10582     bool ConstexprSupported, bool CLinkageMayDiffer) {
10583   enum DoesntSupport {
10584     FuncTemplates = 0,
10585     VirtFuncs = 1,
10586     DeducedReturn = 2,
10587     Constructors = 3,
10588     Destructors = 4,
10589     DeletedFuncs = 5,
10590     DefaultedFuncs = 6,
10591     ConstexprFuncs = 7,
10592     ConstevalFuncs = 8,
10593     Lambda = 9,
10594   };
10595   enum Different {
10596     CallingConv = 0,
10597     ReturnType = 1,
10598     ConstexprSpec = 2,
10599     InlineSpec = 3,
10600     Linkage = 4,
10601     LanguageLinkage = 5,
10602   };
10603 
10604   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10605       !OldFD->getType()->getAs<FunctionProtoType>()) {
10606     Diag(OldFD->getLocation(), NoProtoDiagID);
10607     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10608     return true;
10609   }
10610 
10611   if (NoProtoDiagID.getDiagID() != 0 &&
10612       !NewFD->getType()->getAs<FunctionProtoType>())
10613     return Diag(NewFD->getLocation(), NoProtoDiagID);
10614 
10615   if (!TemplatesSupported &&
10616       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10617     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10618            << FuncTemplates;
10619 
10620   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10621     if (NewCXXFD->isVirtual())
10622       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10623              << VirtFuncs;
10624 
10625     if (isa<CXXConstructorDecl>(NewCXXFD))
10626       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10627              << Constructors;
10628 
10629     if (isa<CXXDestructorDecl>(NewCXXFD))
10630       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10631              << Destructors;
10632   }
10633 
10634   if (NewFD->isDeleted())
10635     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10636            << DeletedFuncs;
10637 
10638   if (NewFD->isDefaulted())
10639     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10640            << DefaultedFuncs;
10641 
10642   if (!ConstexprSupported && NewFD->isConstexpr())
10643     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10644            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10645 
10646   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10647   const auto *NewType = cast<FunctionType>(NewQType);
10648   QualType NewReturnType = NewType->getReturnType();
10649 
10650   if (NewReturnType->isUndeducedType())
10651     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10652            << DeducedReturn;
10653 
10654   // Ensure the return type is identical.
10655   if (OldFD) {
10656     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10657     const auto *OldType = cast<FunctionType>(OldQType);
10658     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10659     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10660 
10661     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10662       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10663 
10664     QualType OldReturnType = OldType->getReturnType();
10665 
10666     if (OldReturnType != NewReturnType)
10667       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10668 
10669     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10670       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10671 
10672     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10673       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10674 
10675     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10676       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10677 
10678     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10679       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10680 
10681     if (CheckEquivalentExceptionSpec(
10682             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10683             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10684       return true;
10685   }
10686   return false;
10687 }
10688 
10689 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10690                                              const FunctionDecl *NewFD,
10691                                              bool CausesMV,
10692                                              MultiVersionKind MVKind) {
10693   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10694     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10695     if (OldFD)
10696       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10697     return true;
10698   }
10699 
10700   bool IsCPUSpecificCPUDispatchMVKind =
10701       MVKind == MultiVersionKind::CPUDispatch ||
10702       MVKind == MultiVersionKind::CPUSpecific;
10703 
10704   if (CausesMV && OldFD &&
10705       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10706     return true;
10707 
10708   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10709     return true;
10710 
10711   // Only allow transition to MultiVersion if it hasn't been used.
10712   if (OldFD && CausesMV && OldFD->isUsed(false))
10713     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10714 
10715   return S.areMultiversionVariantFunctionsCompatible(
10716       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10717       PartialDiagnosticAt(NewFD->getLocation(),
10718                           S.PDiag(diag::note_multiversioning_caused_here)),
10719       PartialDiagnosticAt(NewFD->getLocation(),
10720                           S.PDiag(diag::err_multiversion_doesnt_support)
10721                               << static_cast<unsigned>(MVKind)),
10722       PartialDiagnosticAt(NewFD->getLocation(),
10723                           S.PDiag(diag::err_multiversion_diff)),
10724       /*TemplatesSupported=*/false,
10725       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10726       /*CLinkageMayDiffer=*/false);
10727 }
10728 
10729 /// Check the validity of a multiversion function declaration that is the
10730 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10731 ///
10732 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10733 ///
10734 /// Returns true if there was an error, false otherwise.
10735 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10736                                            MultiVersionKind MVKind,
10737                                            const TargetAttr *TA) {
10738   assert(MVKind != MultiVersionKind::None &&
10739          "Function lacks multiversion attribute");
10740 
10741   // Target only causes MV if it is default, otherwise this is a normal
10742   // function.
10743   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10744     return false;
10745 
10746   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10747     FD->setInvalidDecl();
10748     return true;
10749   }
10750 
10751   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10752     FD->setInvalidDecl();
10753     return true;
10754   }
10755 
10756   FD->setIsMultiVersion();
10757   return false;
10758 }
10759 
10760 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10761   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10762     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10763       return true;
10764   }
10765 
10766   return false;
10767 }
10768 
10769 static bool CheckTargetCausesMultiVersioning(
10770     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10771     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10772   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10773   ParsedTargetAttr NewParsed = NewTA->parse();
10774   // Sort order doesn't matter, it just needs to be consistent.
10775   llvm::sort(NewParsed.Features);
10776 
10777   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10778   // to change, this is a simple redeclaration.
10779   if (!NewTA->isDefaultVersion() &&
10780       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10781     return false;
10782 
10783   // Otherwise, this decl causes MultiVersioning.
10784   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10785                                        MultiVersionKind::Target)) {
10786     NewFD->setInvalidDecl();
10787     return true;
10788   }
10789 
10790   if (CheckMultiVersionValue(S, NewFD)) {
10791     NewFD->setInvalidDecl();
10792     return true;
10793   }
10794 
10795   // If this is 'default', permit the forward declaration.
10796   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10797     Redeclaration = true;
10798     OldDecl = OldFD;
10799     OldFD->setIsMultiVersion();
10800     NewFD->setIsMultiVersion();
10801     return false;
10802   }
10803 
10804   if (CheckMultiVersionValue(S, OldFD)) {
10805     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10806     NewFD->setInvalidDecl();
10807     return true;
10808   }
10809 
10810   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10811 
10812   if (OldParsed == NewParsed) {
10813     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10814     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10815     NewFD->setInvalidDecl();
10816     return true;
10817   }
10818 
10819   for (const auto *FD : OldFD->redecls()) {
10820     const auto *CurTA = FD->getAttr<TargetAttr>();
10821     // We allow forward declarations before ANY multiversioning attributes, but
10822     // nothing after the fact.
10823     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10824         (!CurTA || CurTA->isInherited())) {
10825       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10826           << 0;
10827       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10828       NewFD->setInvalidDecl();
10829       return true;
10830     }
10831   }
10832 
10833   OldFD->setIsMultiVersion();
10834   NewFD->setIsMultiVersion();
10835   Redeclaration = false;
10836   OldDecl = nullptr;
10837   Previous.clear();
10838   return false;
10839 }
10840 
10841 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10842                                         MultiVersionKind New) {
10843   if (Old == New || Old == MultiVersionKind::None ||
10844       New == MultiVersionKind::None)
10845     return true;
10846 
10847   return (Old == MultiVersionKind::CPUDispatch &&
10848           New == MultiVersionKind::CPUSpecific) ||
10849          (Old == MultiVersionKind::CPUSpecific &&
10850           New == MultiVersionKind::CPUDispatch);
10851 }
10852 
10853 /// Check the validity of a new function declaration being added to an existing
10854 /// multiversioned declaration collection.
10855 static bool CheckMultiVersionAdditionalDecl(
10856     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10857     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10858     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10859     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10860     LookupResult &Previous) {
10861 
10862   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10863   // Disallow mixing of multiversioning types.
10864   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10865     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10866     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10867     NewFD->setInvalidDecl();
10868     return true;
10869   }
10870 
10871   ParsedTargetAttr NewParsed;
10872   if (NewTA) {
10873     NewParsed = NewTA->parse();
10874     llvm::sort(NewParsed.Features);
10875   }
10876 
10877   bool UseMemberUsingDeclRules =
10878       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10879 
10880   bool MayNeedOverloadableChecks =
10881       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10882 
10883   // Next, check ALL non-overloads to see if this is a redeclaration of a
10884   // previous member of the MultiVersion set.
10885   for (NamedDecl *ND : Previous) {
10886     FunctionDecl *CurFD = ND->getAsFunction();
10887     if (!CurFD)
10888       continue;
10889     if (MayNeedOverloadableChecks &&
10890         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10891       continue;
10892 
10893     switch (NewMVKind) {
10894     case MultiVersionKind::None:
10895       assert(OldMVKind == MultiVersionKind::TargetClones &&
10896              "Only target_clones can be omitted in subsequent declarations");
10897       break;
10898     case MultiVersionKind::Target: {
10899       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10900       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10901         NewFD->setIsMultiVersion();
10902         Redeclaration = true;
10903         OldDecl = ND;
10904         return false;
10905       }
10906 
10907       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10908       if (CurParsed == NewParsed) {
10909         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10910         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10911         NewFD->setInvalidDecl();
10912         return true;
10913       }
10914       break;
10915     }
10916     case MultiVersionKind::TargetClones: {
10917       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10918       Redeclaration = true;
10919       OldDecl = CurFD;
10920       NewFD->setIsMultiVersion();
10921 
10922       if (CurClones && NewClones &&
10923           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10924            !std::equal(CurClones->featuresStrs_begin(),
10925                        CurClones->featuresStrs_end(),
10926                        NewClones->featuresStrs_begin()))) {
10927         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10928         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10929         NewFD->setInvalidDecl();
10930         return true;
10931       }
10932 
10933       return false;
10934     }
10935     case MultiVersionKind::CPUSpecific:
10936     case MultiVersionKind::CPUDispatch: {
10937       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10938       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10939       // Handle CPUDispatch/CPUSpecific versions.
10940       // Only 1 CPUDispatch function is allowed, this will make it go through
10941       // the redeclaration errors.
10942       if (NewMVKind == MultiVersionKind::CPUDispatch &&
10943           CurFD->hasAttr<CPUDispatchAttr>()) {
10944         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10945             std::equal(
10946                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10947                 NewCPUDisp->cpus_begin(),
10948                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10949                   return Cur->getName() == New->getName();
10950                 })) {
10951           NewFD->setIsMultiVersion();
10952           Redeclaration = true;
10953           OldDecl = ND;
10954           return false;
10955         }
10956 
10957         // If the declarations don't match, this is an error condition.
10958         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10959         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10960         NewFD->setInvalidDecl();
10961         return true;
10962       }
10963       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10964         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10965             std::equal(
10966                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10967                 NewCPUSpec->cpus_begin(),
10968                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10969                   return Cur->getName() == New->getName();
10970                 })) {
10971           NewFD->setIsMultiVersion();
10972           Redeclaration = true;
10973           OldDecl = ND;
10974           return false;
10975         }
10976 
10977         // Only 1 version of CPUSpecific is allowed for each CPU.
10978         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10979           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10980             if (CurII == NewII) {
10981               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10982                   << NewII;
10983               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10984               NewFD->setInvalidDecl();
10985               return true;
10986             }
10987           }
10988         }
10989       }
10990       break;
10991     }
10992     }
10993   }
10994 
10995   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10996   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10997   // handled in the attribute adding step.
10998   if (NewMVKind == MultiVersionKind::Target &&
10999       CheckMultiVersionValue(S, NewFD)) {
11000     NewFD->setInvalidDecl();
11001     return true;
11002   }
11003 
11004   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11005                                        !OldFD->isMultiVersion(), NewMVKind)) {
11006     NewFD->setInvalidDecl();
11007     return true;
11008   }
11009 
11010   // Permit forward declarations in the case where these two are compatible.
11011   if (!OldFD->isMultiVersion()) {
11012     OldFD->setIsMultiVersion();
11013     NewFD->setIsMultiVersion();
11014     Redeclaration = true;
11015     OldDecl = OldFD;
11016     return false;
11017   }
11018 
11019   NewFD->setIsMultiVersion();
11020   Redeclaration = false;
11021   OldDecl = nullptr;
11022   Previous.clear();
11023   return false;
11024 }
11025 
11026 /// Check the validity of a mulitversion function declaration.
11027 /// Also sets the multiversion'ness' of the function itself.
11028 ///
11029 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11030 ///
11031 /// Returns true if there was an error, false otherwise.
11032 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11033                                       bool &Redeclaration, NamedDecl *&OldDecl,
11034                                       LookupResult &Previous) {
11035   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11036   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11037   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11038   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11039   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11040 
11041   // Main isn't allowed to become a multiversion function, however it IS
11042   // permitted to have 'main' be marked with the 'target' optimization hint.
11043   if (NewFD->isMain()) {
11044     if (MVKind != MultiVersionKind::None &&
11045         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11046       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11047       NewFD->setInvalidDecl();
11048       return true;
11049     }
11050     return false;
11051   }
11052 
11053   if (!OldDecl || !OldDecl->getAsFunction() ||
11054       OldDecl->getDeclContext()->getRedeclContext() !=
11055           NewFD->getDeclContext()->getRedeclContext()) {
11056     // If there's no previous declaration, AND this isn't attempting to cause
11057     // multiversioning, this isn't an error condition.
11058     if (MVKind == MultiVersionKind::None)
11059       return false;
11060     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11061   }
11062 
11063   FunctionDecl *OldFD = OldDecl->getAsFunction();
11064 
11065   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11066     return false;
11067 
11068   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11069   // for target_clones.
11070   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11071       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11072     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11073         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11074     NewFD->setInvalidDecl();
11075     return true;
11076   }
11077 
11078   if (!OldFD->isMultiVersion()) {
11079     switch (MVKind) {
11080     case MultiVersionKind::Target:
11081       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11082                                               Redeclaration, OldDecl, Previous);
11083     case MultiVersionKind::TargetClones:
11084       if (OldFD->isUsed(false)) {
11085         NewFD->setInvalidDecl();
11086         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11087       }
11088       OldFD->setIsMultiVersion();
11089       break;
11090     case MultiVersionKind::CPUDispatch:
11091     case MultiVersionKind::CPUSpecific:
11092     case MultiVersionKind::None:
11093       break;
11094     }
11095   }
11096 
11097   // At this point, we have a multiversion function decl (in OldFD) AND an
11098   // appropriate attribute in the current function decl.  Resolve that these are
11099   // still compatible with previous declarations.
11100   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11101                                          NewCPUDisp, NewCPUSpec, NewClones,
11102                                          Redeclaration, OldDecl, Previous);
11103 }
11104 
11105 /// Perform semantic checking of a new function declaration.
11106 ///
11107 /// Performs semantic analysis of the new function declaration
11108 /// NewFD. This routine performs all semantic checking that does not
11109 /// require the actual declarator involved in the declaration, and is
11110 /// used both for the declaration of functions as they are parsed
11111 /// (called via ActOnDeclarator) and for the declaration of functions
11112 /// that have been instantiated via C++ template instantiation (called
11113 /// via InstantiateDecl).
11114 ///
11115 /// \param IsMemberSpecialization whether this new function declaration is
11116 /// a member specialization (that replaces any definition provided by the
11117 /// previous declaration).
11118 ///
11119 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11120 ///
11121 /// \returns true if the function declaration is a redeclaration.
11122 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11123                                     LookupResult &Previous,
11124                                     bool IsMemberSpecialization,
11125                                     bool DeclIsDefn) {
11126   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11127          "Variably modified return types are not handled here");
11128 
11129   // Determine whether the type of this function should be merged with
11130   // a previous visible declaration. This never happens for functions in C++,
11131   // and always happens in C if the previous declaration was visible.
11132   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11133                                !Previous.isShadowed();
11134 
11135   bool Redeclaration = false;
11136   NamedDecl *OldDecl = nullptr;
11137   bool MayNeedOverloadableChecks = false;
11138 
11139   // Merge or overload the declaration with an existing declaration of
11140   // the same name, if appropriate.
11141   if (!Previous.empty()) {
11142     // Determine whether NewFD is an overload of PrevDecl or
11143     // a declaration that requires merging. If it's an overload,
11144     // there's no more work to do here; we'll just add the new
11145     // function to the scope.
11146     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11147       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11148       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11149         Redeclaration = true;
11150         OldDecl = Candidate;
11151       }
11152     } else {
11153       MayNeedOverloadableChecks = true;
11154       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11155                             /*NewIsUsingDecl*/ false)) {
11156       case Ovl_Match:
11157         Redeclaration = true;
11158         break;
11159 
11160       case Ovl_NonFunction:
11161         Redeclaration = true;
11162         break;
11163 
11164       case Ovl_Overload:
11165         Redeclaration = false;
11166         break;
11167       }
11168     }
11169   }
11170 
11171   // Check for a previous extern "C" declaration with this name.
11172   if (!Redeclaration &&
11173       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11174     if (!Previous.empty()) {
11175       // This is an extern "C" declaration with the same name as a previous
11176       // declaration, and thus redeclares that entity...
11177       Redeclaration = true;
11178       OldDecl = Previous.getFoundDecl();
11179       MergeTypeWithPrevious = false;
11180 
11181       // ... except in the presence of __attribute__((overloadable)).
11182       if (OldDecl->hasAttr<OverloadableAttr>() ||
11183           NewFD->hasAttr<OverloadableAttr>()) {
11184         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11185           MayNeedOverloadableChecks = true;
11186           Redeclaration = false;
11187           OldDecl = nullptr;
11188         }
11189       }
11190     }
11191   }
11192 
11193   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11194     return Redeclaration;
11195 
11196   // PPC MMA non-pointer types are not allowed as function return types.
11197   if (Context.getTargetInfo().getTriple().isPPC64() &&
11198       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11199     NewFD->setInvalidDecl();
11200   }
11201 
11202   // C++11 [dcl.constexpr]p8:
11203   //   A constexpr specifier for a non-static member function that is not
11204   //   a constructor declares that member function to be const.
11205   //
11206   // This needs to be delayed until we know whether this is an out-of-line
11207   // definition of a static member function.
11208   //
11209   // This rule is not present in C++1y, so we produce a backwards
11210   // compatibility warning whenever it happens in C++11.
11211   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11212   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11213       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11214       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11215     CXXMethodDecl *OldMD = nullptr;
11216     if (OldDecl)
11217       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11218     if (!OldMD || !OldMD->isStatic()) {
11219       const FunctionProtoType *FPT =
11220         MD->getType()->castAs<FunctionProtoType>();
11221       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11222       EPI.TypeQuals.addConst();
11223       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11224                                           FPT->getParamTypes(), EPI));
11225 
11226       // Warn that we did this, if we're not performing template instantiation.
11227       // In that case, we'll have warned already when the template was defined.
11228       if (!inTemplateInstantiation()) {
11229         SourceLocation AddConstLoc;
11230         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11231                 .IgnoreParens().getAs<FunctionTypeLoc>())
11232           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11233 
11234         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11235           << FixItHint::CreateInsertion(AddConstLoc, " const");
11236       }
11237     }
11238   }
11239 
11240   if (Redeclaration) {
11241     // NewFD and OldDecl represent declarations that need to be
11242     // merged.
11243     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11244                           DeclIsDefn)) {
11245       NewFD->setInvalidDecl();
11246       return Redeclaration;
11247     }
11248 
11249     Previous.clear();
11250     Previous.addDecl(OldDecl);
11251 
11252     if (FunctionTemplateDecl *OldTemplateDecl =
11253             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11254       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11255       FunctionTemplateDecl *NewTemplateDecl
11256         = NewFD->getDescribedFunctionTemplate();
11257       assert(NewTemplateDecl && "Template/non-template mismatch");
11258 
11259       // The call to MergeFunctionDecl above may have created some state in
11260       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11261       // can add it as a redeclaration.
11262       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11263 
11264       NewFD->setPreviousDeclaration(OldFD);
11265       if (NewFD->isCXXClassMember()) {
11266         NewFD->setAccess(OldTemplateDecl->getAccess());
11267         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11268       }
11269 
11270       // If this is an explicit specialization of a member that is a function
11271       // template, mark it as a member specialization.
11272       if (IsMemberSpecialization &&
11273           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11274         NewTemplateDecl->setMemberSpecialization();
11275         assert(OldTemplateDecl->isMemberSpecialization());
11276         // Explicit specializations of a member template do not inherit deleted
11277         // status from the parent member template that they are specializing.
11278         if (OldFD->isDeleted()) {
11279           // FIXME: This assert will not hold in the presence of modules.
11280           assert(OldFD->getCanonicalDecl() == OldFD);
11281           // FIXME: We need an update record for this AST mutation.
11282           OldFD->setDeletedAsWritten(false);
11283         }
11284       }
11285 
11286     } else {
11287       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11288         auto *OldFD = cast<FunctionDecl>(OldDecl);
11289         // This needs to happen first so that 'inline' propagates.
11290         NewFD->setPreviousDeclaration(OldFD);
11291         if (NewFD->isCXXClassMember())
11292           NewFD->setAccess(OldFD->getAccess());
11293       }
11294     }
11295   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11296              !NewFD->getAttr<OverloadableAttr>()) {
11297     assert((Previous.empty() ||
11298             llvm::any_of(Previous,
11299                          [](const NamedDecl *ND) {
11300                            return ND->hasAttr<OverloadableAttr>();
11301                          })) &&
11302            "Non-redecls shouldn't happen without overloadable present");
11303 
11304     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11305       const auto *FD = dyn_cast<FunctionDecl>(ND);
11306       return FD && !FD->hasAttr<OverloadableAttr>();
11307     });
11308 
11309     if (OtherUnmarkedIter != Previous.end()) {
11310       Diag(NewFD->getLocation(),
11311            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11312       Diag((*OtherUnmarkedIter)->getLocation(),
11313            diag::note_attribute_overloadable_prev_overload)
11314           << false;
11315 
11316       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11317     }
11318   }
11319 
11320   if (LangOpts.OpenMP)
11321     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11322 
11323   // Semantic checking for this function declaration (in isolation).
11324 
11325   if (getLangOpts().CPlusPlus) {
11326     // C++-specific checks.
11327     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11328       CheckConstructor(Constructor);
11329     } else if (CXXDestructorDecl *Destructor =
11330                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11331       CXXRecordDecl *Record = Destructor->getParent();
11332       QualType ClassType = Context.getTypeDeclType(Record);
11333 
11334       // FIXME: Shouldn't we be able to perform this check even when the class
11335       // type is dependent? Both gcc and edg can handle that.
11336       if (!ClassType->isDependentType()) {
11337         DeclarationName Name
11338           = Context.DeclarationNames.getCXXDestructorName(
11339                                         Context.getCanonicalType(ClassType));
11340         if (NewFD->getDeclName() != Name) {
11341           Diag(NewFD->getLocation(), diag::err_destructor_name);
11342           NewFD->setInvalidDecl();
11343           return Redeclaration;
11344         }
11345       }
11346     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11347       if (auto *TD = Guide->getDescribedFunctionTemplate())
11348         CheckDeductionGuideTemplate(TD);
11349 
11350       // A deduction guide is not on the list of entities that can be
11351       // explicitly specialized.
11352       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11353         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11354             << /*explicit specialization*/ 1;
11355     }
11356 
11357     // Find any virtual functions that this function overrides.
11358     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11359       if (!Method->isFunctionTemplateSpecialization() &&
11360           !Method->getDescribedFunctionTemplate() &&
11361           Method->isCanonicalDecl()) {
11362         AddOverriddenMethods(Method->getParent(), Method);
11363       }
11364       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11365         // C++2a [class.virtual]p6
11366         // A virtual method shall not have a requires-clause.
11367         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11368              diag::err_constrained_virtual_method);
11369 
11370       if (Method->isStatic())
11371         checkThisInStaticMemberFunctionType(Method);
11372     }
11373 
11374     // C++20: dcl.decl.general p4:
11375     // The optional requires-clause ([temp.pre]) in an init-declarator or
11376     // member-declarator shall be present only if the declarator declares a
11377     // templated function ([dcl.fct]).
11378     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11379       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11380         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11381     }
11382 
11383     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11384       ActOnConversionDeclarator(Conversion);
11385 
11386     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11387     if (NewFD->isOverloadedOperator() &&
11388         CheckOverloadedOperatorDeclaration(NewFD)) {
11389       NewFD->setInvalidDecl();
11390       return Redeclaration;
11391     }
11392 
11393     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11394     if (NewFD->getLiteralIdentifier() &&
11395         CheckLiteralOperatorDeclaration(NewFD)) {
11396       NewFD->setInvalidDecl();
11397       return Redeclaration;
11398     }
11399 
11400     // In C++, check default arguments now that we have merged decls. Unless
11401     // the lexical context is the class, because in this case this is done
11402     // during delayed parsing anyway.
11403     if (!CurContext->isRecord())
11404       CheckCXXDefaultArguments(NewFD);
11405 
11406     // If this function is declared as being extern "C", then check to see if
11407     // the function returns a UDT (class, struct, or union type) that is not C
11408     // compatible, and if it does, warn the user.
11409     // But, issue any diagnostic on the first declaration only.
11410     if (Previous.empty() && NewFD->isExternC()) {
11411       QualType R = NewFD->getReturnType();
11412       if (R->isIncompleteType() && !R->isVoidType())
11413         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11414             << NewFD << R;
11415       else if (!R.isPODType(Context) && !R->isVoidType() &&
11416                !R->isObjCObjectPointerType())
11417         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11418     }
11419 
11420     // C++1z [dcl.fct]p6:
11421     //   [...] whether the function has a non-throwing exception-specification
11422     //   [is] part of the function type
11423     //
11424     // This results in an ABI break between C++14 and C++17 for functions whose
11425     // declared type includes an exception-specification in a parameter or
11426     // return type. (Exception specifications on the function itself are OK in
11427     // most cases, and exception specifications are not permitted in most other
11428     // contexts where they could make it into a mangling.)
11429     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11430       auto HasNoexcept = [&](QualType T) -> bool {
11431         // Strip off declarator chunks that could be between us and a function
11432         // type. We don't need to look far, exception specifications are very
11433         // restricted prior to C++17.
11434         if (auto *RT = T->getAs<ReferenceType>())
11435           T = RT->getPointeeType();
11436         else if (T->isAnyPointerType())
11437           T = T->getPointeeType();
11438         else if (auto *MPT = T->getAs<MemberPointerType>())
11439           T = MPT->getPointeeType();
11440         if (auto *FPT = T->getAs<FunctionProtoType>())
11441           if (FPT->isNothrow())
11442             return true;
11443         return false;
11444       };
11445 
11446       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11447       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11448       for (QualType T : FPT->param_types())
11449         AnyNoexcept |= HasNoexcept(T);
11450       if (AnyNoexcept)
11451         Diag(NewFD->getLocation(),
11452              diag::warn_cxx17_compat_exception_spec_in_signature)
11453             << NewFD;
11454     }
11455 
11456     if (!Redeclaration && LangOpts.CUDA)
11457       checkCUDATargetOverload(NewFD, Previous);
11458   }
11459   return Redeclaration;
11460 }
11461 
11462 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11463   // C++11 [basic.start.main]p3:
11464   //   A program that [...] declares main to be inline, static or
11465   //   constexpr is ill-formed.
11466   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11467   //   appear in a declaration of main.
11468   // static main is not an error under C99, but we should warn about it.
11469   // We accept _Noreturn main as an extension.
11470   if (FD->getStorageClass() == SC_Static)
11471     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11472          ? diag::err_static_main : diag::warn_static_main)
11473       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11474   if (FD->isInlineSpecified())
11475     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11476       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11477   if (DS.isNoreturnSpecified()) {
11478     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11479     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11480     Diag(NoreturnLoc, diag::ext_noreturn_main);
11481     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11482       << FixItHint::CreateRemoval(NoreturnRange);
11483   }
11484   if (FD->isConstexpr()) {
11485     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11486         << FD->isConsteval()
11487         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11488     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11489   }
11490 
11491   if (getLangOpts().OpenCL) {
11492     Diag(FD->getLocation(), diag::err_opencl_no_main)
11493         << FD->hasAttr<OpenCLKernelAttr>();
11494     FD->setInvalidDecl();
11495     return;
11496   }
11497 
11498   // Functions named main in hlsl are default entries, but don't have specific
11499   // signatures they are required to conform to.
11500   if (getLangOpts().HLSL)
11501     return;
11502 
11503   QualType T = FD->getType();
11504   assert(T->isFunctionType() && "function decl is not of function type");
11505   const FunctionType* FT = T->castAs<FunctionType>();
11506 
11507   // Set default calling convention for main()
11508   if (FT->getCallConv() != CC_C) {
11509     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11510     FD->setType(QualType(FT, 0));
11511     T = Context.getCanonicalType(FD->getType());
11512   }
11513 
11514   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11515     // In C with GNU extensions we allow main() to have non-integer return
11516     // type, but we should warn about the extension, and we disable the
11517     // implicit-return-zero rule.
11518 
11519     // GCC in C mode accepts qualified 'int'.
11520     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11521       FD->setHasImplicitReturnZero(true);
11522     else {
11523       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11524       SourceRange RTRange = FD->getReturnTypeSourceRange();
11525       if (RTRange.isValid())
11526         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11527             << FixItHint::CreateReplacement(RTRange, "int");
11528     }
11529   } else {
11530     // In C and C++, main magically returns 0 if you fall off the end;
11531     // set the flag which tells us that.
11532     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11533 
11534     // All the standards say that main() should return 'int'.
11535     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11536       FD->setHasImplicitReturnZero(true);
11537     else {
11538       // Otherwise, this is just a flat-out error.
11539       SourceRange RTRange = FD->getReturnTypeSourceRange();
11540       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11541           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11542                                 : FixItHint());
11543       FD->setInvalidDecl(true);
11544     }
11545   }
11546 
11547   // Treat protoless main() as nullary.
11548   if (isa<FunctionNoProtoType>(FT)) return;
11549 
11550   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11551   unsigned nparams = FTP->getNumParams();
11552   assert(FD->getNumParams() == nparams);
11553 
11554   bool HasExtraParameters = (nparams > 3);
11555 
11556   if (FTP->isVariadic()) {
11557     Diag(FD->getLocation(), diag::ext_variadic_main);
11558     // FIXME: if we had information about the location of the ellipsis, we
11559     // could add a FixIt hint to remove it as a parameter.
11560   }
11561 
11562   // Darwin passes an undocumented fourth argument of type char**.  If
11563   // other platforms start sprouting these, the logic below will start
11564   // getting shifty.
11565   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11566     HasExtraParameters = false;
11567 
11568   if (HasExtraParameters) {
11569     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11570     FD->setInvalidDecl(true);
11571     nparams = 3;
11572   }
11573 
11574   // FIXME: a lot of the following diagnostics would be improved
11575   // if we had some location information about types.
11576 
11577   QualType CharPP =
11578     Context.getPointerType(Context.getPointerType(Context.CharTy));
11579   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11580 
11581   for (unsigned i = 0; i < nparams; ++i) {
11582     QualType AT = FTP->getParamType(i);
11583 
11584     bool mismatch = true;
11585 
11586     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11587       mismatch = false;
11588     else if (Expected[i] == CharPP) {
11589       // As an extension, the following forms are okay:
11590       //   char const **
11591       //   char const * const *
11592       //   char * const *
11593 
11594       QualifierCollector qs;
11595       const PointerType* PT;
11596       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11597           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11598           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11599                               Context.CharTy)) {
11600         qs.removeConst();
11601         mismatch = !qs.empty();
11602       }
11603     }
11604 
11605     if (mismatch) {
11606       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11607       // TODO: suggest replacing given type with expected type
11608       FD->setInvalidDecl(true);
11609     }
11610   }
11611 
11612   if (nparams == 1 && !FD->isInvalidDecl()) {
11613     Diag(FD->getLocation(), diag::warn_main_one_arg);
11614   }
11615 
11616   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11617     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11618     FD->setInvalidDecl();
11619   }
11620 }
11621 
11622 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11623 
11624   // Default calling convention for main and wmain is __cdecl
11625   if (FD->getName() == "main" || FD->getName() == "wmain")
11626     return false;
11627 
11628   // Default calling convention for MinGW is __cdecl
11629   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11630   if (T.isWindowsGNUEnvironment())
11631     return false;
11632 
11633   // Default calling convention for WinMain, wWinMain and DllMain
11634   // is __stdcall on 32 bit Windows
11635   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11636     return true;
11637 
11638   return false;
11639 }
11640 
11641 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11642   QualType T = FD->getType();
11643   assert(T->isFunctionType() && "function decl is not of function type");
11644   const FunctionType *FT = T->castAs<FunctionType>();
11645 
11646   // Set an implicit return of 'zero' if the function can return some integral,
11647   // enumeration, pointer or nullptr type.
11648   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11649       FT->getReturnType()->isAnyPointerType() ||
11650       FT->getReturnType()->isNullPtrType())
11651     // DllMain is exempt because a return value of zero means it failed.
11652     if (FD->getName() != "DllMain")
11653       FD->setHasImplicitReturnZero(true);
11654 
11655   // Explicity specified calling conventions are applied to MSVC entry points
11656   if (!hasExplicitCallingConv(T)) {
11657     if (isDefaultStdCall(FD, *this)) {
11658       if (FT->getCallConv() != CC_X86StdCall) {
11659         FT = Context.adjustFunctionType(
11660             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11661         FD->setType(QualType(FT, 0));
11662       }
11663     } else if (FT->getCallConv() != CC_C) {
11664       FT = Context.adjustFunctionType(FT,
11665                                       FT->getExtInfo().withCallingConv(CC_C));
11666       FD->setType(QualType(FT, 0));
11667     }
11668   }
11669 
11670   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11671     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11672     FD->setInvalidDecl();
11673   }
11674 }
11675 
11676 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11677   // FIXME: Need strict checking.  In C89, we need to check for
11678   // any assignment, increment, decrement, function-calls, or
11679   // commas outside of a sizeof.  In C99, it's the same list,
11680   // except that the aforementioned are allowed in unevaluated
11681   // expressions.  Everything else falls under the
11682   // "may accept other forms of constant expressions" exception.
11683   //
11684   // Regular C++ code will not end up here (exceptions: language extensions,
11685   // OpenCL C++ etc), so the constant expression rules there don't matter.
11686   if (Init->isValueDependent()) {
11687     assert(Init->containsErrors() &&
11688            "Dependent code should only occur in error-recovery path.");
11689     return true;
11690   }
11691   const Expr *Culprit;
11692   if (Init->isConstantInitializer(Context, false, &Culprit))
11693     return false;
11694   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11695     << Culprit->getSourceRange();
11696   return true;
11697 }
11698 
11699 namespace {
11700   // Visits an initialization expression to see if OrigDecl is evaluated in
11701   // its own initialization and throws a warning if it does.
11702   class SelfReferenceChecker
11703       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11704     Sema &S;
11705     Decl *OrigDecl;
11706     bool isRecordType;
11707     bool isPODType;
11708     bool isReferenceType;
11709 
11710     bool isInitList;
11711     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11712 
11713   public:
11714     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11715 
11716     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11717                                                     S(S), OrigDecl(OrigDecl) {
11718       isPODType = false;
11719       isRecordType = false;
11720       isReferenceType = false;
11721       isInitList = false;
11722       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11723         isPODType = VD->getType().isPODType(S.Context);
11724         isRecordType = VD->getType()->isRecordType();
11725         isReferenceType = VD->getType()->isReferenceType();
11726       }
11727     }
11728 
11729     // For most expressions, just call the visitor.  For initializer lists,
11730     // track the index of the field being initialized since fields are
11731     // initialized in order allowing use of previously initialized fields.
11732     void CheckExpr(Expr *E) {
11733       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11734       if (!InitList) {
11735         Visit(E);
11736         return;
11737       }
11738 
11739       // Track and increment the index here.
11740       isInitList = true;
11741       InitFieldIndex.push_back(0);
11742       for (auto Child : InitList->children()) {
11743         CheckExpr(cast<Expr>(Child));
11744         ++InitFieldIndex.back();
11745       }
11746       InitFieldIndex.pop_back();
11747     }
11748 
11749     // Returns true if MemberExpr is checked and no further checking is needed.
11750     // Returns false if additional checking is required.
11751     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11752       llvm::SmallVector<FieldDecl*, 4> Fields;
11753       Expr *Base = E;
11754       bool ReferenceField = false;
11755 
11756       // Get the field members used.
11757       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11758         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11759         if (!FD)
11760           return false;
11761         Fields.push_back(FD);
11762         if (FD->getType()->isReferenceType())
11763           ReferenceField = true;
11764         Base = ME->getBase()->IgnoreParenImpCasts();
11765       }
11766 
11767       // Keep checking only if the base Decl is the same.
11768       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11769       if (!DRE || DRE->getDecl() != OrigDecl)
11770         return false;
11771 
11772       // A reference field can be bound to an unininitialized field.
11773       if (CheckReference && !ReferenceField)
11774         return true;
11775 
11776       // Convert FieldDecls to their index number.
11777       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11778       for (const FieldDecl *I : llvm::reverse(Fields))
11779         UsedFieldIndex.push_back(I->getFieldIndex());
11780 
11781       // See if a warning is needed by checking the first difference in index
11782       // numbers.  If field being used has index less than the field being
11783       // initialized, then the use is safe.
11784       for (auto UsedIter = UsedFieldIndex.begin(),
11785                 UsedEnd = UsedFieldIndex.end(),
11786                 OrigIter = InitFieldIndex.begin(),
11787                 OrigEnd = InitFieldIndex.end();
11788            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11789         if (*UsedIter < *OrigIter)
11790           return true;
11791         if (*UsedIter > *OrigIter)
11792           break;
11793       }
11794 
11795       // TODO: Add a different warning which will print the field names.
11796       HandleDeclRefExpr(DRE);
11797       return true;
11798     }
11799 
11800     // For most expressions, the cast is directly above the DeclRefExpr.
11801     // For conditional operators, the cast can be outside the conditional
11802     // operator if both expressions are DeclRefExpr's.
11803     void HandleValue(Expr *E) {
11804       E = E->IgnoreParens();
11805       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11806         HandleDeclRefExpr(DRE);
11807         return;
11808       }
11809 
11810       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11811         Visit(CO->getCond());
11812         HandleValue(CO->getTrueExpr());
11813         HandleValue(CO->getFalseExpr());
11814         return;
11815       }
11816 
11817       if (BinaryConditionalOperator *BCO =
11818               dyn_cast<BinaryConditionalOperator>(E)) {
11819         Visit(BCO->getCond());
11820         HandleValue(BCO->getFalseExpr());
11821         return;
11822       }
11823 
11824       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11825         HandleValue(OVE->getSourceExpr());
11826         return;
11827       }
11828 
11829       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11830         if (BO->getOpcode() == BO_Comma) {
11831           Visit(BO->getLHS());
11832           HandleValue(BO->getRHS());
11833           return;
11834         }
11835       }
11836 
11837       if (isa<MemberExpr>(E)) {
11838         if (isInitList) {
11839           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11840                                       false /*CheckReference*/))
11841             return;
11842         }
11843 
11844         Expr *Base = E->IgnoreParenImpCasts();
11845         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11846           // Check for static member variables and don't warn on them.
11847           if (!isa<FieldDecl>(ME->getMemberDecl()))
11848             return;
11849           Base = ME->getBase()->IgnoreParenImpCasts();
11850         }
11851         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11852           HandleDeclRefExpr(DRE);
11853         return;
11854       }
11855 
11856       Visit(E);
11857     }
11858 
11859     // Reference types not handled in HandleValue are handled here since all
11860     // uses of references are bad, not just r-value uses.
11861     void VisitDeclRefExpr(DeclRefExpr *E) {
11862       if (isReferenceType)
11863         HandleDeclRefExpr(E);
11864     }
11865 
11866     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11867       if (E->getCastKind() == CK_LValueToRValue) {
11868         HandleValue(E->getSubExpr());
11869         return;
11870       }
11871 
11872       Inherited::VisitImplicitCastExpr(E);
11873     }
11874 
11875     void VisitMemberExpr(MemberExpr *E) {
11876       if (isInitList) {
11877         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11878           return;
11879       }
11880 
11881       // Don't warn on arrays since they can be treated as pointers.
11882       if (E->getType()->canDecayToPointerType()) return;
11883 
11884       // Warn when a non-static method call is followed by non-static member
11885       // field accesses, which is followed by a DeclRefExpr.
11886       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11887       bool Warn = (MD && !MD->isStatic());
11888       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11889       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11890         if (!isa<FieldDecl>(ME->getMemberDecl()))
11891           Warn = false;
11892         Base = ME->getBase()->IgnoreParenImpCasts();
11893       }
11894 
11895       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11896         if (Warn)
11897           HandleDeclRefExpr(DRE);
11898         return;
11899       }
11900 
11901       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11902       // Visit that expression.
11903       Visit(Base);
11904     }
11905 
11906     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11907       Expr *Callee = E->getCallee();
11908 
11909       if (isa<UnresolvedLookupExpr>(Callee))
11910         return Inherited::VisitCXXOperatorCallExpr(E);
11911 
11912       Visit(Callee);
11913       for (auto Arg: E->arguments())
11914         HandleValue(Arg->IgnoreParenImpCasts());
11915     }
11916 
11917     void VisitUnaryOperator(UnaryOperator *E) {
11918       // For POD record types, addresses of its own members are well-defined.
11919       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11920           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11921         if (!isPODType)
11922           HandleValue(E->getSubExpr());
11923         return;
11924       }
11925 
11926       if (E->isIncrementDecrementOp()) {
11927         HandleValue(E->getSubExpr());
11928         return;
11929       }
11930 
11931       Inherited::VisitUnaryOperator(E);
11932     }
11933 
11934     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11935 
11936     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11937       if (E->getConstructor()->isCopyConstructor()) {
11938         Expr *ArgExpr = E->getArg(0);
11939         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11940           if (ILE->getNumInits() == 1)
11941             ArgExpr = ILE->getInit(0);
11942         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11943           if (ICE->getCastKind() == CK_NoOp)
11944             ArgExpr = ICE->getSubExpr();
11945         HandleValue(ArgExpr);
11946         return;
11947       }
11948       Inherited::VisitCXXConstructExpr(E);
11949     }
11950 
11951     void VisitCallExpr(CallExpr *E) {
11952       // Treat std::move as a use.
11953       if (E->isCallToStdMove()) {
11954         HandleValue(E->getArg(0));
11955         return;
11956       }
11957 
11958       Inherited::VisitCallExpr(E);
11959     }
11960 
11961     void VisitBinaryOperator(BinaryOperator *E) {
11962       if (E->isCompoundAssignmentOp()) {
11963         HandleValue(E->getLHS());
11964         Visit(E->getRHS());
11965         return;
11966       }
11967 
11968       Inherited::VisitBinaryOperator(E);
11969     }
11970 
11971     // A custom visitor for BinaryConditionalOperator is needed because the
11972     // regular visitor would check the condition and true expression separately
11973     // but both point to the same place giving duplicate diagnostics.
11974     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11975       Visit(E->getCond());
11976       Visit(E->getFalseExpr());
11977     }
11978 
11979     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11980       Decl* ReferenceDecl = DRE->getDecl();
11981       if (OrigDecl != ReferenceDecl) return;
11982       unsigned diag;
11983       if (isReferenceType) {
11984         diag = diag::warn_uninit_self_reference_in_reference_init;
11985       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11986         diag = diag::warn_static_self_reference_in_init;
11987       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11988                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11989                  DRE->getDecl()->getType()->isRecordType()) {
11990         diag = diag::warn_uninit_self_reference_in_init;
11991       } else {
11992         // Local variables will be handled by the CFG analysis.
11993         return;
11994       }
11995 
11996       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11997                             S.PDiag(diag)
11998                                 << DRE->getDecl() << OrigDecl->getLocation()
11999                                 << DRE->getSourceRange());
12000     }
12001   };
12002 
12003   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12004   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12005                                  bool DirectInit) {
12006     // Parameters arguments are occassionially constructed with itself,
12007     // for instance, in recursive functions.  Skip them.
12008     if (isa<ParmVarDecl>(OrigDecl))
12009       return;
12010 
12011     E = E->IgnoreParens();
12012 
12013     // Skip checking T a = a where T is not a record or reference type.
12014     // Doing so is a way to silence uninitialized warnings.
12015     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12016       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12017         if (ICE->getCastKind() == CK_LValueToRValue)
12018           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12019             if (DRE->getDecl() == OrigDecl)
12020               return;
12021 
12022     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12023   }
12024 } // end anonymous namespace
12025 
12026 namespace {
12027   // Simple wrapper to add the name of a variable or (if no variable is
12028   // available) a DeclarationName into a diagnostic.
12029   struct VarDeclOrName {
12030     VarDecl *VDecl;
12031     DeclarationName Name;
12032 
12033     friend const Sema::SemaDiagnosticBuilder &
12034     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12035       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12036     }
12037   };
12038 } // end anonymous namespace
12039 
12040 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12041                                             DeclarationName Name, QualType Type,
12042                                             TypeSourceInfo *TSI,
12043                                             SourceRange Range, bool DirectInit,
12044                                             Expr *Init) {
12045   bool IsInitCapture = !VDecl;
12046   assert((!VDecl || !VDecl->isInitCapture()) &&
12047          "init captures are expected to be deduced prior to initialization");
12048 
12049   VarDeclOrName VN{VDecl, Name};
12050 
12051   DeducedType *Deduced = Type->getContainedDeducedType();
12052   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12053 
12054   // C++11 [dcl.spec.auto]p3
12055   if (!Init) {
12056     assert(VDecl && "no init for init capture deduction?");
12057 
12058     // Except for class argument deduction, and then for an initializing
12059     // declaration only, i.e. no static at class scope or extern.
12060     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12061         VDecl->hasExternalStorage() ||
12062         VDecl->isStaticDataMember()) {
12063       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12064         << VDecl->getDeclName() << Type;
12065       return QualType();
12066     }
12067   }
12068 
12069   ArrayRef<Expr*> DeduceInits;
12070   if (Init)
12071     DeduceInits = Init;
12072 
12073   if (DirectInit) {
12074     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12075       DeduceInits = PL->exprs();
12076   }
12077 
12078   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12079     assert(VDecl && "non-auto type for init capture deduction?");
12080     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12081     InitializationKind Kind = InitializationKind::CreateForInit(
12082         VDecl->getLocation(), DirectInit, Init);
12083     // FIXME: Initialization should not be taking a mutable list of inits.
12084     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12085     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12086                                                        InitsCopy);
12087   }
12088 
12089   if (DirectInit) {
12090     if (auto *IL = dyn_cast<InitListExpr>(Init))
12091       DeduceInits = IL->inits();
12092   }
12093 
12094   // Deduction only works if we have exactly one source expression.
12095   if (DeduceInits.empty()) {
12096     // It isn't possible to write this directly, but it is possible to
12097     // end up in this situation with "auto x(some_pack...);"
12098     Diag(Init->getBeginLoc(), IsInitCapture
12099                                   ? diag::err_init_capture_no_expression
12100                                   : diag::err_auto_var_init_no_expression)
12101         << VN << Type << Range;
12102     return QualType();
12103   }
12104 
12105   if (DeduceInits.size() > 1) {
12106     Diag(DeduceInits[1]->getBeginLoc(),
12107          IsInitCapture ? diag::err_init_capture_multiple_expressions
12108                        : diag::err_auto_var_init_multiple_expressions)
12109         << VN << Type << Range;
12110     return QualType();
12111   }
12112 
12113   Expr *DeduceInit = DeduceInits[0];
12114   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12115     Diag(Init->getBeginLoc(), IsInitCapture
12116                                   ? diag::err_init_capture_paren_braces
12117                                   : diag::err_auto_var_init_paren_braces)
12118         << isa<InitListExpr>(Init) << VN << Type << Range;
12119     return QualType();
12120   }
12121 
12122   // Expressions default to 'id' when we're in a debugger.
12123   bool DefaultedAnyToId = false;
12124   if (getLangOpts().DebuggerCastResultToId &&
12125       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12126     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12127     if (Result.isInvalid()) {
12128       return QualType();
12129     }
12130     Init = Result.get();
12131     DefaultedAnyToId = true;
12132   }
12133 
12134   // C++ [dcl.decomp]p1:
12135   //   If the assignment-expression [...] has array type A and no ref-qualifier
12136   //   is present, e has type cv A
12137   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12138       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12139       DeduceInit->getType()->isConstantArrayType())
12140     return Context.getQualifiedType(DeduceInit->getType(),
12141                                     Type.getQualifiers());
12142 
12143   QualType DeducedType;
12144   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12145     if (!IsInitCapture)
12146       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12147     else if (isa<InitListExpr>(Init))
12148       Diag(Range.getBegin(),
12149            diag::err_init_capture_deduction_failure_from_init_list)
12150           << VN
12151           << (DeduceInit->getType().isNull() ? TSI->getType()
12152                                              : DeduceInit->getType())
12153           << DeduceInit->getSourceRange();
12154     else
12155       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12156           << VN << TSI->getType()
12157           << (DeduceInit->getType().isNull() ? TSI->getType()
12158                                              : DeduceInit->getType())
12159           << DeduceInit->getSourceRange();
12160   }
12161 
12162   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12163   // 'id' instead of a specific object type prevents most of our usual
12164   // checks.
12165   // We only want to warn outside of template instantiations, though:
12166   // inside a template, the 'id' could have come from a parameter.
12167   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12168       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12169     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12170     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12171   }
12172 
12173   return DeducedType;
12174 }
12175 
12176 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12177                                          Expr *Init) {
12178   assert(!Init || !Init->containsErrors());
12179   QualType DeducedType = deduceVarTypeFromInitializer(
12180       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12181       VDecl->getSourceRange(), DirectInit, Init);
12182   if (DeducedType.isNull()) {
12183     VDecl->setInvalidDecl();
12184     return true;
12185   }
12186 
12187   VDecl->setType(DeducedType);
12188   assert(VDecl->isLinkageValid());
12189 
12190   // In ARC, infer lifetime.
12191   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12192     VDecl->setInvalidDecl();
12193 
12194   if (getLangOpts().OpenCL)
12195     deduceOpenCLAddressSpace(VDecl);
12196 
12197   // If this is a redeclaration, check that the type we just deduced matches
12198   // the previously declared type.
12199   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12200     // We never need to merge the type, because we cannot form an incomplete
12201     // array of auto, nor deduce such a type.
12202     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12203   }
12204 
12205   // Check the deduced type is valid for a variable declaration.
12206   CheckVariableDeclarationType(VDecl);
12207   return VDecl->isInvalidDecl();
12208 }
12209 
12210 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12211                                               SourceLocation Loc) {
12212   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12213     Init = EWC->getSubExpr();
12214 
12215   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12216     Init = CE->getSubExpr();
12217 
12218   QualType InitType = Init->getType();
12219   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12220           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12221          "shouldn't be called if type doesn't have a non-trivial C struct");
12222   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12223     for (auto I : ILE->inits()) {
12224       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12225           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12226         continue;
12227       SourceLocation SL = I->getExprLoc();
12228       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12229     }
12230     return;
12231   }
12232 
12233   if (isa<ImplicitValueInitExpr>(Init)) {
12234     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12235       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12236                             NTCUK_Init);
12237   } else {
12238     // Assume all other explicit initializers involving copying some existing
12239     // object.
12240     // TODO: ignore any explicit initializers where we can guarantee
12241     // copy-elision.
12242     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12243       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12244   }
12245 }
12246 
12247 namespace {
12248 
12249 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12250   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12251   // in the source code or implicitly by the compiler if it is in a union
12252   // defined in a system header and has non-trivial ObjC ownership
12253   // qualifications. We don't want those fields to participate in determining
12254   // whether the containing union is non-trivial.
12255   return FD->hasAttr<UnavailableAttr>();
12256 }
12257 
12258 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12259     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12260                                     void> {
12261   using Super =
12262       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12263                                     void>;
12264 
12265   DiagNonTrivalCUnionDefaultInitializeVisitor(
12266       QualType OrigTy, SourceLocation OrigLoc,
12267       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12268       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12269 
12270   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12271                      const FieldDecl *FD, bool InNonTrivialUnion) {
12272     if (const auto *AT = S.Context.getAsArrayType(QT))
12273       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12274                                      InNonTrivialUnion);
12275     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12276   }
12277 
12278   void visitARCStrong(QualType QT, const FieldDecl *FD,
12279                       bool InNonTrivialUnion) {
12280     if (InNonTrivialUnion)
12281       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12282           << 1 << 0 << QT << FD->getName();
12283   }
12284 
12285   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12286     if (InNonTrivialUnion)
12287       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12288           << 1 << 0 << QT << FD->getName();
12289   }
12290 
12291   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12292     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12293     if (RD->isUnion()) {
12294       if (OrigLoc.isValid()) {
12295         bool IsUnion = false;
12296         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12297           IsUnion = OrigRD->isUnion();
12298         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12299             << 0 << OrigTy << IsUnion << UseContext;
12300         // Reset OrigLoc so that this diagnostic is emitted only once.
12301         OrigLoc = SourceLocation();
12302       }
12303       InNonTrivialUnion = true;
12304     }
12305 
12306     if (InNonTrivialUnion)
12307       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12308           << 0 << 0 << QT.getUnqualifiedType() << "";
12309 
12310     for (const FieldDecl *FD : RD->fields())
12311       if (!shouldIgnoreForRecordTriviality(FD))
12312         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12313   }
12314 
12315   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12316 
12317   // The non-trivial C union type or the struct/union type that contains a
12318   // non-trivial C union.
12319   QualType OrigTy;
12320   SourceLocation OrigLoc;
12321   Sema::NonTrivialCUnionContext UseContext;
12322   Sema &S;
12323 };
12324 
12325 struct DiagNonTrivalCUnionDestructedTypeVisitor
12326     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12327   using Super =
12328       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12329 
12330   DiagNonTrivalCUnionDestructedTypeVisitor(
12331       QualType OrigTy, SourceLocation OrigLoc,
12332       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12333       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12334 
12335   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12336                      const FieldDecl *FD, bool InNonTrivialUnion) {
12337     if (const auto *AT = S.Context.getAsArrayType(QT))
12338       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12339                                      InNonTrivialUnion);
12340     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12341   }
12342 
12343   void visitARCStrong(QualType QT, const FieldDecl *FD,
12344                       bool InNonTrivialUnion) {
12345     if (InNonTrivialUnion)
12346       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12347           << 1 << 1 << QT << FD->getName();
12348   }
12349 
12350   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12351     if (InNonTrivialUnion)
12352       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12353           << 1 << 1 << QT << FD->getName();
12354   }
12355 
12356   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12357     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12358     if (RD->isUnion()) {
12359       if (OrigLoc.isValid()) {
12360         bool IsUnion = false;
12361         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12362           IsUnion = OrigRD->isUnion();
12363         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12364             << 1 << OrigTy << IsUnion << UseContext;
12365         // Reset OrigLoc so that this diagnostic is emitted only once.
12366         OrigLoc = SourceLocation();
12367       }
12368       InNonTrivialUnion = true;
12369     }
12370 
12371     if (InNonTrivialUnion)
12372       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12373           << 0 << 1 << QT.getUnqualifiedType() << "";
12374 
12375     for (const FieldDecl *FD : RD->fields())
12376       if (!shouldIgnoreForRecordTriviality(FD))
12377         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12378   }
12379 
12380   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12381   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12382                           bool InNonTrivialUnion) {}
12383 
12384   // The non-trivial C union type or the struct/union type that contains a
12385   // non-trivial C union.
12386   QualType OrigTy;
12387   SourceLocation OrigLoc;
12388   Sema::NonTrivialCUnionContext UseContext;
12389   Sema &S;
12390 };
12391 
12392 struct DiagNonTrivalCUnionCopyVisitor
12393     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12394   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12395 
12396   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12397                                  Sema::NonTrivialCUnionContext UseContext,
12398                                  Sema &S)
12399       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12400 
12401   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12402                      const FieldDecl *FD, bool InNonTrivialUnion) {
12403     if (const auto *AT = S.Context.getAsArrayType(QT))
12404       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12405                                      InNonTrivialUnion);
12406     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12407   }
12408 
12409   void visitARCStrong(QualType QT, const FieldDecl *FD,
12410                       bool InNonTrivialUnion) {
12411     if (InNonTrivialUnion)
12412       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12413           << 1 << 2 << QT << FD->getName();
12414   }
12415 
12416   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12417     if (InNonTrivialUnion)
12418       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12419           << 1 << 2 << QT << FD->getName();
12420   }
12421 
12422   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12423     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12424     if (RD->isUnion()) {
12425       if (OrigLoc.isValid()) {
12426         bool IsUnion = false;
12427         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12428           IsUnion = OrigRD->isUnion();
12429         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12430             << 2 << OrigTy << IsUnion << UseContext;
12431         // Reset OrigLoc so that this diagnostic is emitted only once.
12432         OrigLoc = SourceLocation();
12433       }
12434       InNonTrivialUnion = true;
12435     }
12436 
12437     if (InNonTrivialUnion)
12438       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12439           << 0 << 2 << QT.getUnqualifiedType() << "";
12440 
12441     for (const FieldDecl *FD : RD->fields())
12442       if (!shouldIgnoreForRecordTriviality(FD))
12443         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12444   }
12445 
12446   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12447                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12448   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12449   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12450                             bool InNonTrivialUnion) {}
12451 
12452   // The non-trivial C union type or the struct/union type that contains a
12453   // non-trivial C union.
12454   QualType OrigTy;
12455   SourceLocation OrigLoc;
12456   Sema::NonTrivialCUnionContext UseContext;
12457   Sema &S;
12458 };
12459 
12460 } // namespace
12461 
12462 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12463                                  NonTrivialCUnionContext UseContext,
12464                                  unsigned NonTrivialKind) {
12465   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12466           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12467           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12468          "shouldn't be called if type doesn't have a non-trivial C union");
12469 
12470   if ((NonTrivialKind & NTCUK_Init) &&
12471       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12472     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12473         .visit(QT, nullptr, false);
12474   if ((NonTrivialKind & NTCUK_Destruct) &&
12475       QT.hasNonTrivialToPrimitiveDestructCUnion())
12476     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12477         .visit(QT, nullptr, false);
12478   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12479     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12480         .visit(QT, nullptr, false);
12481 }
12482 
12483 /// AddInitializerToDecl - Adds the initializer Init to the
12484 /// declaration dcl. If DirectInit is true, this is C++ direct
12485 /// initialization rather than copy initialization.
12486 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12487   // If there is no declaration, there was an error parsing it.  Just ignore
12488   // the initializer.
12489   if (!RealDecl || RealDecl->isInvalidDecl()) {
12490     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12491     return;
12492   }
12493 
12494   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12495     // Pure-specifiers are handled in ActOnPureSpecifier.
12496     Diag(Method->getLocation(), diag::err_member_function_initialization)
12497       << Method->getDeclName() << Init->getSourceRange();
12498     Method->setInvalidDecl();
12499     return;
12500   }
12501 
12502   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12503   if (!VDecl) {
12504     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12505     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12506     RealDecl->setInvalidDecl();
12507     return;
12508   }
12509 
12510   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12511   if (VDecl->getType()->isUndeducedType()) {
12512     // Attempt typo correction early so that the type of the init expression can
12513     // be deduced based on the chosen correction if the original init contains a
12514     // TypoExpr.
12515     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12516     if (!Res.isUsable()) {
12517       // There are unresolved typos in Init, just drop them.
12518       // FIXME: improve the recovery strategy to preserve the Init.
12519       RealDecl->setInvalidDecl();
12520       return;
12521     }
12522     if (Res.get()->containsErrors()) {
12523       // Invalidate the decl as we don't know the type for recovery-expr yet.
12524       RealDecl->setInvalidDecl();
12525       VDecl->setInit(Res.get());
12526       return;
12527     }
12528     Init = Res.get();
12529 
12530     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12531       return;
12532   }
12533 
12534   // dllimport cannot be used on variable definitions.
12535   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12536     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12537     VDecl->setInvalidDecl();
12538     return;
12539   }
12540 
12541   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12542     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12543     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12544     VDecl->setInvalidDecl();
12545     return;
12546   }
12547 
12548   if (!VDecl->getType()->isDependentType()) {
12549     // A definition must end up with a complete type, which means it must be
12550     // complete with the restriction that an array type might be completed by
12551     // the initializer; note that later code assumes this restriction.
12552     QualType BaseDeclType = VDecl->getType();
12553     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12554       BaseDeclType = Array->getElementType();
12555     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12556                             diag::err_typecheck_decl_incomplete_type)) {
12557       RealDecl->setInvalidDecl();
12558       return;
12559     }
12560 
12561     // The variable can not have an abstract class type.
12562     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12563                                diag::err_abstract_type_in_decl,
12564                                AbstractVariableType))
12565       VDecl->setInvalidDecl();
12566   }
12567 
12568   // If adding the initializer will turn this declaration into a definition,
12569   // and we already have a definition for this variable, diagnose or otherwise
12570   // handle the situation.
12571   if (VarDecl *Def = VDecl->getDefinition())
12572     if (Def != VDecl &&
12573         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12574         !VDecl->isThisDeclarationADemotedDefinition() &&
12575         checkVarDeclRedefinition(Def, VDecl))
12576       return;
12577 
12578   if (getLangOpts().CPlusPlus) {
12579     // C++ [class.static.data]p4
12580     //   If a static data member is of const integral or const
12581     //   enumeration type, its declaration in the class definition can
12582     //   specify a constant-initializer which shall be an integral
12583     //   constant expression (5.19). In that case, the member can appear
12584     //   in integral constant expressions. The member shall still be
12585     //   defined in a namespace scope if it is used in the program and the
12586     //   namespace scope definition shall not contain an initializer.
12587     //
12588     // We already performed a redefinition check above, but for static
12589     // data members we also need to check whether there was an in-class
12590     // declaration with an initializer.
12591     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12592       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12593           << VDecl->getDeclName();
12594       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12595            diag::note_previous_initializer)
12596           << 0;
12597       return;
12598     }
12599 
12600     if (VDecl->hasLocalStorage())
12601       setFunctionHasBranchProtectedScope();
12602 
12603     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12604       VDecl->setInvalidDecl();
12605       return;
12606     }
12607   }
12608 
12609   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12610   // a kernel function cannot be initialized."
12611   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12612     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12613     VDecl->setInvalidDecl();
12614     return;
12615   }
12616 
12617   // The LoaderUninitialized attribute acts as a definition (of undef).
12618   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12619     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12620     VDecl->setInvalidDecl();
12621     return;
12622   }
12623 
12624   // Get the decls type and save a reference for later, since
12625   // CheckInitializerTypes may change it.
12626   QualType DclT = VDecl->getType(), SavT = DclT;
12627 
12628   // Expressions default to 'id' when we're in a debugger
12629   // and we are assigning it to a variable of Objective-C pointer type.
12630   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12631       Init->getType() == Context.UnknownAnyTy) {
12632     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12633     if (Result.isInvalid()) {
12634       VDecl->setInvalidDecl();
12635       return;
12636     }
12637     Init = Result.get();
12638   }
12639 
12640   // Perform the initialization.
12641   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12642   if (!VDecl->isInvalidDecl()) {
12643     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12644     InitializationKind Kind = InitializationKind::CreateForInit(
12645         VDecl->getLocation(), DirectInit, Init);
12646 
12647     MultiExprArg Args = Init;
12648     if (CXXDirectInit)
12649       Args = MultiExprArg(CXXDirectInit->getExprs(),
12650                           CXXDirectInit->getNumExprs());
12651 
12652     // Try to correct any TypoExprs in the initialization arguments.
12653     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12654       ExprResult Res = CorrectDelayedTyposInExpr(
12655           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12656           [this, Entity, Kind](Expr *E) {
12657             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12658             return Init.Failed() ? ExprError() : E;
12659           });
12660       if (Res.isInvalid()) {
12661         VDecl->setInvalidDecl();
12662       } else if (Res.get() != Args[Idx]) {
12663         Args[Idx] = Res.get();
12664       }
12665     }
12666     if (VDecl->isInvalidDecl())
12667       return;
12668 
12669     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12670                                    /*TopLevelOfInitList=*/false,
12671                                    /*TreatUnavailableAsInvalid=*/false);
12672     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12673     if (Result.isInvalid()) {
12674       // If the provided initializer fails to initialize the var decl,
12675       // we attach a recovery expr for better recovery.
12676       auto RecoveryExpr =
12677           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12678       if (RecoveryExpr.get())
12679         VDecl->setInit(RecoveryExpr.get());
12680       return;
12681     }
12682 
12683     Init = Result.getAs<Expr>();
12684   }
12685 
12686   // Check for self-references within variable initializers.
12687   // Variables declared within a function/method body (except for references)
12688   // are handled by a dataflow analysis.
12689   // This is undefined behavior in C++, but valid in C.
12690   if (getLangOpts().CPlusPlus)
12691     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12692         VDecl->getType()->isReferenceType())
12693       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12694 
12695   // If the type changed, it means we had an incomplete type that was
12696   // completed by the initializer. For example:
12697   //   int ary[] = { 1, 3, 5 };
12698   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12699   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12700     VDecl->setType(DclT);
12701 
12702   if (!VDecl->isInvalidDecl()) {
12703     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12704 
12705     if (VDecl->hasAttr<BlocksAttr>())
12706       checkRetainCycles(VDecl, Init);
12707 
12708     // It is safe to assign a weak reference into a strong variable.
12709     // Although this code can still have problems:
12710     //   id x = self.weakProp;
12711     //   id y = self.weakProp;
12712     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12713     // paths through the function. This should be revisited if
12714     // -Wrepeated-use-of-weak is made flow-sensitive.
12715     if (FunctionScopeInfo *FSI = getCurFunction())
12716       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12717            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12718           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12719                            Init->getBeginLoc()))
12720         FSI->markSafeWeakUse(Init);
12721   }
12722 
12723   // The initialization is usually a full-expression.
12724   //
12725   // FIXME: If this is a braced initialization of an aggregate, it is not
12726   // an expression, and each individual field initializer is a separate
12727   // full-expression. For instance, in:
12728   //
12729   //   struct Temp { ~Temp(); };
12730   //   struct S { S(Temp); };
12731   //   struct T { S a, b; } t = { Temp(), Temp() }
12732   //
12733   // we should destroy the first Temp before constructing the second.
12734   ExprResult Result =
12735       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12736                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12737   if (Result.isInvalid()) {
12738     VDecl->setInvalidDecl();
12739     return;
12740   }
12741   Init = Result.get();
12742 
12743   // Attach the initializer to the decl.
12744   VDecl->setInit(Init);
12745 
12746   if (VDecl->isLocalVarDecl()) {
12747     // Don't check the initializer if the declaration is malformed.
12748     if (VDecl->isInvalidDecl()) {
12749       // do nothing
12750 
12751     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12752     // This is true even in C++ for OpenCL.
12753     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12754       CheckForConstantInitializer(Init, DclT);
12755 
12756     // Otherwise, C++ does not restrict the initializer.
12757     } else if (getLangOpts().CPlusPlus) {
12758       // do nothing
12759 
12760     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12761     // static storage duration shall be constant expressions or string literals.
12762     } else if (VDecl->getStorageClass() == SC_Static) {
12763       CheckForConstantInitializer(Init, DclT);
12764 
12765     // C89 is stricter than C99 for aggregate initializers.
12766     // C89 6.5.7p3: All the expressions [...] in an initializer list
12767     // for an object that has aggregate or union type shall be
12768     // constant expressions.
12769     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12770                isa<InitListExpr>(Init)) {
12771       const Expr *Culprit;
12772       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12773         Diag(Culprit->getExprLoc(),
12774              diag::ext_aggregate_init_not_constant)
12775           << Culprit->getSourceRange();
12776       }
12777     }
12778 
12779     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12780       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12781         if (VDecl->hasLocalStorage())
12782           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12783   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12784              VDecl->getLexicalDeclContext()->isRecord()) {
12785     // This is an in-class initialization for a static data member, e.g.,
12786     //
12787     // struct S {
12788     //   static const int value = 17;
12789     // };
12790 
12791     // C++ [class.mem]p4:
12792     //   A member-declarator can contain a constant-initializer only
12793     //   if it declares a static member (9.4) of const integral or
12794     //   const enumeration type, see 9.4.2.
12795     //
12796     // C++11 [class.static.data]p3:
12797     //   If a non-volatile non-inline const static data member is of integral
12798     //   or enumeration type, its declaration in the class definition can
12799     //   specify a brace-or-equal-initializer in which every initializer-clause
12800     //   that is an assignment-expression is a constant expression. A static
12801     //   data member of literal type can be declared in the class definition
12802     //   with the constexpr specifier; if so, its declaration shall specify a
12803     //   brace-or-equal-initializer in which every initializer-clause that is
12804     //   an assignment-expression is a constant expression.
12805 
12806     // Do nothing on dependent types.
12807     if (DclT->isDependentType()) {
12808 
12809     // Allow any 'static constexpr' members, whether or not they are of literal
12810     // type. We separately check that every constexpr variable is of literal
12811     // type.
12812     } else if (VDecl->isConstexpr()) {
12813 
12814     // Require constness.
12815     } else if (!DclT.isConstQualified()) {
12816       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12817         << Init->getSourceRange();
12818       VDecl->setInvalidDecl();
12819 
12820     // We allow integer constant expressions in all cases.
12821     } else if (DclT->isIntegralOrEnumerationType()) {
12822       // Check whether the expression is a constant expression.
12823       SourceLocation Loc;
12824       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12825         // In C++11, a non-constexpr const static data member with an
12826         // in-class initializer cannot be volatile.
12827         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12828       else if (Init->isValueDependent())
12829         ; // Nothing to check.
12830       else if (Init->isIntegerConstantExpr(Context, &Loc))
12831         ; // Ok, it's an ICE!
12832       else if (Init->getType()->isScopedEnumeralType() &&
12833                Init->isCXX11ConstantExpr(Context))
12834         ; // Ok, it is a scoped-enum constant expression.
12835       else if (Init->isEvaluatable(Context)) {
12836         // If we can constant fold the initializer through heroics, accept it,
12837         // but report this as a use of an extension for -pedantic.
12838         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12839           << Init->getSourceRange();
12840       } else {
12841         // Otherwise, this is some crazy unknown case.  Report the issue at the
12842         // location provided by the isIntegerConstantExpr failed check.
12843         Diag(Loc, diag::err_in_class_initializer_non_constant)
12844           << Init->getSourceRange();
12845         VDecl->setInvalidDecl();
12846       }
12847 
12848     // We allow foldable floating-point constants as an extension.
12849     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12850       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12851       // it anyway and provide a fixit to add the 'constexpr'.
12852       if (getLangOpts().CPlusPlus11) {
12853         Diag(VDecl->getLocation(),
12854              diag::ext_in_class_initializer_float_type_cxx11)
12855             << DclT << Init->getSourceRange();
12856         Diag(VDecl->getBeginLoc(),
12857              diag::note_in_class_initializer_float_type_cxx11)
12858             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12859       } else {
12860         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12861           << DclT << Init->getSourceRange();
12862 
12863         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12864           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12865             << Init->getSourceRange();
12866           VDecl->setInvalidDecl();
12867         }
12868       }
12869 
12870     // Suggest adding 'constexpr' in C++11 for literal types.
12871     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12872       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12873           << DclT << Init->getSourceRange()
12874           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12875       VDecl->setConstexpr(true);
12876 
12877     } else {
12878       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12879         << DclT << Init->getSourceRange();
12880       VDecl->setInvalidDecl();
12881     }
12882   } else if (VDecl->isFileVarDecl()) {
12883     // In C, extern is typically used to avoid tentative definitions when
12884     // declaring variables in headers, but adding an intializer makes it a
12885     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12886     // In C++, extern is often used to give implictly static const variables
12887     // external linkage, so don't warn in that case. If selectany is present,
12888     // this might be header code intended for C and C++ inclusion, so apply the
12889     // C++ rules.
12890     if (VDecl->getStorageClass() == SC_Extern &&
12891         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12892          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12893         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12894         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12895       Diag(VDecl->getLocation(), diag::warn_extern_init);
12896 
12897     // In Microsoft C++ mode, a const variable defined in namespace scope has
12898     // external linkage by default if the variable is declared with
12899     // __declspec(dllexport).
12900     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12901         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12902         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12903       VDecl->setStorageClass(SC_Extern);
12904 
12905     // C99 6.7.8p4. All file scoped initializers need to be constant.
12906     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12907       CheckForConstantInitializer(Init, DclT);
12908   }
12909 
12910   QualType InitType = Init->getType();
12911   if (!InitType.isNull() &&
12912       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12913        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12914     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12915 
12916   // We will represent direct-initialization similarly to copy-initialization:
12917   //    int x(1);  -as-> int x = 1;
12918   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12919   //
12920   // Clients that want to distinguish between the two forms, can check for
12921   // direct initializer using VarDecl::getInitStyle().
12922   // A major benefit is that clients that don't particularly care about which
12923   // exactly form was it (like the CodeGen) can handle both cases without
12924   // special case code.
12925 
12926   // C++ 8.5p11:
12927   // The form of initialization (using parentheses or '=') is generally
12928   // insignificant, but does matter when the entity being initialized has a
12929   // class type.
12930   if (CXXDirectInit) {
12931     assert(DirectInit && "Call-style initializer must be direct init.");
12932     VDecl->setInitStyle(VarDecl::CallInit);
12933   } else if (DirectInit) {
12934     // This must be list-initialization. No other way is direct-initialization.
12935     VDecl->setInitStyle(VarDecl::ListInit);
12936   }
12937 
12938   if (LangOpts.OpenMP &&
12939       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12940       VDecl->isFileVarDecl())
12941     DeclsToCheckForDeferredDiags.insert(VDecl);
12942   CheckCompleteVariableDeclaration(VDecl);
12943 }
12944 
12945 /// ActOnInitializerError - Given that there was an error parsing an
12946 /// initializer for the given declaration, try to at least re-establish
12947 /// invariants such as whether a variable's type is either dependent or
12948 /// complete.
12949 void Sema::ActOnInitializerError(Decl *D) {
12950   // Our main concern here is re-establishing invariants like "a
12951   // variable's type is either dependent or complete".
12952   if (!D || D->isInvalidDecl()) return;
12953 
12954   VarDecl *VD = dyn_cast<VarDecl>(D);
12955   if (!VD) return;
12956 
12957   // Bindings are not usable if we can't make sense of the initializer.
12958   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12959     for (auto *BD : DD->bindings())
12960       BD->setInvalidDecl();
12961 
12962   // Auto types are meaningless if we can't make sense of the initializer.
12963   if (VD->getType()->isUndeducedType()) {
12964     D->setInvalidDecl();
12965     return;
12966   }
12967 
12968   QualType Ty = VD->getType();
12969   if (Ty->isDependentType()) return;
12970 
12971   // Require a complete type.
12972   if (RequireCompleteType(VD->getLocation(),
12973                           Context.getBaseElementType(Ty),
12974                           diag::err_typecheck_decl_incomplete_type)) {
12975     VD->setInvalidDecl();
12976     return;
12977   }
12978 
12979   // Require a non-abstract type.
12980   if (RequireNonAbstractType(VD->getLocation(), Ty,
12981                              diag::err_abstract_type_in_decl,
12982                              AbstractVariableType)) {
12983     VD->setInvalidDecl();
12984     return;
12985   }
12986 
12987   // Don't bother complaining about constructors or destructors,
12988   // though.
12989 }
12990 
12991 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12992   // If there is no declaration, there was an error parsing it. Just ignore it.
12993   if (!RealDecl)
12994     return;
12995 
12996   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12997     QualType Type = Var->getType();
12998 
12999     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13000     if (isa<DecompositionDecl>(RealDecl)) {
13001       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13002       Var->setInvalidDecl();
13003       return;
13004     }
13005 
13006     if (Type->isUndeducedType() &&
13007         DeduceVariableDeclarationType(Var, false, nullptr))
13008       return;
13009 
13010     // C++11 [class.static.data]p3: A static data member can be declared with
13011     // the constexpr specifier; if so, its declaration shall specify
13012     // a brace-or-equal-initializer.
13013     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13014     // the definition of a variable [...] or the declaration of a static data
13015     // member.
13016     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13017         !Var->isThisDeclarationADemotedDefinition()) {
13018       if (Var->isStaticDataMember()) {
13019         // C++1z removes the relevant rule; the in-class declaration is always
13020         // a definition there.
13021         if (!getLangOpts().CPlusPlus17 &&
13022             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13023           Diag(Var->getLocation(),
13024                diag::err_constexpr_static_mem_var_requires_init)
13025               << Var;
13026           Var->setInvalidDecl();
13027           return;
13028         }
13029       } else {
13030         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13031         Var->setInvalidDecl();
13032         return;
13033       }
13034     }
13035 
13036     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13037     // be initialized.
13038     if (!Var->isInvalidDecl() &&
13039         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13040         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13041       bool HasConstExprDefaultConstructor = false;
13042       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13043         for (auto *Ctor : RD->ctors()) {
13044           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13045               Ctor->getMethodQualifiers().getAddressSpace() ==
13046                   LangAS::opencl_constant) {
13047             HasConstExprDefaultConstructor = true;
13048           }
13049         }
13050       }
13051       if (!HasConstExprDefaultConstructor) {
13052         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13053         Var->setInvalidDecl();
13054         return;
13055       }
13056     }
13057 
13058     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13059       if (Var->getStorageClass() == SC_Extern) {
13060         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13061             << Var;
13062         Var->setInvalidDecl();
13063         return;
13064       }
13065       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13066                               diag::err_typecheck_decl_incomplete_type)) {
13067         Var->setInvalidDecl();
13068         return;
13069       }
13070       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13071         if (!RD->hasTrivialDefaultConstructor()) {
13072           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13073           Var->setInvalidDecl();
13074           return;
13075         }
13076       }
13077       // The declaration is unitialized, no need for further checks.
13078       return;
13079     }
13080 
13081     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13082     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13083         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13084       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13085                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13086 
13087 
13088     switch (DefKind) {
13089     case VarDecl::Definition:
13090       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13091         break;
13092 
13093       // We have an out-of-line definition of a static data member
13094       // that has an in-class initializer, so we type-check this like
13095       // a declaration.
13096       //
13097       LLVM_FALLTHROUGH;
13098 
13099     case VarDecl::DeclarationOnly:
13100       // It's only a declaration.
13101 
13102       // Block scope. C99 6.7p7: If an identifier for an object is
13103       // declared with no linkage (C99 6.2.2p6), the type for the
13104       // object shall be complete.
13105       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13106           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13107           RequireCompleteType(Var->getLocation(), Type,
13108                               diag::err_typecheck_decl_incomplete_type))
13109         Var->setInvalidDecl();
13110 
13111       // Make sure that the type is not abstract.
13112       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13113           RequireNonAbstractType(Var->getLocation(), Type,
13114                                  diag::err_abstract_type_in_decl,
13115                                  AbstractVariableType))
13116         Var->setInvalidDecl();
13117       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13118           Var->getStorageClass() == SC_PrivateExtern) {
13119         Diag(Var->getLocation(), diag::warn_private_extern);
13120         Diag(Var->getLocation(), diag::note_private_extern);
13121       }
13122 
13123       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13124           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13125         ExternalDeclarations.push_back(Var);
13126 
13127       return;
13128 
13129     case VarDecl::TentativeDefinition:
13130       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13131       // object that has file scope without an initializer, and without a
13132       // storage-class specifier or with the storage-class specifier "static",
13133       // constitutes a tentative definition. Note: A tentative definition with
13134       // external linkage is valid (C99 6.2.2p5).
13135       if (!Var->isInvalidDecl()) {
13136         if (const IncompleteArrayType *ArrayT
13137                                     = Context.getAsIncompleteArrayType(Type)) {
13138           if (RequireCompleteSizedType(
13139                   Var->getLocation(), ArrayT->getElementType(),
13140                   diag::err_array_incomplete_or_sizeless_type))
13141             Var->setInvalidDecl();
13142         } else if (Var->getStorageClass() == SC_Static) {
13143           // C99 6.9.2p3: If the declaration of an identifier for an object is
13144           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13145           // declared type shall not be an incomplete type.
13146           // NOTE: code such as the following
13147           //     static struct s;
13148           //     struct s { int a; };
13149           // is accepted by gcc. Hence here we issue a warning instead of
13150           // an error and we do not invalidate the static declaration.
13151           // NOTE: to avoid multiple warnings, only check the first declaration.
13152           if (Var->isFirstDecl())
13153             RequireCompleteType(Var->getLocation(), Type,
13154                                 diag::ext_typecheck_decl_incomplete_type);
13155         }
13156       }
13157 
13158       // Record the tentative definition; we're done.
13159       if (!Var->isInvalidDecl())
13160         TentativeDefinitions.push_back(Var);
13161       return;
13162     }
13163 
13164     // Provide a specific diagnostic for uninitialized variable
13165     // definitions with incomplete array type.
13166     if (Type->isIncompleteArrayType()) {
13167       Diag(Var->getLocation(),
13168            diag::err_typecheck_incomplete_array_needs_initializer);
13169       Var->setInvalidDecl();
13170       return;
13171     }
13172 
13173     // Provide a specific diagnostic for uninitialized variable
13174     // definitions with reference type.
13175     if (Type->isReferenceType()) {
13176       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13177           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13178       return;
13179     }
13180 
13181     // Do not attempt to type-check the default initializer for a
13182     // variable with dependent type.
13183     if (Type->isDependentType())
13184       return;
13185 
13186     if (Var->isInvalidDecl())
13187       return;
13188 
13189     if (!Var->hasAttr<AliasAttr>()) {
13190       if (RequireCompleteType(Var->getLocation(),
13191                               Context.getBaseElementType(Type),
13192                               diag::err_typecheck_decl_incomplete_type)) {
13193         Var->setInvalidDecl();
13194         return;
13195       }
13196     } else {
13197       return;
13198     }
13199 
13200     // The variable can not have an abstract class type.
13201     if (RequireNonAbstractType(Var->getLocation(), Type,
13202                                diag::err_abstract_type_in_decl,
13203                                AbstractVariableType)) {
13204       Var->setInvalidDecl();
13205       return;
13206     }
13207 
13208     // Check for jumps past the implicit initializer.  C++0x
13209     // clarifies that this applies to a "variable with automatic
13210     // storage duration", not a "local variable".
13211     // C++11 [stmt.dcl]p3
13212     //   A program that jumps from a point where a variable with automatic
13213     //   storage duration is not in scope to a point where it is in scope is
13214     //   ill-formed unless the variable has scalar type, class type with a
13215     //   trivial default constructor and a trivial destructor, a cv-qualified
13216     //   version of one of these types, or an array of one of the preceding
13217     //   types and is declared without an initializer.
13218     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13219       if (const RecordType *Record
13220             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13221         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13222         // Mark the function (if we're in one) for further checking even if the
13223         // looser rules of C++11 do not require such checks, so that we can
13224         // diagnose incompatibilities with C++98.
13225         if (!CXXRecord->isPOD())
13226           setFunctionHasBranchProtectedScope();
13227       }
13228     }
13229     // In OpenCL, we can't initialize objects in the __local address space,
13230     // even implicitly, so don't synthesize an implicit initializer.
13231     if (getLangOpts().OpenCL &&
13232         Var->getType().getAddressSpace() == LangAS::opencl_local)
13233       return;
13234     // C++03 [dcl.init]p9:
13235     //   If no initializer is specified for an object, and the
13236     //   object is of (possibly cv-qualified) non-POD class type (or
13237     //   array thereof), the object shall be default-initialized; if
13238     //   the object is of const-qualified type, the underlying class
13239     //   type shall have a user-declared default
13240     //   constructor. Otherwise, if no initializer is specified for
13241     //   a non- static object, the object and its subobjects, if
13242     //   any, have an indeterminate initial value); if the object
13243     //   or any of its subobjects are of const-qualified type, the
13244     //   program is ill-formed.
13245     // C++0x [dcl.init]p11:
13246     //   If no initializer is specified for an object, the object is
13247     //   default-initialized; [...].
13248     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13249     InitializationKind Kind
13250       = InitializationKind::CreateDefault(Var->getLocation());
13251 
13252     InitializationSequence InitSeq(*this, Entity, Kind, None);
13253     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13254 
13255     if (Init.get()) {
13256       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13257       // This is important for template substitution.
13258       Var->setInitStyle(VarDecl::CallInit);
13259     } else if (Init.isInvalid()) {
13260       // If default-init fails, attach a recovery-expr initializer to track
13261       // that initialization was attempted and failed.
13262       auto RecoveryExpr =
13263           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13264       if (RecoveryExpr.get())
13265         Var->setInit(RecoveryExpr.get());
13266     }
13267 
13268     CheckCompleteVariableDeclaration(Var);
13269   }
13270 }
13271 
13272 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13273   // If there is no declaration, there was an error parsing it. Ignore it.
13274   if (!D)
13275     return;
13276 
13277   VarDecl *VD = dyn_cast<VarDecl>(D);
13278   if (!VD) {
13279     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13280     D->setInvalidDecl();
13281     return;
13282   }
13283 
13284   VD->setCXXForRangeDecl(true);
13285 
13286   // for-range-declaration cannot be given a storage class specifier.
13287   int Error = -1;
13288   switch (VD->getStorageClass()) {
13289   case SC_None:
13290     break;
13291   case SC_Extern:
13292     Error = 0;
13293     break;
13294   case SC_Static:
13295     Error = 1;
13296     break;
13297   case SC_PrivateExtern:
13298     Error = 2;
13299     break;
13300   case SC_Auto:
13301     Error = 3;
13302     break;
13303   case SC_Register:
13304     Error = 4;
13305     break;
13306   }
13307 
13308   // for-range-declaration cannot be given a storage class specifier con't.
13309   switch (VD->getTSCSpec()) {
13310   case TSCS_thread_local:
13311     Error = 6;
13312     break;
13313   case TSCS___thread:
13314   case TSCS__Thread_local:
13315   case TSCS_unspecified:
13316     break;
13317   }
13318 
13319   if (Error != -1) {
13320     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13321         << VD << Error;
13322     D->setInvalidDecl();
13323   }
13324 }
13325 
13326 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13327                                             IdentifierInfo *Ident,
13328                                             ParsedAttributes &Attrs) {
13329   // C++1y [stmt.iter]p1:
13330   //   A range-based for statement of the form
13331   //      for ( for-range-identifier : for-range-initializer ) statement
13332   //   is equivalent to
13333   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13334   DeclSpec DS(Attrs.getPool().getFactory());
13335 
13336   const char *PrevSpec;
13337   unsigned DiagID;
13338   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13339                      getPrintingPolicy());
13340 
13341   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13342   D.SetIdentifier(Ident, IdentLoc);
13343   D.takeAttributes(Attrs);
13344 
13345   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13346                 IdentLoc);
13347   Decl *Var = ActOnDeclarator(S, D);
13348   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13349   FinalizeDeclaration(Var);
13350   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13351                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13352                                                       : IdentLoc);
13353 }
13354 
13355 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13356   if (var->isInvalidDecl()) return;
13357 
13358   MaybeAddCUDAConstantAttr(var);
13359 
13360   if (getLangOpts().OpenCL) {
13361     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13362     // initialiser
13363     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13364         !var->hasInit()) {
13365       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13366           << 1 /*Init*/;
13367       var->setInvalidDecl();
13368       return;
13369     }
13370   }
13371 
13372   // In Objective-C, don't allow jumps past the implicit initialization of a
13373   // local retaining variable.
13374   if (getLangOpts().ObjC &&
13375       var->hasLocalStorage()) {
13376     switch (var->getType().getObjCLifetime()) {
13377     case Qualifiers::OCL_None:
13378     case Qualifiers::OCL_ExplicitNone:
13379     case Qualifiers::OCL_Autoreleasing:
13380       break;
13381 
13382     case Qualifiers::OCL_Weak:
13383     case Qualifiers::OCL_Strong:
13384       setFunctionHasBranchProtectedScope();
13385       break;
13386     }
13387   }
13388 
13389   if (var->hasLocalStorage() &&
13390       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13391     setFunctionHasBranchProtectedScope();
13392 
13393   // Warn about externally-visible variables being defined without a
13394   // prior declaration.  We only want to do this for global
13395   // declarations, but we also specifically need to avoid doing it for
13396   // class members because the linkage of an anonymous class can
13397   // change if it's later given a typedef name.
13398   if (var->isThisDeclarationADefinition() &&
13399       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13400       var->isExternallyVisible() && var->hasLinkage() &&
13401       !var->isInline() && !var->getDescribedVarTemplate() &&
13402       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13403       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13404       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13405                                   var->getLocation())) {
13406     // Find a previous declaration that's not a definition.
13407     VarDecl *prev = var->getPreviousDecl();
13408     while (prev && prev->isThisDeclarationADefinition())
13409       prev = prev->getPreviousDecl();
13410 
13411     if (!prev) {
13412       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13413       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13414           << /* variable */ 0;
13415     }
13416   }
13417 
13418   // Cache the result of checking for constant initialization.
13419   Optional<bool> CacheHasConstInit;
13420   const Expr *CacheCulprit = nullptr;
13421   auto checkConstInit = [&]() mutable {
13422     if (!CacheHasConstInit)
13423       CacheHasConstInit = var->getInit()->isConstantInitializer(
13424             Context, var->getType()->isReferenceType(), &CacheCulprit);
13425     return *CacheHasConstInit;
13426   };
13427 
13428   if (var->getTLSKind() == VarDecl::TLS_Static) {
13429     if (var->getType().isDestructedType()) {
13430       // GNU C++98 edits for __thread, [basic.start.term]p3:
13431       //   The type of an object with thread storage duration shall not
13432       //   have a non-trivial destructor.
13433       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13434       if (getLangOpts().CPlusPlus11)
13435         Diag(var->getLocation(), diag::note_use_thread_local);
13436     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13437       if (!checkConstInit()) {
13438         // GNU C++98 edits for __thread, [basic.start.init]p4:
13439         //   An object of thread storage duration shall not require dynamic
13440         //   initialization.
13441         // FIXME: Need strict checking here.
13442         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13443           << CacheCulprit->getSourceRange();
13444         if (getLangOpts().CPlusPlus11)
13445           Diag(var->getLocation(), diag::note_use_thread_local);
13446       }
13447     }
13448   }
13449 
13450 
13451   if (!var->getType()->isStructureType() && var->hasInit() &&
13452       isa<InitListExpr>(var->getInit())) {
13453     const auto *ILE = cast<InitListExpr>(var->getInit());
13454     unsigned NumInits = ILE->getNumInits();
13455     if (NumInits > 2)
13456       for (unsigned I = 0; I < NumInits; ++I) {
13457         const auto *Init = ILE->getInit(I);
13458         if (!Init)
13459           break;
13460         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13461         if (!SL)
13462           break;
13463 
13464         unsigned NumConcat = SL->getNumConcatenated();
13465         // Diagnose missing comma in string array initialization.
13466         // Do not warn when all the elements in the initializer are concatenated
13467         // together. Do not warn for macros too.
13468         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13469           bool OnlyOneMissingComma = true;
13470           for (unsigned J = I + 1; J < NumInits; ++J) {
13471             const auto *Init = ILE->getInit(J);
13472             if (!Init)
13473               break;
13474             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13475             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13476               OnlyOneMissingComma = false;
13477               break;
13478             }
13479           }
13480 
13481           if (OnlyOneMissingComma) {
13482             SmallVector<FixItHint, 1> Hints;
13483             for (unsigned i = 0; i < NumConcat - 1; ++i)
13484               Hints.push_back(FixItHint::CreateInsertion(
13485                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13486 
13487             Diag(SL->getStrTokenLoc(1),
13488                  diag::warn_concatenated_literal_array_init)
13489                 << Hints;
13490             Diag(SL->getBeginLoc(),
13491                  diag::note_concatenated_string_literal_silence);
13492           }
13493           // In any case, stop now.
13494           break;
13495         }
13496       }
13497   }
13498 
13499 
13500   QualType type = var->getType();
13501 
13502   if (var->hasAttr<BlocksAttr>())
13503     getCurFunction()->addByrefBlockVar(var);
13504 
13505   Expr *Init = var->getInit();
13506   bool GlobalStorage = var->hasGlobalStorage();
13507   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13508   QualType baseType = Context.getBaseElementType(type);
13509   bool HasConstInit = true;
13510 
13511   // Check whether the initializer is sufficiently constant.
13512   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13513       !Init->isValueDependent() &&
13514       (GlobalStorage || var->isConstexpr() ||
13515        var->mightBeUsableInConstantExpressions(Context))) {
13516     // If this variable might have a constant initializer or might be usable in
13517     // constant expressions, check whether or not it actually is now.  We can't
13518     // do this lazily, because the result might depend on things that change
13519     // later, such as which constexpr functions happen to be defined.
13520     SmallVector<PartialDiagnosticAt, 8> Notes;
13521     if (!getLangOpts().CPlusPlus11) {
13522       // Prior to C++11, in contexts where a constant initializer is required,
13523       // the set of valid constant initializers is described by syntactic rules
13524       // in [expr.const]p2-6.
13525       // FIXME: Stricter checking for these rules would be useful for constinit /
13526       // -Wglobal-constructors.
13527       HasConstInit = checkConstInit();
13528 
13529       // Compute and cache the constant value, and remember that we have a
13530       // constant initializer.
13531       if (HasConstInit) {
13532         (void)var->checkForConstantInitialization(Notes);
13533         Notes.clear();
13534       } else if (CacheCulprit) {
13535         Notes.emplace_back(CacheCulprit->getExprLoc(),
13536                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13537         Notes.back().second << CacheCulprit->getSourceRange();
13538       }
13539     } else {
13540       // Evaluate the initializer to see if it's a constant initializer.
13541       HasConstInit = var->checkForConstantInitialization(Notes);
13542     }
13543 
13544     if (HasConstInit) {
13545       // FIXME: Consider replacing the initializer with a ConstantExpr.
13546     } else if (var->isConstexpr()) {
13547       SourceLocation DiagLoc = var->getLocation();
13548       // If the note doesn't add any useful information other than a source
13549       // location, fold it into the primary diagnostic.
13550       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13551                                    diag::note_invalid_subexpr_in_const_expr) {
13552         DiagLoc = Notes[0].first;
13553         Notes.clear();
13554       }
13555       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13556           << var << Init->getSourceRange();
13557       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13558         Diag(Notes[I].first, Notes[I].second);
13559     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13560       auto *Attr = var->getAttr<ConstInitAttr>();
13561       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13562           << Init->getSourceRange();
13563       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13564           << Attr->getRange() << Attr->isConstinit();
13565       for (auto &it : Notes)
13566         Diag(it.first, it.second);
13567     } else if (IsGlobal &&
13568                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13569                                            var->getLocation())) {
13570       // Warn about globals which don't have a constant initializer.  Don't
13571       // warn about globals with a non-trivial destructor because we already
13572       // warned about them.
13573       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13574       if (!(RD && !RD->hasTrivialDestructor())) {
13575         // checkConstInit() here permits trivial default initialization even in
13576         // C++11 onwards, where such an initializer is not a constant initializer
13577         // but nonetheless doesn't require a global constructor.
13578         if (!checkConstInit())
13579           Diag(var->getLocation(), diag::warn_global_constructor)
13580               << Init->getSourceRange();
13581       }
13582     }
13583   }
13584 
13585   // Apply section attributes and pragmas to global variables.
13586   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13587       !inTemplateInstantiation()) {
13588     PragmaStack<StringLiteral *> *Stack = nullptr;
13589     int SectionFlags = ASTContext::PSF_Read;
13590     if (var->getType().isConstQualified()) {
13591       if (HasConstInit)
13592         Stack = &ConstSegStack;
13593       else {
13594         Stack = &BSSSegStack;
13595         SectionFlags |= ASTContext::PSF_Write;
13596       }
13597     } else if (var->hasInit() && HasConstInit) {
13598       Stack = &DataSegStack;
13599       SectionFlags |= ASTContext::PSF_Write;
13600     } else {
13601       Stack = &BSSSegStack;
13602       SectionFlags |= ASTContext::PSF_Write;
13603     }
13604     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13605       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13606         SectionFlags |= ASTContext::PSF_Implicit;
13607       UnifySection(SA->getName(), SectionFlags, var);
13608     } else if (Stack->CurrentValue) {
13609       SectionFlags |= ASTContext::PSF_Implicit;
13610       auto SectionName = Stack->CurrentValue->getString();
13611       var->addAttr(SectionAttr::CreateImplicit(
13612           Context, SectionName, Stack->CurrentPragmaLocation,
13613           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13614       if (UnifySection(SectionName, SectionFlags, var))
13615         var->dropAttr<SectionAttr>();
13616     }
13617 
13618     // Apply the init_seg attribute if this has an initializer.  If the
13619     // initializer turns out to not be dynamic, we'll end up ignoring this
13620     // attribute.
13621     if (CurInitSeg && var->getInit())
13622       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13623                                                CurInitSegLoc,
13624                                                AttributeCommonInfo::AS_Pragma));
13625   }
13626 
13627   // All the following checks are C++ only.
13628   if (!getLangOpts().CPlusPlus) {
13629     // If this variable must be emitted, add it as an initializer for the
13630     // current module.
13631     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13632       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13633     return;
13634   }
13635 
13636   // Require the destructor.
13637   if (!type->isDependentType())
13638     if (const RecordType *recordType = baseType->getAs<RecordType>())
13639       FinalizeVarWithDestructor(var, recordType);
13640 
13641   // If this variable must be emitted, add it as an initializer for the current
13642   // module.
13643   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13644     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13645 
13646   // Build the bindings if this is a structured binding declaration.
13647   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13648     CheckCompleteDecompositionDeclaration(DD);
13649 }
13650 
13651 /// Check if VD needs to be dllexport/dllimport due to being in a
13652 /// dllexport/import function.
13653 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13654   assert(VD->isStaticLocal());
13655 
13656   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13657 
13658   // Find outermost function when VD is in lambda function.
13659   while (FD && !getDLLAttr(FD) &&
13660          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13661          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13662     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13663   }
13664 
13665   if (!FD)
13666     return;
13667 
13668   // Static locals inherit dll attributes from their function.
13669   if (Attr *A = getDLLAttr(FD)) {
13670     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13671     NewAttr->setInherited(true);
13672     VD->addAttr(NewAttr);
13673   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13674     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13675     NewAttr->setInherited(true);
13676     VD->addAttr(NewAttr);
13677 
13678     // Export this function to enforce exporting this static variable even
13679     // if it is not used in this compilation unit.
13680     if (!FD->hasAttr<DLLExportAttr>())
13681       FD->addAttr(NewAttr);
13682 
13683   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13684     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13685     NewAttr->setInherited(true);
13686     VD->addAttr(NewAttr);
13687   }
13688 }
13689 
13690 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13691 /// any semantic actions necessary after any initializer has been attached.
13692 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13693   // Note that we are no longer parsing the initializer for this declaration.
13694   ParsingInitForAutoVars.erase(ThisDecl);
13695 
13696   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13697   if (!VD)
13698     return;
13699 
13700   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13701   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13702       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13703     if (PragmaClangBSSSection.Valid)
13704       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13705           Context, PragmaClangBSSSection.SectionName,
13706           PragmaClangBSSSection.PragmaLocation,
13707           AttributeCommonInfo::AS_Pragma));
13708     if (PragmaClangDataSection.Valid)
13709       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13710           Context, PragmaClangDataSection.SectionName,
13711           PragmaClangDataSection.PragmaLocation,
13712           AttributeCommonInfo::AS_Pragma));
13713     if (PragmaClangRodataSection.Valid)
13714       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13715           Context, PragmaClangRodataSection.SectionName,
13716           PragmaClangRodataSection.PragmaLocation,
13717           AttributeCommonInfo::AS_Pragma));
13718     if (PragmaClangRelroSection.Valid)
13719       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13720           Context, PragmaClangRelroSection.SectionName,
13721           PragmaClangRelroSection.PragmaLocation,
13722           AttributeCommonInfo::AS_Pragma));
13723   }
13724 
13725   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13726     for (auto *BD : DD->bindings()) {
13727       FinalizeDeclaration(BD);
13728     }
13729   }
13730 
13731   checkAttributesAfterMerging(*this, *VD);
13732 
13733   // Perform TLS alignment check here after attributes attached to the variable
13734   // which may affect the alignment have been processed. Only perform the check
13735   // if the target has a maximum TLS alignment (zero means no constraints).
13736   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13737     // Protect the check so that it's not performed on dependent types and
13738     // dependent alignments (we can't determine the alignment in that case).
13739     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13740       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13741       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13742         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13743           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13744           << (unsigned)MaxAlignChars.getQuantity();
13745       }
13746     }
13747   }
13748 
13749   if (VD->isStaticLocal())
13750     CheckStaticLocalForDllExport(VD);
13751 
13752   // Perform check for initializers of device-side global variables.
13753   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13754   // 7.5). We must also apply the same checks to all __shared__
13755   // variables whether they are local or not. CUDA also allows
13756   // constant initializers for __constant__ and __device__ variables.
13757   if (getLangOpts().CUDA)
13758     checkAllowedCUDAInitializer(VD);
13759 
13760   // Grab the dllimport or dllexport attribute off of the VarDecl.
13761   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13762 
13763   // Imported static data members cannot be defined out-of-line.
13764   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13765     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13766         VD->isThisDeclarationADefinition()) {
13767       // We allow definitions of dllimport class template static data members
13768       // with a warning.
13769       CXXRecordDecl *Context =
13770         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13771       bool IsClassTemplateMember =
13772           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13773           Context->getDescribedClassTemplate();
13774 
13775       Diag(VD->getLocation(),
13776            IsClassTemplateMember
13777                ? diag::warn_attribute_dllimport_static_field_definition
13778                : diag::err_attribute_dllimport_static_field_definition);
13779       Diag(IA->getLocation(), diag::note_attribute);
13780       if (!IsClassTemplateMember)
13781         VD->setInvalidDecl();
13782     }
13783   }
13784 
13785   // dllimport/dllexport variables cannot be thread local, their TLS index
13786   // isn't exported with the variable.
13787   if (DLLAttr && VD->getTLSKind()) {
13788     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13789     if (F && getDLLAttr(F)) {
13790       assert(VD->isStaticLocal());
13791       // But if this is a static local in a dlimport/dllexport function, the
13792       // function will never be inlined, which means the var would never be
13793       // imported, so having it marked import/export is safe.
13794     } else {
13795       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13796                                                                     << DLLAttr;
13797       VD->setInvalidDecl();
13798     }
13799   }
13800 
13801   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13802     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13803       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13804           << Attr;
13805       VD->dropAttr<UsedAttr>();
13806     }
13807   }
13808   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13809     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13810       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13811           << Attr;
13812       VD->dropAttr<RetainAttr>();
13813     }
13814   }
13815 
13816   const DeclContext *DC = VD->getDeclContext();
13817   // If there's a #pragma GCC visibility in scope, and this isn't a class
13818   // member, set the visibility of this variable.
13819   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13820     AddPushedVisibilityAttribute(VD);
13821 
13822   // FIXME: Warn on unused var template partial specializations.
13823   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13824     MarkUnusedFileScopedDecl(VD);
13825 
13826   // Now we have parsed the initializer and can update the table of magic
13827   // tag values.
13828   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13829       !VD->getType()->isIntegralOrEnumerationType())
13830     return;
13831 
13832   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13833     const Expr *MagicValueExpr = VD->getInit();
13834     if (!MagicValueExpr) {
13835       continue;
13836     }
13837     Optional<llvm::APSInt> MagicValueInt;
13838     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13839       Diag(I->getRange().getBegin(),
13840            diag::err_type_tag_for_datatype_not_ice)
13841         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13842       continue;
13843     }
13844     if (MagicValueInt->getActiveBits() > 64) {
13845       Diag(I->getRange().getBegin(),
13846            diag::err_type_tag_for_datatype_too_large)
13847         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13848       continue;
13849     }
13850     uint64_t MagicValue = MagicValueInt->getZExtValue();
13851     RegisterTypeTagForDatatype(I->getArgumentKind(),
13852                                MagicValue,
13853                                I->getMatchingCType(),
13854                                I->getLayoutCompatible(),
13855                                I->getMustBeNull());
13856   }
13857 }
13858 
13859 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13860   auto *VD = dyn_cast<VarDecl>(DD);
13861   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13862 }
13863 
13864 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13865                                                    ArrayRef<Decl *> Group) {
13866   SmallVector<Decl*, 8> Decls;
13867 
13868   if (DS.isTypeSpecOwned())
13869     Decls.push_back(DS.getRepAsDecl());
13870 
13871   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13872   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13873   bool DiagnosedMultipleDecomps = false;
13874   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13875   bool DiagnosedNonDeducedAuto = false;
13876 
13877   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13878     if (Decl *D = Group[i]) {
13879       // For declarators, there are some additional syntactic-ish checks we need
13880       // to perform.
13881       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13882         if (!FirstDeclaratorInGroup)
13883           FirstDeclaratorInGroup = DD;
13884         if (!FirstDecompDeclaratorInGroup)
13885           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13886         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13887             !hasDeducedAuto(DD))
13888           FirstNonDeducedAutoInGroup = DD;
13889 
13890         if (FirstDeclaratorInGroup != DD) {
13891           // A decomposition declaration cannot be combined with any other
13892           // declaration in the same group.
13893           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13894             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13895                  diag::err_decomp_decl_not_alone)
13896                 << FirstDeclaratorInGroup->getSourceRange()
13897                 << DD->getSourceRange();
13898             DiagnosedMultipleDecomps = true;
13899           }
13900 
13901           // A declarator that uses 'auto' in any way other than to declare a
13902           // variable with a deduced type cannot be combined with any other
13903           // declarator in the same group.
13904           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13905             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13906                  diag::err_auto_non_deduced_not_alone)
13907                 << FirstNonDeducedAutoInGroup->getType()
13908                        ->hasAutoForTrailingReturnType()
13909                 << FirstDeclaratorInGroup->getSourceRange()
13910                 << DD->getSourceRange();
13911             DiagnosedNonDeducedAuto = true;
13912           }
13913         }
13914       }
13915 
13916       Decls.push_back(D);
13917     }
13918   }
13919 
13920   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13921     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13922       handleTagNumbering(Tag, S);
13923       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13924           getLangOpts().CPlusPlus)
13925         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13926     }
13927   }
13928 
13929   return BuildDeclaratorGroup(Decls);
13930 }
13931 
13932 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13933 /// group, performing any necessary semantic checking.
13934 Sema::DeclGroupPtrTy
13935 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13936   // C++14 [dcl.spec.auto]p7: (DR1347)
13937   //   If the type that replaces the placeholder type is not the same in each
13938   //   deduction, the program is ill-formed.
13939   if (Group.size() > 1) {
13940     QualType Deduced;
13941     VarDecl *DeducedDecl = nullptr;
13942     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13943       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13944       if (!D || D->isInvalidDecl())
13945         break;
13946       DeducedType *DT = D->getType()->getContainedDeducedType();
13947       if (!DT || DT->getDeducedType().isNull())
13948         continue;
13949       if (Deduced.isNull()) {
13950         Deduced = DT->getDeducedType();
13951         DeducedDecl = D;
13952       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13953         auto *AT = dyn_cast<AutoType>(DT);
13954         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13955                         diag::err_auto_different_deductions)
13956                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13957                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13958                    << D->getDeclName();
13959         if (DeducedDecl->hasInit())
13960           Dia << DeducedDecl->getInit()->getSourceRange();
13961         if (D->getInit())
13962           Dia << D->getInit()->getSourceRange();
13963         D->setInvalidDecl();
13964         break;
13965       }
13966     }
13967   }
13968 
13969   ActOnDocumentableDecls(Group);
13970 
13971   return DeclGroupPtrTy::make(
13972       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13973 }
13974 
13975 void Sema::ActOnDocumentableDecl(Decl *D) {
13976   ActOnDocumentableDecls(D);
13977 }
13978 
13979 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13980   // Don't parse the comment if Doxygen diagnostics are ignored.
13981   if (Group.empty() || !Group[0])
13982     return;
13983 
13984   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13985                       Group[0]->getLocation()) &&
13986       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13987                       Group[0]->getLocation()))
13988     return;
13989 
13990   if (Group.size() >= 2) {
13991     // This is a decl group.  Normally it will contain only declarations
13992     // produced from declarator list.  But in case we have any definitions or
13993     // additional declaration references:
13994     //   'typedef struct S {} S;'
13995     //   'typedef struct S *S;'
13996     //   'struct S *pS;'
13997     // FinalizeDeclaratorGroup adds these as separate declarations.
13998     Decl *MaybeTagDecl = Group[0];
13999     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14000       Group = Group.slice(1);
14001     }
14002   }
14003 
14004   // FIMXE: We assume every Decl in the group is in the same file.
14005   // This is false when preprocessor constructs the group from decls in
14006   // different files (e. g. macros or #include).
14007   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14008 }
14009 
14010 /// Common checks for a parameter-declaration that should apply to both function
14011 /// parameters and non-type template parameters.
14012 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14013   // Check that there are no default arguments inside the type of this
14014   // parameter.
14015   if (getLangOpts().CPlusPlus)
14016     CheckExtraCXXDefaultArguments(D);
14017 
14018   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14019   if (D.getCXXScopeSpec().isSet()) {
14020     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14021       << D.getCXXScopeSpec().getRange();
14022   }
14023 
14024   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14025   // simple identifier except [...irrelevant cases...].
14026   switch (D.getName().getKind()) {
14027   case UnqualifiedIdKind::IK_Identifier:
14028     break;
14029 
14030   case UnqualifiedIdKind::IK_OperatorFunctionId:
14031   case UnqualifiedIdKind::IK_ConversionFunctionId:
14032   case UnqualifiedIdKind::IK_LiteralOperatorId:
14033   case UnqualifiedIdKind::IK_ConstructorName:
14034   case UnqualifiedIdKind::IK_DestructorName:
14035   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14036   case UnqualifiedIdKind::IK_DeductionGuideName:
14037     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14038       << GetNameForDeclarator(D).getName();
14039     break;
14040 
14041   case UnqualifiedIdKind::IK_TemplateId:
14042   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14043     // GetNameForDeclarator would not produce a useful name in this case.
14044     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14045     break;
14046   }
14047 }
14048 
14049 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14050 /// to introduce parameters into function prototype scope.
14051 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14052   const DeclSpec &DS = D.getDeclSpec();
14053 
14054   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14055 
14056   // C++03 [dcl.stc]p2 also permits 'auto'.
14057   StorageClass SC = SC_None;
14058   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14059     SC = SC_Register;
14060     // In C++11, the 'register' storage class specifier is deprecated.
14061     // In C++17, it is not allowed, but we tolerate it as an extension.
14062     if (getLangOpts().CPlusPlus11) {
14063       Diag(DS.getStorageClassSpecLoc(),
14064            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14065                                      : diag::warn_deprecated_register)
14066         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14067     }
14068   } else if (getLangOpts().CPlusPlus &&
14069              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14070     SC = SC_Auto;
14071   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14072     Diag(DS.getStorageClassSpecLoc(),
14073          diag::err_invalid_storage_class_in_func_decl);
14074     D.getMutableDeclSpec().ClearStorageClassSpecs();
14075   }
14076 
14077   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14078     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14079       << DeclSpec::getSpecifierName(TSCS);
14080   if (DS.isInlineSpecified())
14081     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14082         << getLangOpts().CPlusPlus17;
14083   if (DS.hasConstexprSpecifier())
14084     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14085         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14086 
14087   DiagnoseFunctionSpecifiers(DS);
14088 
14089   CheckFunctionOrTemplateParamDeclarator(S, D);
14090 
14091   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14092   QualType parmDeclType = TInfo->getType();
14093 
14094   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14095   IdentifierInfo *II = D.getIdentifier();
14096   if (II) {
14097     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14098                    ForVisibleRedeclaration);
14099     LookupName(R, S);
14100     if (R.isSingleResult()) {
14101       NamedDecl *PrevDecl = R.getFoundDecl();
14102       if (PrevDecl->isTemplateParameter()) {
14103         // Maybe we will complain about the shadowed template parameter.
14104         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14105         // Just pretend that we didn't see the previous declaration.
14106         PrevDecl = nullptr;
14107       } else if (S->isDeclScope(PrevDecl)) {
14108         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14109         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14110 
14111         // Recover by removing the name
14112         II = nullptr;
14113         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14114         D.setInvalidType(true);
14115       }
14116     }
14117   }
14118 
14119   // Temporarily put parameter variables in the translation unit, not
14120   // the enclosing context.  This prevents them from accidentally
14121   // looking like class members in C++.
14122   ParmVarDecl *New =
14123       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14124                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14125 
14126   if (D.isInvalidType())
14127     New->setInvalidDecl();
14128 
14129   assert(S->isFunctionPrototypeScope());
14130   assert(S->getFunctionPrototypeDepth() >= 1);
14131   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14132                     S->getNextFunctionPrototypeIndex());
14133 
14134   // Add the parameter declaration into this scope.
14135   S->AddDecl(New);
14136   if (II)
14137     IdResolver.AddDecl(New);
14138 
14139   ProcessDeclAttributes(S, New, D);
14140 
14141   if (D.getDeclSpec().isModulePrivateSpecified())
14142     Diag(New->getLocation(), diag::err_module_private_local)
14143         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14144         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14145 
14146   if (New->hasAttr<BlocksAttr>()) {
14147     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14148   }
14149 
14150   if (getLangOpts().OpenCL)
14151     deduceOpenCLAddressSpace(New);
14152 
14153   return New;
14154 }
14155 
14156 /// Synthesizes a variable for a parameter arising from a
14157 /// typedef.
14158 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14159                                               SourceLocation Loc,
14160                                               QualType T) {
14161   /* FIXME: setting StartLoc == Loc.
14162      Would it be worth to modify callers so as to provide proper source
14163      location for the unnamed parameters, embedding the parameter's type? */
14164   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14165                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14166                                            SC_None, nullptr);
14167   Param->setImplicit();
14168   return Param;
14169 }
14170 
14171 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14172   // Don't diagnose unused-parameter errors in template instantiations; we
14173   // will already have done so in the template itself.
14174   if (inTemplateInstantiation())
14175     return;
14176 
14177   for (const ParmVarDecl *Parameter : Parameters) {
14178     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14179         !Parameter->hasAttr<UnusedAttr>()) {
14180       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14181         << Parameter->getDeclName();
14182     }
14183   }
14184 }
14185 
14186 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14187     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14188   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14189     return;
14190 
14191   // Warn if the return value is pass-by-value and larger than the specified
14192   // threshold.
14193   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14194     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14195     if (Size > LangOpts.NumLargeByValueCopy)
14196       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14197   }
14198 
14199   // Warn if any parameter is pass-by-value and larger than the specified
14200   // threshold.
14201   for (const ParmVarDecl *Parameter : Parameters) {
14202     QualType T = Parameter->getType();
14203     if (T->isDependentType() || !T.isPODType(Context))
14204       continue;
14205     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14206     if (Size > LangOpts.NumLargeByValueCopy)
14207       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14208           << Parameter << Size;
14209   }
14210 }
14211 
14212 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14213                                   SourceLocation NameLoc, IdentifierInfo *Name,
14214                                   QualType T, TypeSourceInfo *TSInfo,
14215                                   StorageClass SC) {
14216   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14217   if (getLangOpts().ObjCAutoRefCount &&
14218       T.getObjCLifetime() == Qualifiers::OCL_None &&
14219       T->isObjCLifetimeType()) {
14220 
14221     Qualifiers::ObjCLifetime lifetime;
14222 
14223     // Special cases for arrays:
14224     //   - if it's const, use __unsafe_unretained
14225     //   - otherwise, it's an error
14226     if (T->isArrayType()) {
14227       if (!T.isConstQualified()) {
14228         if (DelayedDiagnostics.shouldDelayDiagnostics())
14229           DelayedDiagnostics.add(
14230               sema::DelayedDiagnostic::makeForbiddenType(
14231               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14232         else
14233           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14234               << TSInfo->getTypeLoc().getSourceRange();
14235       }
14236       lifetime = Qualifiers::OCL_ExplicitNone;
14237     } else {
14238       lifetime = T->getObjCARCImplicitLifetime();
14239     }
14240     T = Context.getLifetimeQualifiedType(T, lifetime);
14241   }
14242 
14243   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14244                                          Context.getAdjustedParameterType(T),
14245                                          TSInfo, SC, nullptr);
14246 
14247   // Make a note if we created a new pack in the scope of a lambda, so that
14248   // we know that references to that pack must also be expanded within the
14249   // lambda scope.
14250   if (New->isParameterPack())
14251     if (auto *LSI = getEnclosingLambda())
14252       LSI->LocalPacks.push_back(New);
14253 
14254   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14255       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14256     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14257                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14258 
14259   // Parameters can not be abstract class types.
14260   // For record types, this is done by the AbstractClassUsageDiagnoser once
14261   // the class has been completely parsed.
14262   if (!CurContext->isRecord() &&
14263       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14264                              AbstractParamType))
14265     New->setInvalidDecl();
14266 
14267   // Parameter declarators cannot be interface types. All ObjC objects are
14268   // passed by reference.
14269   if (T->isObjCObjectType()) {
14270     SourceLocation TypeEndLoc =
14271         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14272     Diag(NameLoc,
14273          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14274       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14275     T = Context.getObjCObjectPointerType(T);
14276     New->setType(T);
14277   }
14278 
14279   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14280   // duration shall not be qualified by an address-space qualifier."
14281   // Since all parameters have automatic store duration, they can not have
14282   // an address space.
14283   if (T.getAddressSpace() != LangAS::Default &&
14284       // OpenCL allows function arguments declared to be an array of a type
14285       // to be qualified with an address space.
14286       !(getLangOpts().OpenCL &&
14287         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14288     Diag(NameLoc, diag::err_arg_with_address_space);
14289     New->setInvalidDecl();
14290   }
14291 
14292   // PPC MMA non-pointer types are not allowed as function argument types.
14293   if (Context.getTargetInfo().getTriple().isPPC64() &&
14294       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14295     New->setInvalidDecl();
14296   }
14297 
14298   return New;
14299 }
14300 
14301 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14302                                            SourceLocation LocAfterDecls) {
14303   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14304 
14305   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14306   // in the declaration list shall have at least one declarator, those
14307   // declarators shall only declare identifiers from the identifier list, and
14308   // every identifier in the identifier list shall be declared.
14309   //
14310   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14311   // identifiers it names shall be declared in the declaration list."
14312   //
14313   // This is why we only diagnose in C99 and later. Note, the other conditions
14314   // listed are checked elsewhere.
14315   if (!FTI.hasPrototype) {
14316     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14317       --i;
14318       if (FTI.Params[i].Param == nullptr) {
14319         if (getLangOpts().C99) {
14320           SmallString<256> Code;
14321           llvm::raw_svector_ostream(Code)
14322               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14323           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14324               << FTI.Params[i].Ident
14325               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14326         }
14327 
14328         // Implicitly declare the argument as type 'int' for lack of a better
14329         // type.
14330         AttributeFactory attrs;
14331         DeclSpec DS(attrs);
14332         const char* PrevSpec; // unused
14333         unsigned DiagID; // unused
14334         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14335                            DiagID, Context.getPrintingPolicy());
14336         // Use the identifier location for the type source range.
14337         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14338         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14339         Declarator ParamD(DS, ParsedAttributesView::none(),
14340                           DeclaratorContext::KNRTypeList);
14341         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14342         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14343       }
14344     }
14345   }
14346 }
14347 
14348 Decl *
14349 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14350                               MultiTemplateParamsArg TemplateParameterLists,
14351                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14352   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14353   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14354   Scope *ParentScope = FnBodyScope->getParent();
14355 
14356   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14357   // we define a non-templated function definition, we will create a declaration
14358   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14359   // The base function declaration will have the equivalent of an `omp declare
14360   // variant` annotation which specifies the mangled definition as a
14361   // specialization function under the OpenMP context defined as part of the
14362   // `omp begin declare variant`.
14363   SmallVector<FunctionDecl *, 4> Bases;
14364   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14365     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14366         ParentScope, D, TemplateParameterLists, Bases);
14367 
14368   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14369   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14370   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14371 
14372   if (!Bases.empty())
14373     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14374 
14375   return Dcl;
14376 }
14377 
14378 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14379   Consumer.HandleInlineFunctionDefinition(D);
14380 }
14381 
14382 static bool
14383 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14384                                 const FunctionDecl *&PossiblePrototype) {
14385   // Don't warn about invalid declarations.
14386   if (FD->isInvalidDecl())
14387     return false;
14388 
14389   // Or declarations that aren't global.
14390   if (!FD->isGlobal())
14391     return false;
14392 
14393   // Don't warn about C++ member functions.
14394   if (isa<CXXMethodDecl>(FD))
14395     return false;
14396 
14397   // Don't warn about 'main'.
14398   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14399     if (IdentifierInfo *II = FD->getIdentifier())
14400       if (II->isStr("main") || II->isStr("efi_main"))
14401         return false;
14402 
14403   // Don't warn about inline functions.
14404   if (FD->isInlined())
14405     return false;
14406 
14407   // Don't warn about function templates.
14408   if (FD->getDescribedFunctionTemplate())
14409     return false;
14410 
14411   // Don't warn about function template specializations.
14412   if (FD->isFunctionTemplateSpecialization())
14413     return false;
14414 
14415   // Don't warn for OpenCL kernels.
14416   if (FD->hasAttr<OpenCLKernelAttr>())
14417     return false;
14418 
14419   // Don't warn on explicitly deleted functions.
14420   if (FD->isDeleted())
14421     return false;
14422 
14423   // Don't warn on implicitly local functions (such as having local-typed
14424   // parameters).
14425   if (!FD->isExternallyVisible())
14426     return false;
14427 
14428   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14429        Prev; Prev = Prev->getPreviousDecl()) {
14430     // Ignore any declarations that occur in function or method
14431     // scope, because they aren't visible from the header.
14432     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14433       continue;
14434 
14435     PossiblePrototype = Prev;
14436     return Prev->getType()->isFunctionNoProtoType();
14437   }
14438 
14439   return true;
14440 }
14441 
14442 void
14443 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14444                                    const FunctionDecl *EffectiveDefinition,
14445                                    SkipBodyInfo *SkipBody) {
14446   const FunctionDecl *Definition = EffectiveDefinition;
14447   if (!Definition &&
14448       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14449     return;
14450 
14451   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14452     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14453       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14454         // A merged copy of the same function, instantiated as a member of
14455         // the same class, is OK.
14456         if (declaresSameEntity(OrigFD, OrigDef) &&
14457             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14458                                cast<Decl>(FD->getLexicalDeclContext())))
14459           return;
14460       }
14461     }
14462   }
14463 
14464   if (canRedefineFunction(Definition, getLangOpts()))
14465     return;
14466 
14467   // Don't emit an error when this is redefinition of a typo-corrected
14468   // definition.
14469   if (TypoCorrectedFunctionDefinitions.count(Definition))
14470     return;
14471 
14472   // If we don't have a visible definition of the function, and it's inline or
14473   // a template, skip the new definition.
14474   if (SkipBody && !hasVisibleDefinition(Definition) &&
14475       (Definition->getFormalLinkage() == InternalLinkage ||
14476        Definition->isInlined() ||
14477        Definition->getDescribedFunctionTemplate() ||
14478        Definition->getNumTemplateParameterLists())) {
14479     SkipBody->ShouldSkip = true;
14480     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14481     if (auto *TD = Definition->getDescribedFunctionTemplate())
14482       makeMergedDefinitionVisible(TD);
14483     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14484     return;
14485   }
14486 
14487   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14488       Definition->getStorageClass() == SC_Extern)
14489     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14490         << FD << getLangOpts().CPlusPlus;
14491   else
14492     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14493 
14494   Diag(Definition->getLocation(), diag::note_previous_definition);
14495   FD->setInvalidDecl();
14496 }
14497 
14498 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14499                                    Sema &S) {
14500   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14501 
14502   LambdaScopeInfo *LSI = S.PushLambdaScope();
14503   LSI->CallOperator = CallOperator;
14504   LSI->Lambda = LambdaClass;
14505   LSI->ReturnType = CallOperator->getReturnType();
14506   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14507 
14508   if (LCD == LCD_None)
14509     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14510   else if (LCD == LCD_ByCopy)
14511     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14512   else if (LCD == LCD_ByRef)
14513     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14514   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14515 
14516   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14517   LSI->Mutable = !CallOperator->isConst();
14518 
14519   // Add the captures to the LSI so they can be noted as already
14520   // captured within tryCaptureVar.
14521   auto I = LambdaClass->field_begin();
14522   for (const auto &C : LambdaClass->captures()) {
14523     if (C.capturesVariable()) {
14524       VarDecl *VD = C.getCapturedVar();
14525       if (VD->isInitCapture())
14526         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14527       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14528       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14529           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14530           /*EllipsisLoc*/C.isPackExpansion()
14531                          ? C.getEllipsisLoc() : SourceLocation(),
14532           I->getType(), /*Invalid*/false);
14533 
14534     } else if (C.capturesThis()) {
14535       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14536                           C.getCaptureKind() == LCK_StarThis);
14537     } else {
14538       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14539                              I->getType());
14540     }
14541     ++I;
14542   }
14543 }
14544 
14545 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14546                                     SkipBodyInfo *SkipBody,
14547                                     FnBodyKind BodyKind) {
14548   if (!D) {
14549     // Parsing the function declaration failed in some way. Push on a fake scope
14550     // anyway so we can try to parse the function body.
14551     PushFunctionScope();
14552     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14553     return D;
14554   }
14555 
14556   FunctionDecl *FD = nullptr;
14557 
14558   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14559     FD = FunTmpl->getTemplatedDecl();
14560   else
14561     FD = cast<FunctionDecl>(D);
14562 
14563   // Do not push if it is a lambda because one is already pushed when building
14564   // the lambda in ActOnStartOfLambdaDefinition().
14565   if (!isLambdaCallOperator(FD))
14566     PushExpressionEvaluationContext(
14567         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14568                           : ExprEvalContexts.back().Context);
14569 
14570   // Check for defining attributes before the check for redefinition.
14571   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14572     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14573     FD->dropAttr<AliasAttr>();
14574     FD->setInvalidDecl();
14575   }
14576   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14577     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14578     FD->dropAttr<IFuncAttr>();
14579     FD->setInvalidDecl();
14580   }
14581 
14582   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14583     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14584         Ctor->isDefaultConstructor() &&
14585         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14586       // If this is an MS ABI dllexport default constructor, instantiate any
14587       // default arguments.
14588       InstantiateDefaultCtorDefaultArgs(Ctor);
14589     }
14590   }
14591 
14592   // See if this is a redefinition. If 'will have body' (or similar) is already
14593   // set, then these checks were already performed when it was set.
14594   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14595       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14596     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14597 
14598     // If we're skipping the body, we're done. Don't enter the scope.
14599     if (SkipBody && SkipBody->ShouldSkip)
14600       return D;
14601   }
14602 
14603   // Mark this function as "will have a body eventually".  This lets users to
14604   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14605   // this function.
14606   FD->setWillHaveBody();
14607 
14608   // If we are instantiating a generic lambda call operator, push
14609   // a LambdaScopeInfo onto the function stack.  But use the information
14610   // that's already been calculated (ActOnLambdaExpr) to prime the current
14611   // LambdaScopeInfo.
14612   // When the template operator is being specialized, the LambdaScopeInfo,
14613   // has to be properly restored so that tryCaptureVariable doesn't try
14614   // and capture any new variables. In addition when calculating potential
14615   // captures during transformation of nested lambdas, it is necessary to
14616   // have the LSI properly restored.
14617   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14618     assert(inTemplateInstantiation() &&
14619            "There should be an active template instantiation on the stack "
14620            "when instantiating a generic lambda!");
14621     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14622   } else {
14623     // Enter a new function scope
14624     PushFunctionScope();
14625   }
14626 
14627   // Builtin functions cannot be defined.
14628   if (unsigned BuiltinID = FD->getBuiltinID()) {
14629     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14630         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14631       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14632       FD->setInvalidDecl();
14633     }
14634   }
14635 
14636   // The return type of a function definition must be complete (C99 6.9.1p3),
14637   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14638   QualType ResultType = FD->getReturnType();
14639   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14640       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14641       RequireCompleteType(FD->getLocation(), ResultType,
14642                           diag::err_func_def_incomplete_result))
14643     FD->setInvalidDecl();
14644 
14645   if (FnBodyScope)
14646     PushDeclContext(FnBodyScope, FD);
14647 
14648   // Check the validity of our function parameters
14649   if (BodyKind != FnBodyKind::Delete)
14650     CheckParmsForFunctionDef(FD->parameters(),
14651                              /*CheckParameterNames=*/true);
14652 
14653   // Add non-parameter declarations already in the function to the current
14654   // scope.
14655   if (FnBodyScope) {
14656     for (Decl *NPD : FD->decls()) {
14657       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14658       if (!NonParmDecl)
14659         continue;
14660       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14661              "parameters should not be in newly created FD yet");
14662 
14663       // If the decl has a name, make it accessible in the current scope.
14664       if (NonParmDecl->getDeclName())
14665         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14666 
14667       // Similarly, dive into enums and fish their constants out, making them
14668       // accessible in this scope.
14669       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14670         for (auto *EI : ED->enumerators())
14671           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14672       }
14673     }
14674   }
14675 
14676   // Introduce our parameters into the function scope
14677   for (auto Param : FD->parameters()) {
14678     Param->setOwningFunction(FD);
14679 
14680     // If this has an identifier, add it to the scope stack.
14681     if (Param->getIdentifier() && FnBodyScope) {
14682       CheckShadow(FnBodyScope, Param);
14683 
14684       PushOnScopeChains(Param, FnBodyScope);
14685     }
14686   }
14687 
14688   // Ensure that the function's exception specification is instantiated.
14689   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14690     ResolveExceptionSpec(D->getLocation(), FPT);
14691 
14692   // dllimport cannot be applied to non-inline function definitions.
14693   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14694       !FD->isTemplateInstantiation()) {
14695     assert(!FD->hasAttr<DLLExportAttr>());
14696     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14697     FD->setInvalidDecl();
14698     return D;
14699   }
14700   // We want to attach documentation to original Decl (which might be
14701   // a function template).
14702   ActOnDocumentableDecl(D);
14703   if (getCurLexicalContext()->isObjCContainer() &&
14704       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14705       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14706     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14707 
14708   return D;
14709 }
14710 
14711 /// Given the set of return statements within a function body,
14712 /// compute the variables that are subject to the named return value
14713 /// optimization.
14714 ///
14715 /// Each of the variables that is subject to the named return value
14716 /// optimization will be marked as NRVO variables in the AST, and any
14717 /// return statement that has a marked NRVO variable as its NRVO candidate can
14718 /// use the named return value optimization.
14719 ///
14720 /// This function applies a very simplistic algorithm for NRVO: if every return
14721 /// statement in the scope of a variable has the same NRVO candidate, that
14722 /// candidate is an NRVO variable.
14723 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14724   ReturnStmt **Returns = Scope->Returns.data();
14725 
14726   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14727     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14728       if (!NRVOCandidate->isNRVOVariable())
14729         Returns[I]->setNRVOCandidate(nullptr);
14730     }
14731   }
14732 }
14733 
14734 bool Sema::canDelayFunctionBody(const Declarator &D) {
14735   // We can't delay parsing the body of a constexpr function template (yet).
14736   if (D.getDeclSpec().hasConstexprSpecifier())
14737     return false;
14738 
14739   // We can't delay parsing the body of a function template with a deduced
14740   // return type (yet).
14741   if (D.getDeclSpec().hasAutoTypeSpec()) {
14742     // If the placeholder introduces a non-deduced trailing return type,
14743     // we can still delay parsing it.
14744     if (D.getNumTypeObjects()) {
14745       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14746       if (Outer.Kind == DeclaratorChunk::Function &&
14747           Outer.Fun.hasTrailingReturnType()) {
14748         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14749         return Ty.isNull() || !Ty->isUndeducedType();
14750       }
14751     }
14752     return false;
14753   }
14754 
14755   return true;
14756 }
14757 
14758 bool Sema::canSkipFunctionBody(Decl *D) {
14759   // We cannot skip the body of a function (or function template) which is
14760   // constexpr, since we may need to evaluate its body in order to parse the
14761   // rest of the file.
14762   // We cannot skip the body of a function with an undeduced return type,
14763   // because any callers of that function need to know the type.
14764   if (const FunctionDecl *FD = D->getAsFunction()) {
14765     if (FD->isConstexpr())
14766       return false;
14767     // We can't simply call Type::isUndeducedType here, because inside template
14768     // auto can be deduced to a dependent type, which is not considered
14769     // "undeduced".
14770     if (FD->getReturnType()->getContainedDeducedType())
14771       return false;
14772   }
14773   return Consumer.shouldSkipFunctionBody(D);
14774 }
14775 
14776 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14777   if (!Decl)
14778     return nullptr;
14779   if (FunctionDecl *FD = Decl->getAsFunction())
14780     FD->setHasSkippedBody();
14781   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14782     MD->setHasSkippedBody();
14783   return Decl;
14784 }
14785 
14786 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14787   return ActOnFinishFunctionBody(D, BodyArg, false);
14788 }
14789 
14790 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14791 /// body.
14792 class ExitFunctionBodyRAII {
14793 public:
14794   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14795   ~ExitFunctionBodyRAII() {
14796     if (!IsLambda)
14797       S.PopExpressionEvaluationContext();
14798   }
14799 
14800 private:
14801   Sema &S;
14802   bool IsLambda = false;
14803 };
14804 
14805 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14806   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14807 
14808   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14809     if (EscapeInfo.count(BD))
14810       return EscapeInfo[BD];
14811 
14812     bool R = false;
14813     const BlockDecl *CurBD = BD;
14814 
14815     do {
14816       R = !CurBD->doesNotEscape();
14817       if (R)
14818         break;
14819       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14820     } while (CurBD);
14821 
14822     return EscapeInfo[BD] = R;
14823   };
14824 
14825   // If the location where 'self' is implicitly retained is inside a escaping
14826   // block, emit a diagnostic.
14827   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14828        S.ImplicitlyRetainedSelfLocs)
14829     if (IsOrNestedInEscapingBlock(P.second))
14830       S.Diag(P.first, diag::warn_implicitly_retains_self)
14831           << FixItHint::CreateInsertion(P.first, "self->");
14832 }
14833 
14834 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14835                                     bool IsInstantiation) {
14836   FunctionScopeInfo *FSI = getCurFunction();
14837   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14838 
14839   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14840     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14841 
14842   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14843   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14844 
14845   if (getLangOpts().Coroutines && FSI->isCoroutine())
14846     CheckCompletedCoroutineBody(FD, Body);
14847 
14848   {
14849     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14850     // one is already popped when finishing the lambda in BuildLambdaExpr().
14851     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14852     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14853 
14854     if (FD) {
14855       FD->setBody(Body);
14856       FD->setWillHaveBody(false);
14857 
14858       if (getLangOpts().CPlusPlus14) {
14859         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14860             FD->getReturnType()->isUndeducedType()) {
14861           // For a function with a deduced result type to return void,
14862           // the result type as written must be 'auto' or 'decltype(auto)',
14863           // possibly cv-qualified or constrained, but not ref-qualified.
14864           if (!FD->getReturnType()->getAs<AutoType>()) {
14865             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14866                 << FD->getReturnType();
14867             FD->setInvalidDecl();
14868           } else {
14869             // Falling off the end of the function is the same as 'return;'.
14870             Expr *Dummy = nullptr;
14871             if (DeduceFunctionTypeFromReturnExpr(
14872                     FD, dcl->getLocation(), Dummy,
14873                     FD->getReturnType()->getAs<AutoType>()))
14874               FD->setInvalidDecl();
14875           }
14876         }
14877       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14878         // In C++11, we don't use 'auto' deduction rules for lambda call
14879         // operators because we don't support return type deduction.
14880         auto *LSI = getCurLambda();
14881         if (LSI->HasImplicitReturnType) {
14882           deduceClosureReturnType(*LSI);
14883 
14884           // C++11 [expr.prim.lambda]p4:
14885           //   [...] if there are no return statements in the compound-statement
14886           //   [the deduced type is] the type void
14887           QualType RetType =
14888               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14889 
14890           // Update the return type to the deduced type.
14891           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14892           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14893                                               Proto->getExtProtoInfo()));
14894         }
14895       }
14896 
14897       // If the function implicitly returns zero (like 'main') or is naked,
14898       // don't complain about missing return statements.
14899       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14900         WP.disableCheckFallThrough();
14901 
14902       // MSVC permits the use of pure specifier (=0) on function definition,
14903       // defined at class scope, warn about this non-standard construct.
14904       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14905         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14906 
14907       if (!FD->isInvalidDecl()) {
14908         // Don't diagnose unused parameters of defaulted, deleted or naked
14909         // functions.
14910         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14911             !FD->hasAttr<NakedAttr>())
14912           DiagnoseUnusedParameters(FD->parameters());
14913         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14914                                                FD->getReturnType(), FD);
14915 
14916         // If this is a structor, we need a vtable.
14917         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14918           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14919         else if (CXXDestructorDecl *Destructor =
14920                      dyn_cast<CXXDestructorDecl>(FD))
14921           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14922 
14923         // Try to apply the named return value optimization. We have to check
14924         // if we can do this here because lambdas keep return statements around
14925         // to deduce an implicit return type.
14926         if (FD->getReturnType()->isRecordType() &&
14927             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14928           computeNRVO(Body, FSI);
14929       }
14930 
14931       // GNU warning -Wmissing-prototypes:
14932       //   Warn if a global function is defined without a previous
14933       //   prototype declaration. This warning is issued even if the
14934       //   definition itself provides a prototype. The aim is to detect
14935       //   global functions that fail to be declared in header files.
14936       const FunctionDecl *PossiblePrototype = nullptr;
14937       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14938         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14939 
14940         if (PossiblePrototype) {
14941           // We found a declaration that is not a prototype,
14942           // but that could be a zero-parameter prototype
14943           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14944             TypeLoc TL = TI->getTypeLoc();
14945             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14946               Diag(PossiblePrototype->getLocation(),
14947                    diag::note_declaration_not_a_prototype)
14948                   << (FD->getNumParams() != 0)
14949                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14950                                                     FTL.getRParenLoc(), "void")
14951                                               : FixItHint{});
14952           }
14953         } else {
14954           // Returns true if the token beginning at this Loc is `const`.
14955           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14956                                   const LangOptions &LangOpts) {
14957             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14958             if (LocInfo.first.isInvalid())
14959               return false;
14960 
14961             bool Invalid = false;
14962             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14963             if (Invalid)
14964               return false;
14965 
14966             if (LocInfo.second > Buffer.size())
14967               return false;
14968 
14969             const char *LexStart = Buffer.data() + LocInfo.second;
14970             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14971 
14972             return StartTok.consume_front("const") &&
14973                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14974                     StartTok.startswith("/*") || StartTok.startswith("//"));
14975           };
14976 
14977           auto findBeginLoc = [&]() {
14978             // If the return type has `const` qualifier, we want to insert
14979             // `static` before `const` (and not before the typename).
14980             if ((FD->getReturnType()->isAnyPointerType() &&
14981                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14982                 FD->getReturnType().isConstQualified()) {
14983               // But only do this if we can determine where the `const` is.
14984 
14985               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14986                                getLangOpts()))
14987 
14988                 return FD->getBeginLoc();
14989             }
14990             return FD->getTypeSpecStartLoc();
14991           };
14992           Diag(FD->getTypeSpecStartLoc(),
14993                diag::note_static_for_internal_linkage)
14994               << /* function */ 1
14995               << (FD->getStorageClass() == SC_None
14996                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14997                       : FixItHint{});
14998         }
14999       }
15000 
15001       // If the function being defined does not have a prototype, then we may
15002       // need to diagnose it as changing behavior in C2x because we now know
15003       // whether the function accepts arguments or not. This only handles the
15004       // case where the definition has no prototype but does have parameters
15005       // and either there is no previous potential prototype, or the previous
15006       // potential prototype also has no actual prototype. This handles cases
15007       // like:
15008       //   void f(); void f(a) int a; {}
15009       //   void g(a) int a; {}
15010       // See MergeFunctionDecl() for other cases of the behavior change
15011       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15012       // type without a prototype.
15013       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15014           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15015                                   !PossiblePrototype->isImplicit()))) {
15016         // The function definition has parameters, so this will change behavior
15017         // in C2x. If there is a possible prototype, it comes before the
15018         // function definition.
15019         // FIXME: The declaration may have already been diagnosed as being
15020         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15021         // there's no way to test for the "changes behavior" condition in
15022         // SemaType.cpp when forming the declaration's function type. So, we do
15023         // this awkward dance instead.
15024         //
15025         // If we have a possible prototype and it declares a function with a
15026         // prototype, we don't want to diagnose it; if we have a possible
15027         // prototype and it has no prototype, it may have already been
15028         // diagnosed in SemaType.cpp as deprecated depending on whether
15029         // -Wstrict-prototypes is enabled. If we already warned about it being
15030         // deprecated, add a note that it also changes behavior. If we didn't
15031         // warn about it being deprecated (because the diagnostic is not
15032         // enabled), warn now that it is deprecated and changes behavior.
15033 
15034         // This K&R C function definition definitely changes behavior in C2x,
15035         // so diagnose it.
15036         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15037             << /*definition*/ 1 << /* not supported in C2x */ 0;
15038 
15039         // If we have a possible prototype for the function which is a user-
15040         // visible declaration, we already tested that it has no prototype.
15041         // This will change behavior in C2x. This gets a warning rather than a
15042         // note because it's the same behavior-changing problem as with the
15043         // definition.
15044         if (PossiblePrototype)
15045           Diag(PossiblePrototype->getLocation(),
15046                diag::warn_non_prototype_changes_behavior)
15047               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15048               << /*definition*/ 1;
15049       }
15050 
15051       // Warn on CPUDispatch with an actual body.
15052       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15053         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15054           if (!CmpndBody->body_empty())
15055             Diag(CmpndBody->body_front()->getBeginLoc(),
15056                  diag::warn_dispatch_body_ignored);
15057 
15058       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15059         const CXXMethodDecl *KeyFunction;
15060         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15061             MD->isVirtual() &&
15062             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15063             MD == KeyFunction->getCanonicalDecl()) {
15064           // Update the key-function state if necessary for this ABI.
15065           if (FD->isInlined() &&
15066               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15067             Context.setNonKeyFunction(MD);
15068 
15069             // If the newly-chosen key function is already defined, then we
15070             // need to mark the vtable as used retroactively.
15071             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15072             const FunctionDecl *Definition;
15073             if (KeyFunction && KeyFunction->isDefined(Definition))
15074               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15075           } else {
15076             // We just defined they key function; mark the vtable as used.
15077             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15078           }
15079         }
15080       }
15081 
15082       assert(
15083           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15084           "Function parsing confused");
15085     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15086       assert(MD == getCurMethodDecl() && "Method parsing confused");
15087       MD->setBody(Body);
15088       if (!MD->isInvalidDecl()) {
15089         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15090                                                MD->getReturnType(), MD);
15091 
15092         if (Body)
15093           computeNRVO(Body, FSI);
15094       }
15095       if (FSI->ObjCShouldCallSuper) {
15096         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15097             << MD->getSelector().getAsString();
15098         FSI->ObjCShouldCallSuper = false;
15099       }
15100       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15101         const ObjCMethodDecl *InitMethod = nullptr;
15102         bool isDesignated =
15103             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15104         assert(isDesignated && InitMethod);
15105         (void)isDesignated;
15106 
15107         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15108           auto IFace = MD->getClassInterface();
15109           if (!IFace)
15110             return false;
15111           auto SuperD = IFace->getSuperClass();
15112           if (!SuperD)
15113             return false;
15114           return SuperD->getIdentifier() ==
15115                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15116         };
15117         // Don't issue this warning for unavailable inits or direct subclasses
15118         // of NSObject.
15119         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15120           Diag(MD->getLocation(),
15121                diag::warn_objc_designated_init_missing_super_call);
15122           Diag(InitMethod->getLocation(),
15123                diag::note_objc_designated_init_marked_here);
15124         }
15125         FSI->ObjCWarnForNoDesignatedInitChain = false;
15126       }
15127       if (FSI->ObjCWarnForNoInitDelegation) {
15128         // Don't issue this warning for unavaialable inits.
15129         if (!MD->isUnavailable())
15130           Diag(MD->getLocation(),
15131                diag::warn_objc_secondary_init_missing_init_call);
15132         FSI->ObjCWarnForNoInitDelegation = false;
15133       }
15134 
15135       diagnoseImplicitlyRetainedSelf(*this);
15136     } else {
15137       // Parsing the function declaration failed in some way. Pop the fake scope
15138       // we pushed on.
15139       PopFunctionScopeInfo(ActivePolicy, dcl);
15140       return nullptr;
15141     }
15142 
15143     if (Body && FSI->HasPotentialAvailabilityViolations)
15144       DiagnoseUnguardedAvailabilityViolations(dcl);
15145 
15146     assert(!FSI->ObjCShouldCallSuper &&
15147            "This should only be set for ObjC methods, which should have been "
15148            "handled in the block above.");
15149 
15150     // Verify and clean out per-function state.
15151     if (Body && (!FD || !FD->isDefaulted())) {
15152       // C++ constructors that have function-try-blocks can't have return
15153       // statements in the handlers of that block. (C++ [except.handle]p14)
15154       // Verify this.
15155       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15156         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15157 
15158       // Verify that gotos and switch cases don't jump into scopes illegally.
15159       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15160         DiagnoseInvalidJumps(Body);
15161 
15162       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15163         if (!Destructor->getParent()->isDependentType())
15164           CheckDestructor(Destructor);
15165 
15166         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15167                                                Destructor->getParent());
15168       }
15169 
15170       // If any errors have occurred, clear out any temporaries that may have
15171       // been leftover. This ensures that these temporaries won't be picked up
15172       // for deletion in some later function.
15173       if (hasUncompilableErrorOccurred() ||
15174           getDiagnostics().getSuppressAllDiagnostics()) {
15175         DiscardCleanupsInEvaluationContext();
15176       }
15177       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15178         // Since the body is valid, issue any analysis-based warnings that are
15179         // enabled.
15180         ActivePolicy = &WP;
15181       }
15182 
15183       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15184           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15185         FD->setInvalidDecl();
15186 
15187       if (FD && FD->hasAttr<NakedAttr>()) {
15188         for (const Stmt *S : Body->children()) {
15189           // Allow local register variables without initializer as they don't
15190           // require prologue.
15191           bool RegisterVariables = false;
15192           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15193             for (const auto *Decl : DS->decls()) {
15194               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15195                 RegisterVariables =
15196                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15197                 if (!RegisterVariables)
15198                   break;
15199               }
15200             }
15201           }
15202           if (RegisterVariables)
15203             continue;
15204           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15205             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15206             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15207             FD->setInvalidDecl();
15208             break;
15209           }
15210         }
15211       }
15212 
15213       assert(ExprCleanupObjects.size() ==
15214                  ExprEvalContexts.back().NumCleanupObjects &&
15215              "Leftover temporaries in function");
15216       assert(!Cleanup.exprNeedsCleanups() &&
15217              "Unaccounted cleanups in function");
15218       assert(MaybeODRUseExprs.empty() &&
15219              "Leftover expressions for odr-use checking");
15220     }
15221   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15222     // the declaration context below. Otherwise, we're unable to transform
15223     // 'this' expressions when transforming immediate context functions.
15224 
15225   if (!IsInstantiation)
15226     PopDeclContext();
15227 
15228   PopFunctionScopeInfo(ActivePolicy, dcl);
15229   // If any errors have occurred, clear out any temporaries that may have
15230   // been leftover. This ensures that these temporaries won't be picked up for
15231   // deletion in some later function.
15232   if (hasUncompilableErrorOccurred()) {
15233     DiscardCleanupsInEvaluationContext();
15234   }
15235 
15236   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15237                                   !LangOpts.OMPTargetTriples.empty())) ||
15238              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15239     auto ES = getEmissionStatus(FD);
15240     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15241         ES == Sema::FunctionEmissionStatus::Unknown)
15242       DeclsToCheckForDeferredDiags.insert(FD);
15243   }
15244 
15245   if (FD && !FD->isDeleted())
15246     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15247 
15248   return dcl;
15249 }
15250 
15251 /// When we finish delayed parsing of an attribute, we must attach it to the
15252 /// relevant Decl.
15253 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15254                                        ParsedAttributes &Attrs) {
15255   // Always attach attributes to the underlying decl.
15256   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15257     D = TD->getTemplatedDecl();
15258   ProcessDeclAttributeList(S, D, Attrs);
15259 
15260   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15261     if (Method->isStatic())
15262       checkThisInStaticMemberFunctionAttributes(Method);
15263 }
15264 
15265 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15266 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15267 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15268                                           IdentifierInfo &II, Scope *S) {
15269   // It is not valid to implicitly define a function in C2x.
15270   assert(LangOpts.implicitFunctionsAllowed() &&
15271          "Implicit function declarations aren't allowed in this language mode");
15272 
15273   // Find the scope in which the identifier is injected and the corresponding
15274   // DeclContext.
15275   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15276   // In that case, we inject the declaration into the translation unit scope
15277   // instead.
15278   Scope *BlockScope = S;
15279   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15280     BlockScope = BlockScope->getParent();
15281 
15282   Scope *ContextScope = BlockScope;
15283   while (!ContextScope->getEntity())
15284     ContextScope = ContextScope->getParent();
15285   ContextRAII SavedContext(*this, ContextScope->getEntity());
15286 
15287   // Before we produce a declaration for an implicitly defined
15288   // function, see whether there was a locally-scoped declaration of
15289   // this name as a function or variable. If so, use that
15290   // (non-visible) declaration, and complain about it.
15291   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15292   if (ExternCPrev) {
15293     // We still need to inject the function into the enclosing block scope so
15294     // that later (non-call) uses can see it.
15295     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15296 
15297     // C89 footnote 38:
15298     //   If in fact it is not defined as having type "function returning int",
15299     //   the behavior is undefined.
15300     if (!isa<FunctionDecl>(ExternCPrev) ||
15301         !Context.typesAreCompatible(
15302             cast<FunctionDecl>(ExternCPrev)->getType(),
15303             Context.getFunctionNoProtoType(Context.IntTy))) {
15304       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15305           << ExternCPrev << !getLangOpts().C99;
15306       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15307       return ExternCPrev;
15308     }
15309   }
15310 
15311   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15312   unsigned diag_id;
15313   if (II.getName().startswith("__builtin_"))
15314     diag_id = diag::warn_builtin_unknown;
15315   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15316   else if (getLangOpts().C99)
15317     diag_id = diag::ext_implicit_function_decl_c99;
15318   else
15319     diag_id = diag::warn_implicit_function_decl;
15320 
15321   TypoCorrection Corrected;
15322   // Because typo correction is expensive, only do it if the implicit
15323   // function declaration is going to be treated as an error.
15324   //
15325   // Perform the corection before issuing the main diagnostic, as some consumers
15326   // use typo-correction callbacks to enhance the main diagnostic.
15327   if (S && !ExternCPrev &&
15328       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15329     DeclFilterCCC<FunctionDecl> CCC{};
15330     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15331                             S, nullptr, CCC, CTK_NonError);
15332   }
15333 
15334   Diag(Loc, diag_id) << &II;
15335   if (Corrected) {
15336     // If the correction is going to suggest an implicitly defined function,
15337     // skip the correction as not being a particularly good idea.
15338     bool Diagnose = true;
15339     if (const auto *D = Corrected.getCorrectionDecl())
15340       Diagnose = !D->isImplicit();
15341     if (Diagnose)
15342       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15343                    /*ErrorRecovery*/ false);
15344   }
15345 
15346   // If we found a prior declaration of this function, don't bother building
15347   // another one. We've already pushed that one into scope, so there's nothing
15348   // more to do.
15349   if (ExternCPrev)
15350     return ExternCPrev;
15351 
15352   // Set a Declarator for the implicit definition: int foo();
15353   const char *Dummy;
15354   AttributeFactory attrFactory;
15355   DeclSpec DS(attrFactory);
15356   unsigned DiagID;
15357   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15358                                   Context.getPrintingPolicy());
15359   (void)Error; // Silence warning.
15360   assert(!Error && "Error setting up implicit decl!");
15361   SourceLocation NoLoc;
15362   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15363   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15364                                              /*IsAmbiguous=*/false,
15365                                              /*LParenLoc=*/NoLoc,
15366                                              /*Params=*/nullptr,
15367                                              /*NumParams=*/0,
15368                                              /*EllipsisLoc=*/NoLoc,
15369                                              /*RParenLoc=*/NoLoc,
15370                                              /*RefQualifierIsLvalueRef=*/true,
15371                                              /*RefQualifierLoc=*/NoLoc,
15372                                              /*MutableLoc=*/NoLoc, EST_None,
15373                                              /*ESpecRange=*/SourceRange(),
15374                                              /*Exceptions=*/nullptr,
15375                                              /*ExceptionRanges=*/nullptr,
15376                                              /*NumExceptions=*/0,
15377                                              /*NoexceptExpr=*/nullptr,
15378                                              /*ExceptionSpecTokens=*/nullptr,
15379                                              /*DeclsInPrototype=*/None, Loc,
15380                                              Loc, D),
15381                 std::move(DS.getAttributes()), SourceLocation());
15382   D.SetIdentifier(&II, Loc);
15383 
15384   // Insert this function into the enclosing block scope.
15385   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15386   FD->setImplicit();
15387 
15388   AddKnownFunctionAttributes(FD);
15389 
15390   return FD;
15391 }
15392 
15393 /// If this function is a C++ replaceable global allocation function
15394 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15395 /// adds any function attributes that we know a priori based on the standard.
15396 ///
15397 /// We need to check for duplicate attributes both here and where user-written
15398 /// attributes are applied to declarations.
15399 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15400     FunctionDecl *FD) {
15401   if (FD->isInvalidDecl())
15402     return;
15403 
15404   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15405       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15406     return;
15407 
15408   Optional<unsigned> AlignmentParam;
15409   bool IsNothrow = false;
15410   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15411     return;
15412 
15413   // C++2a [basic.stc.dynamic.allocation]p4:
15414   //   An allocation function that has a non-throwing exception specification
15415   //   indicates failure by returning a null pointer value. Any other allocation
15416   //   function never returns a null pointer value and indicates failure only by
15417   //   throwing an exception [...]
15418   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15419     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15420 
15421   // C++2a [basic.stc.dynamic.allocation]p2:
15422   //   An allocation function attempts to allocate the requested amount of
15423   //   storage. [...] If the request succeeds, the value returned by a
15424   //   replaceable allocation function is a [...] pointer value p0 different
15425   //   from any previously returned value p1 [...]
15426   //
15427   // However, this particular information is being added in codegen,
15428   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15429 
15430   // C++2a [basic.stc.dynamic.allocation]p2:
15431   //   An allocation function attempts to allocate the requested amount of
15432   //   storage. If it is successful, it returns the address of the start of a
15433   //   block of storage whose length in bytes is at least as large as the
15434   //   requested size.
15435   if (!FD->hasAttr<AllocSizeAttr>()) {
15436     FD->addAttr(AllocSizeAttr::CreateImplicit(
15437         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15438         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15439   }
15440 
15441   // C++2a [basic.stc.dynamic.allocation]p3:
15442   //   For an allocation function [...], the pointer returned on a successful
15443   //   call shall represent the address of storage that is aligned as follows:
15444   //   (3.1) If the allocation function takes an argument of type
15445   //         std​::​align_­val_­t, the storage will have the alignment
15446   //         specified by the value of this argument.
15447   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15448     FD->addAttr(AllocAlignAttr::CreateImplicit(
15449         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15450   }
15451 
15452   // FIXME:
15453   // C++2a [basic.stc.dynamic.allocation]p3:
15454   //   For an allocation function [...], the pointer returned on a successful
15455   //   call shall represent the address of storage that is aligned as follows:
15456   //   (3.2) Otherwise, if the allocation function is named operator new[],
15457   //         the storage is aligned for any object that does not have
15458   //         new-extended alignment ([basic.align]) and is no larger than the
15459   //         requested size.
15460   //   (3.3) Otherwise, the storage is aligned for any object that does not
15461   //         have new-extended alignment and is of the requested size.
15462 }
15463 
15464 /// Adds any function attributes that we know a priori based on
15465 /// the declaration of this function.
15466 ///
15467 /// These attributes can apply both to implicitly-declared builtins
15468 /// (like __builtin___printf_chk) or to library-declared functions
15469 /// like NSLog or printf.
15470 ///
15471 /// We need to check for duplicate attributes both here and where user-written
15472 /// attributes are applied to declarations.
15473 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15474   if (FD->isInvalidDecl())
15475     return;
15476 
15477   // If this is a built-in function, map its builtin attributes to
15478   // actual attributes.
15479   if (unsigned BuiltinID = FD->getBuiltinID()) {
15480     // Handle printf-formatting attributes.
15481     unsigned FormatIdx;
15482     bool HasVAListArg;
15483     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15484       if (!FD->hasAttr<FormatAttr>()) {
15485         const char *fmt = "printf";
15486         unsigned int NumParams = FD->getNumParams();
15487         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15488             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15489           fmt = "NSString";
15490         FD->addAttr(FormatAttr::CreateImplicit(Context,
15491                                                &Context.Idents.get(fmt),
15492                                                FormatIdx+1,
15493                                                HasVAListArg ? 0 : FormatIdx+2,
15494                                                FD->getLocation()));
15495       }
15496     }
15497     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15498                                              HasVAListArg)) {
15499      if (!FD->hasAttr<FormatAttr>())
15500        FD->addAttr(FormatAttr::CreateImplicit(Context,
15501                                               &Context.Idents.get("scanf"),
15502                                               FormatIdx+1,
15503                                               HasVAListArg ? 0 : FormatIdx+2,
15504                                               FD->getLocation()));
15505     }
15506 
15507     // Handle automatically recognized callbacks.
15508     SmallVector<int, 4> Encoding;
15509     if (!FD->hasAttr<CallbackAttr>() &&
15510         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15511       FD->addAttr(CallbackAttr::CreateImplicit(
15512           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15513 
15514     // Mark const if we don't care about errno and that is the only thing
15515     // preventing the function from being const. This allows IRgen to use LLVM
15516     // intrinsics for such functions.
15517     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15518         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15519       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15520 
15521     // We make "fma" on GNU or Windows const because we know it does not set
15522     // errno in those environments even though it could set errno based on the
15523     // C standard.
15524     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15525     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15526         !FD->hasAttr<ConstAttr>()) {
15527       switch (BuiltinID) {
15528       case Builtin::BI__builtin_fma:
15529       case Builtin::BI__builtin_fmaf:
15530       case Builtin::BI__builtin_fmal:
15531       case Builtin::BIfma:
15532       case Builtin::BIfmaf:
15533       case Builtin::BIfmal:
15534         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15535         break;
15536       default:
15537         break;
15538       }
15539     }
15540 
15541     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15542         !FD->hasAttr<ReturnsTwiceAttr>())
15543       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15544                                          FD->getLocation()));
15545     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15546       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15547     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15548       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15549     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15550       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15551     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15552         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15553       // Add the appropriate attribute, depending on the CUDA compilation mode
15554       // and which target the builtin belongs to. For example, during host
15555       // compilation, aux builtins are __device__, while the rest are __host__.
15556       if (getLangOpts().CUDAIsDevice !=
15557           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15558         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15559       else
15560         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15561     }
15562 
15563     // Add known guaranteed alignment for allocation functions.
15564     switch (BuiltinID) {
15565     case Builtin::BImemalign:
15566     case Builtin::BIaligned_alloc:
15567       if (!FD->hasAttr<AllocAlignAttr>())
15568         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15569                                                    FD->getLocation()));
15570       break;
15571     default:
15572       break;
15573     }
15574 
15575     // Add allocsize attribute for allocation functions.
15576     switch (BuiltinID) {
15577     case Builtin::BIcalloc:
15578       FD->addAttr(AllocSizeAttr::CreateImplicit(
15579           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15580       break;
15581     case Builtin::BImemalign:
15582     case Builtin::BIaligned_alloc:
15583     case Builtin::BIrealloc:
15584       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15585                                                 ParamIdx(), FD->getLocation()));
15586       break;
15587     case Builtin::BImalloc:
15588       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15589                                                 ParamIdx(), FD->getLocation()));
15590       break;
15591     default:
15592       break;
15593     }
15594   }
15595 
15596   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15597 
15598   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15599   // throw, add an implicit nothrow attribute to any extern "C" function we come
15600   // across.
15601   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15602       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15603     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15604     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15605       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15606   }
15607 
15608   IdentifierInfo *Name = FD->getIdentifier();
15609   if (!Name)
15610     return;
15611   if ((!getLangOpts().CPlusPlus &&
15612        FD->getDeclContext()->isTranslationUnit()) ||
15613       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15614        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15615        LinkageSpecDecl::lang_c)) {
15616     // Okay: this could be a libc/libm/Objective-C function we know
15617     // about.
15618   } else
15619     return;
15620 
15621   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15622     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15623     // target-specific builtins, perhaps?
15624     if (!FD->hasAttr<FormatAttr>())
15625       FD->addAttr(FormatAttr::CreateImplicit(Context,
15626                                              &Context.Idents.get("printf"), 2,
15627                                              Name->isStr("vasprintf") ? 0 : 3,
15628                                              FD->getLocation()));
15629   }
15630 
15631   if (Name->isStr("__CFStringMakeConstantString")) {
15632     // We already have a __builtin___CFStringMakeConstantString,
15633     // but builds that use -fno-constant-cfstrings don't go through that.
15634     if (!FD->hasAttr<FormatArgAttr>())
15635       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15636                                                 FD->getLocation()));
15637   }
15638 }
15639 
15640 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15641                                     TypeSourceInfo *TInfo) {
15642   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15643   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15644 
15645   if (!TInfo) {
15646     assert(D.isInvalidType() && "no declarator info for valid type");
15647     TInfo = Context.getTrivialTypeSourceInfo(T);
15648   }
15649 
15650   // Scope manipulation handled by caller.
15651   TypedefDecl *NewTD =
15652       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15653                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15654 
15655   // Bail out immediately if we have an invalid declaration.
15656   if (D.isInvalidType()) {
15657     NewTD->setInvalidDecl();
15658     return NewTD;
15659   }
15660 
15661   if (D.getDeclSpec().isModulePrivateSpecified()) {
15662     if (CurContext->isFunctionOrMethod())
15663       Diag(NewTD->getLocation(), diag::err_module_private_local)
15664           << 2 << NewTD
15665           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15666           << FixItHint::CreateRemoval(
15667                  D.getDeclSpec().getModulePrivateSpecLoc());
15668     else
15669       NewTD->setModulePrivate();
15670   }
15671 
15672   // C++ [dcl.typedef]p8:
15673   //   If the typedef declaration defines an unnamed class (or
15674   //   enum), the first typedef-name declared by the declaration
15675   //   to be that class type (or enum type) is used to denote the
15676   //   class type (or enum type) for linkage purposes only.
15677   // We need to check whether the type was declared in the declaration.
15678   switch (D.getDeclSpec().getTypeSpecType()) {
15679   case TST_enum:
15680   case TST_struct:
15681   case TST_interface:
15682   case TST_union:
15683   case TST_class: {
15684     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15685     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15686     break;
15687   }
15688 
15689   default:
15690     break;
15691   }
15692 
15693   return NewTD;
15694 }
15695 
15696 /// Check that this is a valid underlying type for an enum declaration.
15697 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15698   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15699   QualType T = TI->getType();
15700 
15701   if (T->isDependentType())
15702     return false;
15703 
15704   // This doesn't use 'isIntegralType' despite the error message mentioning
15705   // integral type because isIntegralType would also allow enum types in C.
15706   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15707     if (BT->isInteger())
15708       return false;
15709 
15710   if (T->isBitIntType())
15711     return false;
15712 
15713   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15714 }
15715 
15716 /// Check whether this is a valid redeclaration of a previous enumeration.
15717 /// \return true if the redeclaration was invalid.
15718 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15719                                   QualType EnumUnderlyingTy, bool IsFixed,
15720                                   const EnumDecl *Prev) {
15721   if (IsScoped != Prev->isScoped()) {
15722     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15723       << Prev->isScoped();
15724     Diag(Prev->getLocation(), diag::note_previous_declaration);
15725     return true;
15726   }
15727 
15728   if (IsFixed && Prev->isFixed()) {
15729     if (!EnumUnderlyingTy->isDependentType() &&
15730         !Prev->getIntegerType()->isDependentType() &&
15731         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15732                                         Prev->getIntegerType())) {
15733       // TODO: Highlight the underlying type of the redeclaration.
15734       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15735         << EnumUnderlyingTy << Prev->getIntegerType();
15736       Diag(Prev->getLocation(), diag::note_previous_declaration)
15737           << Prev->getIntegerTypeRange();
15738       return true;
15739     }
15740   } else if (IsFixed != Prev->isFixed()) {
15741     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15742       << Prev->isFixed();
15743     Diag(Prev->getLocation(), diag::note_previous_declaration);
15744     return true;
15745   }
15746 
15747   return false;
15748 }
15749 
15750 /// Get diagnostic %select index for tag kind for
15751 /// redeclaration diagnostic message.
15752 /// WARNING: Indexes apply to particular diagnostics only!
15753 ///
15754 /// \returns diagnostic %select index.
15755 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15756   switch (Tag) {
15757   case TTK_Struct: return 0;
15758   case TTK_Interface: return 1;
15759   case TTK_Class:  return 2;
15760   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15761   }
15762 }
15763 
15764 /// Determine if tag kind is a class-key compatible with
15765 /// class for redeclaration (class, struct, or __interface).
15766 ///
15767 /// \returns true iff the tag kind is compatible.
15768 static bool isClassCompatTagKind(TagTypeKind Tag)
15769 {
15770   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15771 }
15772 
15773 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15774                                              TagTypeKind TTK) {
15775   if (isa<TypedefDecl>(PrevDecl))
15776     return NTK_Typedef;
15777   else if (isa<TypeAliasDecl>(PrevDecl))
15778     return NTK_TypeAlias;
15779   else if (isa<ClassTemplateDecl>(PrevDecl))
15780     return NTK_Template;
15781   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15782     return NTK_TypeAliasTemplate;
15783   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15784     return NTK_TemplateTemplateArgument;
15785   switch (TTK) {
15786   case TTK_Struct:
15787   case TTK_Interface:
15788   case TTK_Class:
15789     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15790   case TTK_Union:
15791     return NTK_NonUnion;
15792   case TTK_Enum:
15793     return NTK_NonEnum;
15794   }
15795   llvm_unreachable("invalid TTK");
15796 }
15797 
15798 /// Determine whether a tag with a given kind is acceptable
15799 /// as a redeclaration of the given tag declaration.
15800 ///
15801 /// \returns true if the new tag kind is acceptable, false otherwise.
15802 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15803                                         TagTypeKind NewTag, bool isDefinition,
15804                                         SourceLocation NewTagLoc,
15805                                         const IdentifierInfo *Name) {
15806   // C++ [dcl.type.elab]p3:
15807   //   The class-key or enum keyword present in the
15808   //   elaborated-type-specifier shall agree in kind with the
15809   //   declaration to which the name in the elaborated-type-specifier
15810   //   refers. This rule also applies to the form of
15811   //   elaborated-type-specifier that declares a class-name or
15812   //   friend class since it can be construed as referring to the
15813   //   definition of the class. Thus, in any
15814   //   elaborated-type-specifier, the enum keyword shall be used to
15815   //   refer to an enumeration (7.2), the union class-key shall be
15816   //   used to refer to a union (clause 9), and either the class or
15817   //   struct class-key shall be used to refer to a class (clause 9)
15818   //   declared using the class or struct class-key.
15819   TagTypeKind OldTag = Previous->getTagKind();
15820   if (OldTag != NewTag &&
15821       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15822     return false;
15823 
15824   // Tags are compatible, but we might still want to warn on mismatched tags.
15825   // Non-class tags can't be mismatched at this point.
15826   if (!isClassCompatTagKind(NewTag))
15827     return true;
15828 
15829   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15830   // by our warning analysis. We don't want to warn about mismatches with (eg)
15831   // declarations in system headers that are designed to be specialized, but if
15832   // a user asks us to warn, we should warn if their code contains mismatched
15833   // declarations.
15834   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15835     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15836                                       Loc);
15837   };
15838   if (IsIgnoredLoc(NewTagLoc))
15839     return true;
15840 
15841   auto IsIgnored = [&](const TagDecl *Tag) {
15842     return IsIgnoredLoc(Tag->getLocation());
15843   };
15844   while (IsIgnored(Previous)) {
15845     Previous = Previous->getPreviousDecl();
15846     if (!Previous)
15847       return true;
15848     OldTag = Previous->getTagKind();
15849   }
15850 
15851   bool isTemplate = false;
15852   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15853     isTemplate = Record->getDescribedClassTemplate();
15854 
15855   if (inTemplateInstantiation()) {
15856     if (OldTag != NewTag) {
15857       // In a template instantiation, do not offer fix-its for tag mismatches
15858       // since they usually mess up the template instead of fixing the problem.
15859       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15860         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15861         << getRedeclDiagFromTagKind(OldTag);
15862       // FIXME: Note previous location?
15863     }
15864     return true;
15865   }
15866 
15867   if (isDefinition) {
15868     // On definitions, check all previous tags and issue a fix-it for each
15869     // one that doesn't match the current tag.
15870     if (Previous->getDefinition()) {
15871       // Don't suggest fix-its for redefinitions.
15872       return true;
15873     }
15874 
15875     bool previousMismatch = false;
15876     for (const TagDecl *I : Previous->redecls()) {
15877       if (I->getTagKind() != NewTag) {
15878         // Ignore previous declarations for which the warning was disabled.
15879         if (IsIgnored(I))
15880           continue;
15881 
15882         if (!previousMismatch) {
15883           previousMismatch = true;
15884           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15885             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15886             << getRedeclDiagFromTagKind(I->getTagKind());
15887         }
15888         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15889           << getRedeclDiagFromTagKind(NewTag)
15890           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15891                TypeWithKeyword::getTagTypeKindName(NewTag));
15892       }
15893     }
15894     return true;
15895   }
15896 
15897   // Identify the prevailing tag kind: this is the kind of the definition (if
15898   // there is a non-ignored definition), or otherwise the kind of the prior
15899   // (non-ignored) declaration.
15900   const TagDecl *PrevDef = Previous->getDefinition();
15901   if (PrevDef && IsIgnored(PrevDef))
15902     PrevDef = nullptr;
15903   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15904   if (Redecl->getTagKind() != NewTag) {
15905     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15906       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15907       << getRedeclDiagFromTagKind(OldTag);
15908     Diag(Redecl->getLocation(), diag::note_previous_use);
15909 
15910     // If there is a previous definition, suggest a fix-it.
15911     if (PrevDef) {
15912       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15913         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15914         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15915              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15916     }
15917   }
15918 
15919   return true;
15920 }
15921 
15922 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15923 /// from an outer enclosing namespace or file scope inside a friend declaration.
15924 /// This should provide the commented out code in the following snippet:
15925 ///   namespace N {
15926 ///     struct X;
15927 ///     namespace M {
15928 ///       struct Y { friend struct /*N::*/ X; };
15929 ///     }
15930 ///   }
15931 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15932                                          SourceLocation NameLoc) {
15933   // While the decl is in a namespace, do repeated lookup of that name and see
15934   // if we get the same namespace back.  If we do not, continue until
15935   // translation unit scope, at which point we have a fully qualified NNS.
15936   SmallVector<IdentifierInfo *, 4> Namespaces;
15937   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15938   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15939     // This tag should be declared in a namespace, which can only be enclosed by
15940     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15941     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15942     if (!Namespace || Namespace->isAnonymousNamespace())
15943       return FixItHint();
15944     IdentifierInfo *II = Namespace->getIdentifier();
15945     Namespaces.push_back(II);
15946     NamedDecl *Lookup = SemaRef.LookupSingleName(
15947         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15948     if (Lookup == Namespace)
15949       break;
15950   }
15951 
15952   // Once we have all the namespaces, reverse them to go outermost first, and
15953   // build an NNS.
15954   SmallString<64> Insertion;
15955   llvm::raw_svector_ostream OS(Insertion);
15956   if (DC->isTranslationUnit())
15957     OS << "::";
15958   std::reverse(Namespaces.begin(), Namespaces.end());
15959   for (auto *II : Namespaces)
15960     OS << II->getName() << "::";
15961   return FixItHint::CreateInsertion(NameLoc, Insertion);
15962 }
15963 
15964 /// Determine whether a tag originally declared in context \p OldDC can
15965 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15966 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15967 /// using-declaration).
15968 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15969                                          DeclContext *NewDC) {
15970   OldDC = OldDC->getRedeclContext();
15971   NewDC = NewDC->getRedeclContext();
15972 
15973   if (OldDC->Equals(NewDC))
15974     return true;
15975 
15976   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15977   // encloses the other).
15978   if (S.getLangOpts().MSVCCompat &&
15979       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15980     return true;
15981 
15982   return false;
15983 }
15984 
15985 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15986 /// former case, Name will be non-null.  In the later case, Name will be null.
15987 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15988 /// reference/declaration/definition of a tag.
15989 ///
15990 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15991 /// trailing-type-specifier) other than one in an alias-declaration.
15992 ///
15993 /// \param SkipBody If non-null, will be set to indicate if the caller should
15994 /// skip the definition of this tag and treat it as if it were a declaration.
15995 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15996                      SourceLocation KWLoc, CXXScopeSpec &SS,
15997                      IdentifierInfo *Name, SourceLocation NameLoc,
15998                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15999                      SourceLocation ModulePrivateLoc,
16000                      MultiTemplateParamsArg TemplateParameterLists,
16001                      bool &OwnedDecl, bool &IsDependent,
16002                      SourceLocation ScopedEnumKWLoc,
16003                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16004                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16005                      SkipBodyInfo *SkipBody) {
16006   // If this is not a definition, it must have a name.
16007   IdentifierInfo *OrigName = Name;
16008   assert((Name != nullptr || TUK == TUK_Definition) &&
16009          "Nameless record must be a definition!");
16010   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16011 
16012   OwnedDecl = false;
16013   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16014   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16015 
16016   // FIXME: Check member specializations more carefully.
16017   bool isMemberSpecialization = false;
16018   bool Invalid = false;
16019 
16020   // We only need to do this matching if we have template parameters
16021   // or a scope specifier, which also conveniently avoids this work
16022   // for non-C++ cases.
16023   if (TemplateParameterLists.size() > 0 ||
16024       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16025     if (TemplateParameterList *TemplateParams =
16026             MatchTemplateParametersToScopeSpecifier(
16027                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16028                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16029       if (Kind == TTK_Enum) {
16030         Diag(KWLoc, diag::err_enum_template);
16031         return nullptr;
16032       }
16033 
16034       if (TemplateParams->size() > 0) {
16035         // This is a declaration or definition of a class template (which may
16036         // be a member of another template).
16037 
16038         if (Invalid)
16039           return nullptr;
16040 
16041         OwnedDecl = false;
16042         DeclResult Result = CheckClassTemplate(
16043             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16044             AS, ModulePrivateLoc,
16045             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16046             TemplateParameterLists.data(), SkipBody);
16047         return Result.get();
16048       } else {
16049         // The "template<>" header is extraneous.
16050         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16051           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16052         isMemberSpecialization = true;
16053       }
16054     }
16055 
16056     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16057         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16058       return nullptr;
16059   }
16060 
16061   // Figure out the underlying type if this a enum declaration. We need to do
16062   // this early, because it's needed to detect if this is an incompatible
16063   // redeclaration.
16064   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16065   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16066 
16067   if (Kind == TTK_Enum) {
16068     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16069       // No underlying type explicitly specified, or we failed to parse the
16070       // type, default to int.
16071       EnumUnderlying = Context.IntTy.getTypePtr();
16072     } else if (UnderlyingType.get()) {
16073       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16074       // integral type; any cv-qualification is ignored.
16075       TypeSourceInfo *TI = nullptr;
16076       GetTypeFromParser(UnderlyingType.get(), &TI);
16077       EnumUnderlying = TI;
16078 
16079       if (CheckEnumUnderlyingType(TI))
16080         // Recover by falling back to int.
16081         EnumUnderlying = Context.IntTy.getTypePtr();
16082 
16083       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16084                                           UPPC_FixedUnderlyingType))
16085         EnumUnderlying = Context.IntTy.getTypePtr();
16086 
16087     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16088       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16089       // of 'int'. However, if this is an unfixed forward declaration, don't set
16090       // the underlying type unless the user enables -fms-compatibility. This
16091       // makes unfixed forward declared enums incomplete and is more conforming.
16092       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16093         EnumUnderlying = Context.IntTy.getTypePtr();
16094     }
16095   }
16096 
16097   DeclContext *SearchDC = CurContext;
16098   DeclContext *DC = CurContext;
16099   bool isStdBadAlloc = false;
16100   bool isStdAlignValT = false;
16101 
16102   RedeclarationKind Redecl = forRedeclarationInCurContext();
16103   if (TUK == TUK_Friend || TUK == TUK_Reference)
16104     Redecl = NotForRedeclaration;
16105 
16106   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16107   /// implemented asks for structural equivalence checking, the returned decl
16108   /// here is passed back to the parser, allowing the tag body to be parsed.
16109   auto createTagFromNewDecl = [&]() -> TagDecl * {
16110     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16111     // If there is an identifier, use the location of the identifier as the
16112     // location of the decl, otherwise use the location of the struct/union
16113     // keyword.
16114     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16115     TagDecl *New = nullptr;
16116 
16117     if (Kind == TTK_Enum) {
16118       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16119                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16120       // If this is an undefined enum, bail.
16121       if (TUK != TUK_Definition && !Invalid)
16122         return nullptr;
16123       if (EnumUnderlying) {
16124         EnumDecl *ED = cast<EnumDecl>(New);
16125         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16126           ED->setIntegerTypeSourceInfo(TI);
16127         else
16128           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16129         ED->setPromotionType(ED->getIntegerType());
16130       }
16131     } else { // struct/union
16132       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16133                                nullptr);
16134     }
16135 
16136     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16137       // Add alignment attributes if necessary; these attributes are checked
16138       // when the ASTContext lays out the structure.
16139       //
16140       // It is important for implementing the correct semantics that this
16141       // happen here (in ActOnTag). The #pragma pack stack is
16142       // maintained as a result of parser callbacks which can occur at
16143       // many points during the parsing of a struct declaration (because
16144       // the #pragma tokens are effectively skipped over during the
16145       // parsing of the struct).
16146       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16147         AddAlignmentAttributesForRecord(RD);
16148         AddMsStructLayoutForRecord(RD);
16149       }
16150     }
16151     New->setLexicalDeclContext(CurContext);
16152     return New;
16153   };
16154 
16155   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16156   if (Name && SS.isNotEmpty()) {
16157     // We have a nested-name tag ('struct foo::bar').
16158 
16159     // Check for invalid 'foo::'.
16160     if (SS.isInvalid()) {
16161       Name = nullptr;
16162       goto CreateNewDecl;
16163     }
16164 
16165     // If this is a friend or a reference to a class in a dependent
16166     // context, don't try to make a decl for it.
16167     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16168       DC = computeDeclContext(SS, false);
16169       if (!DC) {
16170         IsDependent = true;
16171         return nullptr;
16172       }
16173     } else {
16174       DC = computeDeclContext(SS, true);
16175       if (!DC) {
16176         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16177           << SS.getRange();
16178         return nullptr;
16179       }
16180     }
16181 
16182     if (RequireCompleteDeclContext(SS, DC))
16183       return nullptr;
16184 
16185     SearchDC = DC;
16186     // Look-up name inside 'foo::'.
16187     LookupQualifiedName(Previous, DC);
16188 
16189     if (Previous.isAmbiguous())
16190       return nullptr;
16191 
16192     if (Previous.empty()) {
16193       // Name lookup did not find anything. However, if the
16194       // nested-name-specifier refers to the current instantiation,
16195       // and that current instantiation has any dependent base
16196       // classes, we might find something at instantiation time: treat
16197       // this as a dependent elaborated-type-specifier.
16198       // But this only makes any sense for reference-like lookups.
16199       if (Previous.wasNotFoundInCurrentInstantiation() &&
16200           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16201         IsDependent = true;
16202         return nullptr;
16203       }
16204 
16205       // A tag 'foo::bar' must already exist.
16206       Diag(NameLoc, diag::err_not_tag_in_scope)
16207         << Kind << Name << DC << SS.getRange();
16208       Name = nullptr;
16209       Invalid = true;
16210       goto CreateNewDecl;
16211     }
16212   } else if (Name) {
16213     // C++14 [class.mem]p14:
16214     //   If T is the name of a class, then each of the following shall have a
16215     //   name different from T:
16216     //    -- every member of class T that is itself a type
16217     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16218         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16219       return nullptr;
16220 
16221     // If this is a named struct, check to see if there was a previous forward
16222     // declaration or definition.
16223     // FIXME: We're looking into outer scopes here, even when we
16224     // shouldn't be. Doing so can result in ambiguities that we
16225     // shouldn't be diagnosing.
16226     LookupName(Previous, S);
16227 
16228     // When declaring or defining a tag, ignore ambiguities introduced
16229     // by types using'ed into this scope.
16230     if (Previous.isAmbiguous() &&
16231         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16232       LookupResult::Filter F = Previous.makeFilter();
16233       while (F.hasNext()) {
16234         NamedDecl *ND = F.next();
16235         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16236                 SearchDC->getRedeclContext()))
16237           F.erase();
16238       }
16239       F.done();
16240     }
16241 
16242     // C++11 [namespace.memdef]p3:
16243     //   If the name in a friend declaration is neither qualified nor
16244     //   a template-id and the declaration is a function or an
16245     //   elaborated-type-specifier, the lookup to determine whether
16246     //   the entity has been previously declared shall not consider
16247     //   any scopes outside the innermost enclosing namespace.
16248     //
16249     // MSVC doesn't implement the above rule for types, so a friend tag
16250     // declaration may be a redeclaration of a type declared in an enclosing
16251     // scope.  They do implement this rule for friend functions.
16252     //
16253     // Does it matter that this should be by scope instead of by
16254     // semantic context?
16255     if (!Previous.empty() && TUK == TUK_Friend) {
16256       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16257       LookupResult::Filter F = Previous.makeFilter();
16258       bool FriendSawTagOutsideEnclosingNamespace = false;
16259       while (F.hasNext()) {
16260         NamedDecl *ND = F.next();
16261         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16262         if (DC->isFileContext() &&
16263             !EnclosingNS->Encloses(ND->getDeclContext())) {
16264           if (getLangOpts().MSVCCompat)
16265             FriendSawTagOutsideEnclosingNamespace = true;
16266           else
16267             F.erase();
16268         }
16269       }
16270       F.done();
16271 
16272       // Diagnose this MSVC extension in the easy case where lookup would have
16273       // unambiguously found something outside the enclosing namespace.
16274       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16275         NamedDecl *ND = Previous.getFoundDecl();
16276         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16277             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16278       }
16279     }
16280 
16281     // Note:  there used to be some attempt at recovery here.
16282     if (Previous.isAmbiguous())
16283       return nullptr;
16284 
16285     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16286       // FIXME: This makes sure that we ignore the contexts associated
16287       // with C structs, unions, and enums when looking for a matching
16288       // tag declaration or definition. See the similar lookup tweak
16289       // in Sema::LookupName; is there a better way to deal with this?
16290       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16291         SearchDC = SearchDC->getParent();
16292     } else if (getLangOpts().CPlusPlus) {
16293       // Inside ObjCContainer want to keep it as a lexical decl context but go
16294       // past it (most often to TranslationUnit) to find the semantic decl
16295       // context.
16296       while (isa<ObjCContainerDecl>(SearchDC))
16297         SearchDC = SearchDC->getParent();
16298     }
16299   } else if (getLangOpts().CPlusPlus) {
16300     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16301     // TagDecl the same way as we skip it for named TagDecl.
16302     while (isa<ObjCContainerDecl>(SearchDC))
16303       SearchDC = SearchDC->getParent();
16304   }
16305 
16306   if (Previous.isSingleResult() &&
16307       Previous.getFoundDecl()->isTemplateParameter()) {
16308     // Maybe we will complain about the shadowed template parameter.
16309     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16310     // Just pretend that we didn't see the previous declaration.
16311     Previous.clear();
16312   }
16313 
16314   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16315       DC->Equals(getStdNamespace())) {
16316     if (Name->isStr("bad_alloc")) {
16317       // This is a declaration of or a reference to "std::bad_alloc".
16318       isStdBadAlloc = true;
16319 
16320       // If std::bad_alloc has been implicitly declared (but made invisible to
16321       // name lookup), fill in this implicit declaration as the previous
16322       // declaration, so that the declarations get chained appropriately.
16323       if (Previous.empty() && StdBadAlloc)
16324         Previous.addDecl(getStdBadAlloc());
16325     } else if (Name->isStr("align_val_t")) {
16326       isStdAlignValT = true;
16327       if (Previous.empty() && StdAlignValT)
16328         Previous.addDecl(getStdAlignValT());
16329     }
16330   }
16331 
16332   // If we didn't find a previous declaration, and this is a reference
16333   // (or friend reference), move to the correct scope.  In C++, we
16334   // also need to do a redeclaration lookup there, just in case
16335   // there's a shadow friend decl.
16336   if (Name && Previous.empty() &&
16337       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16338     if (Invalid) goto CreateNewDecl;
16339     assert(SS.isEmpty());
16340 
16341     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16342       // C++ [basic.scope.pdecl]p5:
16343       //   -- for an elaborated-type-specifier of the form
16344       //
16345       //          class-key identifier
16346       //
16347       //      if the elaborated-type-specifier is used in the
16348       //      decl-specifier-seq or parameter-declaration-clause of a
16349       //      function defined in namespace scope, the identifier is
16350       //      declared as a class-name in the namespace that contains
16351       //      the declaration; otherwise, except as a friend
16352       //      declaration, the identifier is declared in the smallest
16353       //      non-class, non-function-prototype scope that contains the
16354       //      declaration.
16355       //
16356       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16357       // C structs and unions.
16358       //
16359       // It is an error in C++ to declare (rather than define) an enum
16360       // type, including via an elaborated type specifier.  We'll
16361       // diagnose that later; for now, declare the enum in the same
16362       // scope as we would have picked for any other tag type.
16363       //
16364       // GNU C also supports this behavior as part of its incomplete
16365       // enum types extension, while GNU C++ does not.
16366       //
16367       // Find the context where we'll be declaring the tag.
16368       // FIXME: We would like to maintain the current DeclContext as the
16369       // lexical context,
16370       SearchDC = getTagInjectionContext(SearchDC);
16371 
16372       // Find the scope where we'll be declaring the tag.
16373       S = getTagInjectionScope(S, getLangOpts());
16374     } else {
16375       assert(TUK == TUK_Friend);
16376       // C++ [namespace.memdef]p3:
16377       //   If a friend declaration in a non-local class first declares a
16378       //   class or function, the friend class or function is a member of
16379       //   the innermost enclosing namespace.
16380       SearchDC = SearchDC->getEnclosingNamespaceContext();
16381     }
16382 
16383     // In C++, we need to do a redeclaration lookup to properly
16384     // diagnose some problems.
16385     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16386     // hidden declaration so that we don't get ambiguity errors when using a
16387     // type declared by an elaborated-type-specifier.  In C that is not correct
16388     // and we should instead merge compatible types found by lookup.
16389     if (getLangOpts().CPlusPlus) {
16390       // FIXME: This can perform qualified lookups into function contexts,
16391       // which are meaningless.
16392       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16393       LookupQualifiedName(Previous, SearchDC);
16394     } else {
16395       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16396       LookupName(Previous, S);
16397     }
16398   }
16399 
16400   // If we have a known previous declaration to use, then use it.
16401   if (Previous.empty() && SkipBody && SkipBody->Previous)
16402     Previous.addDecl(SkipBody->Previous);
16403 
16404   if (!Previous.empty()) {
16405     NamedDecl *PrevDecl = Previous.getFoundDecl();
16406     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16407 
16408     // It's okay to have a tag decl in the same scope as a typedef
16409     // which hides a tag decl in the same scope.  Finding this
16410     // with a redeclaration lookup can only actually happen in C++.
16411     //
16412     // This is also okay for elaborated-type-specifiers, which is
16413     // technically forbidden by the current standard but which is
16414     // okay according to the likely resolution of an open issue;
16415     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16416     if (getLangOpts().CPlusPlus) {
16417       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16418         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16419           TagDecl *Tag = TT->getDecl();
16420           if (Tag->getDeclName() == Name &&
16421               Tag->getDeclContext()->getRedeclContext()
16422                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16423             PrevDecl = Tag;
16424             Previous.clear();
16425             Previous.addDecl(Tag);
16426             Previous.resolveKind();
16427           }
16428         }
16429       }
16430     }
16431 
16432     // If this is a redeclaration of a using shadow declaration, it must
16433     // declare a tag in the same context. In MSVC mode, we allow a
16434     // redefinition if either context is within the other.
16435     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16436       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16437       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16438           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16439           !(OldTag && isAcceptableTagRedeclContext(
16440                           *this, OldTag->getDeclContext(), SearchDC))) {
16441         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16442         Diag(Shadow->getTargetDecl()->getLocation(),
16443              diag::note_using_decl_target);
16444         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16445             << 0;
16446         // Recover by ignoring the old declaration.
16447         Previous.clear();
16448         goto CreateNewDecl;
16449       }
16450     }
16451 
16452     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16453       // If this is a use of a previous tag, or if the tag is already declared
16454       // in the same scope (so that the definition/declaration completes or
16455       // rementions the tag), reuse the decl.
16456       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16457           isDeclInScope(DirectPrevDecl, SearchDC, S,
16458                         SS.isNotEmpty() || isMemberSpecialization)) {
16459         // Make sure that this wasn't declared as an enum and now used as a
16460         // struct or something similar.
16461         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16462                                           TUK == TUK_Definition, KWLoc,
16463                                           Name)) {
16464           bool SafeToContinue
16465             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16466                Kind != TTK_Enum);
16467           if (SafeToContinue)
16468             Diag(KWLoc, diag::err_use_with_wrong_tag)
16469               << Name
16470               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16471                                               PrevTagDecl->getKindName());
16472           else
16473             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16474           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16475 
16476           if (SafeToContinue)
16477             Kind = PrevTagDecl->getTagKind();
16478           else {
16479             // Recover by making this an anonymous redefinition.
16480             Name = nullptr;
16481             Previous.clear();
16482             Invalid = true;
16483           }
16484         }
16485 
16486         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16487           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16488           if (TUK == TUK_Reference || TUK == TUK_Friend)
16489             return PrevTagDecl;
16490 
16491           QualType EnumUnderlyingTy;
16492           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16493             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16494           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16495             EnumUnderlyingTy = QualType(T, 0);
16496 
16497           // All conflicts with previous declarations are recovered by
16498           // returning the previous declaration, unless this is a definition,
16499           // in which case we want the caller to bail out.
16500           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16501                                      ScopedEnum, EnumUnderlyingTy,
16502                                      IsFixed, PrevEnum))
16503             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16504         }
16505 
16506         // C++11 [class.mem]p1:
16507         //   A member shall not be declared twice in the member-specification,
16508         //   except that a nested class or member class template can be declared
16509         //   and then later defined.
16510         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16511             S->isDeclScope(PrevDecl)) {
16512           Diag(NameLoc, diag::ext_member_redeclared);
16513           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16514         }
16515 
16516         if (!Invalid) {
16517           // If this is a use, just return the declaration we found, unless
16518           // we have attributes.
16519           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16520             if (!Attrs.empty()) {
16521               // FIXME: Diagnose these attributes. For now, we create a new
16522               // declaration to hold them.
16523             } else if (TUK == TUK_Reference &&
16524                        (PrevTagDecl->getFriendObjectKind() ==
16525                             Decl::FOK_Undeclared ||
16526                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16527                        SS.isEmpty()) {
16528               // This declaration is a reference to an existing entity, but
16529               // has different visibility from that entity: it either makes
16530               // a friend visible or it makes a type visible in a new module.
16531               // In either case, create a new declaration. We only do this if
16532               // the declaration would have meant the same thing if no prior
16533               // declaration were found, that is, if it was found in the same
16534               // scope where we would have injected a declaration.
16535               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16536                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16537                 return PrevTagDecl;
16538               // This is in the injected scope, create a new declaration in
16539               // that scope.
16540               S = getTagInjectionScope(S, getLangOpts());
16541             } else {
16542               return PrevTagDecl;
16543             }
16544           }
16545 
16546           // Diagnose attempts to redefine a tag.
16547           if (TUK == TUK_Definition) {
16548             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16549               // If we're defining a specialization and the previous definition
16550               // is from an implicit instantiation, don't emit an error
16551               // here; we'll catch this in the general case below.
16552               bool IsExplicitSpecializationAfterInstantiation = false;
16553               if (isMemberSpecialization) {
16554                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16555                   IsExplicitSpecializationAfterInstantiation =
16556                     RD->getTemplateSpecializationKind() !=
16557                     TSK_ExplicitSpecialization;
16558                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16559                   IsExplicitSpecializationAfterInstantiation =
16560                     ED->getTemplateSpecializationKind() !=
16561                     TSK_ExplicitSpecialization;
16562               }
16563 
16564               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16565               // not keep more that one definition around (merge them). However,
16566               // ensure the decl passes the structural compatibility check in
16567               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16568               NamedDecl *Hidden = nullptr;
16569               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16570                 // There is a definition of this tag, but it is not visible. We
16571                 // explicitly make use of C++'s one definition rule here, and
16572                 // assume that this definition is identical to the hidden one
16573                 // we already have. Make the existing definition visible and
16574                 // use it in place of this one.
16575                 if (!getLangOpts().CPlusPlus) {
16576                   // Postpone making the old definition visible until after we
16577                   // complete parsing the new one and do the structural
16578                   // comparison.
16579                   SkipBody->CheckSameAsPrevious = true;
16580                   SkipBody->New = createTagFromNewDecl();
16581                   SkipBody->Previous = Def;
16582                   return Def;
16583                 } else {
16584                   SkipBody->ShouldSkip = true;
16585                   SkipBody->Previous = Def;
16586                   makeMergedDefinitionVisible(Hidden);
16587                   // Carry on and handle it like a normal definition. We'll
16588                   // skip starting the definitiion later.
16589                 }
16590               } else if (!IsExplicitSpecializationAfterInstantiation) {
16591                 // A redeclaration in function prototype scope in C isn't
16592                 // visible elsewhere, so merely issue a warning.
16593                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16594                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16595                 else
16596                   Diag(NameLoc, diag::err_redefinition) << Name;
16597                 notePreviousDefinition(Def,
16598                                        NameLoc.isValid() ? NameLoc : KWLoc);
16599                 // If this is a redefinition, recover by making this
16600                 // struct be anonymous, which will make any later
16601                 // references get the previous definition.
16602                 Name = nullptr;
16603                 Previous.clear();
16604                 Invalid = true;
16605               }
16606             } else {
16607               // If the type is currently being defined, complain
16608               // about a nested redefinition.
16609               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16610               if (TD->isBeingDefined()) {
16611                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16612                 Diag(PrevTagDecl->getLocation(),
16613                      diag::note_previous_definition);
16614                 Name = nullptr;
16615                 Previous.clear();
16616                 Invalid = true;
16617               }
16618             }
16619 
16620             // Okay, this is definition of a previously declared or referenced
16621             // tag. We're going to create a new Decl for it.
16622           }
16623 
16624           // Okay, we're going to make a redeclaration.  If this is some kind
16625           // of reference, make sure we build the redeclaration in the same DC
16626           // as the original, and ignore the current access specifier.
16627           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16628             SearchDC = PrevTagDecl->getDeclContext();
16629             AS = AS_none;
16630           }
16631         }
16632         // If we get here we have (another) forward declaration or we
16633         // have a definition.  Just create a new decl.
16634 
16635       } else {
16636         // If we get here, this is a definition of a new tag type in a nested
16637         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16638         // new decl/type.  We set PrevDecl to NULL so that the entities
16639         // have distinct types.
16640         Previous.clear();
16641       }
16642       // If we get here, we're going to create a new Decl. If PrevDecl
16643       // is non-NULL, it's a definition of the tag declared by
16644       // PrevDecl. If it's NULL, we have a new definition.
16645 
16646     // Otherwise, PrevDecl is not a tag, but was found with tag
16647     // lookup.  This is only actually possible in C++, where a few
16648     // things like templates still live in the tag namespace.
16649     } else {
16650       // Use a better diagnostic if an elaborated-type-specifier
16651       // found the wrong kind of type on the first
16652       // (non-redeclaration) lookup.
16653       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16654           !Previous.isForRedeclaration()) {
16655         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16656         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16657                                                        << Kind;
16658         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16659         Invalid = true;
16660 
16661       // Otherwise, only diagnose if the declaration is in scope.
16662       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16663                                 SS.isNotEmpty() || isMemberSpecialization)) {
16664         // do nothing
16665 
16666       // Diagnose implicit declarations introduced by elaborated types.
16667       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16668         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16669         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16670         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16671         Invalid = true;
16672 
16673       // Otherwise it's a declaration.  Call out a particularly common
16674       // case here.
16675       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16676         unsigned Kind = 0;
16677         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16678         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16679           << Name << Kind << TND->getUnderlyingType();
16680         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16681         Invalid = true;
16682 
16683       // Otherwise, diagnose.
16684       } else {
16685         // The tag name clashes with something else in the target scope,
16686         // issue an error and recover by making this tag be anonymous.
16687         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16688         notePreviousDefinition(PrevDecl, NameLoc);
16689         Name = nullptr;
16690         Invalid = true;
16691       }
16692 
16693       // The existing declaration isn't relevant to us; we're in a
16694       // new scope, so clear out the previous declaration.
16695       Previous.clear();
16696     }
16697   }
16698 
16699 CreateNewDecl:
16700 
16701   TagDecl *PrevDecl = nullptr;
16702   if (Previous.isSingleResult())
16703     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16704 
16705   // If there is an identifier, use the location of the identifier as the
16706   // location of the decl, otherwise use the location of the struct/union
16707   // keyword.
16708   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16709 
16710   // Otherwise, create a new declaration. If there is a previous
16711   // declaration of the same entity, the two will be linked via
16712   // PrevDecl.
16713   TagDecl *New;
16714 
16715   if (Kind == TTK_Enum) {
16716     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16717     // enum X { A, B, C } D;    D should chain to X.
16718     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16719                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16720                            ScopedEnumUsesClassTag, IsFixed);
16721 
16722     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16723       StdAlignValT = cast<EnumDecl>(New);
16724 
16725     // If this is an undefined enum, warn.
16726     if (TUK != TUK_Definition && !Invalid) {
16727       TagDecl *Def;
16728       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16729         // C++0x: 7.2p2: opaque-enum-declaration.
16730         // Conflicts are diagnosed above. Do nothing.
16731       }
16732       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16733         Diag(Loc, diag::ext_forward_ref_enum_def)
16734           << New;
16735         Diag(Def->getLocation(), diag::note_previous_definition);
16736       } else {
16737         unsigned DiagID = diag::ext_forward_ref_enum;
16738         if (getLangOpts().MSVCCompat)
16739           DiagID = diag::ext_ms_forward_ref_enum;
16740         else if (getLangOpts().CPlusPlus)
16741           DiagID = diag::err_forward_ref_enum;
16742         Diag(Loc, DiagID);
16743       }
16744     }
16745 
16746     if (EnumUnderlying) {
16747       EnumDecl *ED = cast<EnumDecl>(New);
16748       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16749         ED->setIntegerTypeSourceInfo(TI);
16750       else
16751         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16752       ED->setPromotionType(ED->getIntegerType());
16753       assert(ED->isComplete() && "enum with type should be complete");
16754     }
16755   } else {
16756     // struct/union/class
16757 
16758     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16759     // struct X { int A; } D;    D should chain to X.
16760     if (getLangOpts().CPlusPlus) {
16761       // FIXME: Look for a way to use RecordDecl for simple structs.
16762       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16763                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16764 
16765       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16766         StdBadAlloc = cast<CXXRecordDecl>(New);
16767     } else
16768       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16769                                cast_or_null<RecordDecl>(PrevDecl));
16770   }
16771 
16772   // C++11 [dcl.type]p3:
16773   //   A type-specifier-seq shall not define a class or enumeration [...].
16774   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16775       TUK == TUK_Definition) {
16776     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16777       << Context.getTagDeclType(New);
16778     Invalid = true;
16779   }
16780 
16781   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16782       DC->getDeclKind() == Decl::Enum) {
16783     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16784       << Context.getTagDeclType(New);
16785     Invalid = true;
16786   }
16787 
16788   // Maybe add qualifier info.
16789   if (SS.isNotEmpty()) {
16790     if (SS.isSet()) {
16791       // If this is either a declaration or a definition, check the
16792       // nested-name-specifier against the current context.
16793       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16794           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16795                                        isMemberSpecialization))
16796         Invalid = true;
16797 
16798       New->setQualifierInfo(SS.getWithLocInContext(Context));
16799       if (TemplateParameterLists.size() > 0) {
16800         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16801       }
16802     }
16803     else
16804       Invalid = true;
16805   }
16806 
16807   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16808     // Add alignment attributes if necessary; these attributes are checked when
16809     // the ASTContext lays out the structure.
16810     //
16811     // It is important for implementing the correct semantics that this
16812     // happen here (in ActOnTag). The #pragma pack stack is
16813     // maintained as a result of parser callbacks which can occur at
16814     // many points during the parsing of a struct declaration (because
16815     // the #pragma tokens are effectively skipped over during the
16816     // parsing of the struct).
16817     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16818       AddAlignmentAttributesForRecord(RD);
16819       AddMsStructLayoutForRecord(RD);
16820     }
16821   }
16822 
16823   if (ModulePrivateLoc.isValid()) {
16824     if (isMemberSpecialization)
16825       Diag(New->getLocation(), diag::err_module_private_specialization)
16826         << 2
16827         << FixItHint::CreateRemoval(ModulePrivateLoc);
16828     // __module_private__ does not apply to local classes. However, we only
16829     // diagnose this as an error when the declaration specifiers are
16830     // freestanding. Here, we just ignore the __module_private__.
16831     else if (!SearchDC->isFunctionOrMethod())
16832       New->setModulePrivate();
16833   }
16834 
16835   // If this is a specialization of a member class (of a class template),
16836   // check the specialization.
16837   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16838     Invalid = true;
16839 
16840   // If we're declaring or defining a tag in function prototype scope in C,
16841   // note that this type can only be used within the function and add it to
16842   // the list of decls to inject into the function definition scope.
16843   if ((Name || Kind == TTK_Enum) &&
16844       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16845     if (getLangOpts().CPlusPlus) {
16846       // C++ [dcl.fct]p6:
16847       //   Types shall not be defined in return or parameter types.
16848       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16849         Diag(Loc, diag::err_type_defined_in_param_type)
16850             << Name;
16851         Invalid = true;
16852       }
16853     } else if (!PrevDecl) {
16854       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16855     }
16856   }
16857 
16858   if (Invalid)
16859     New->setInvalidDecl();
16860 
16861   // Set the lexical context. If the tag has a C++ scope specifier, the
16862   // lexical context will be different from the semantic context.
16863   New->setLexicalDeclContext(CurContext);
16864 
16865   // Mark this as a friend decl if applicable.
16866   // In Microsoft mode, a friend declaration also acts as a forward
16867   // declaration so we always pass true to setObjectOfFriendDecl to make
16868   // the tag name visible.
16869   if (TUK == TUK_Friend)
16870     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16871 
16872   // Set the access specifier.
16873   if (!Invalid && SearchDC->isRecord())
16874     SetMemberAccessSpecifier(New, PrevDecl, AS);
16875 
16876   if (PrevDecl)
16877     CheckRedeclarationInModule(New, PrevDecl);
16878 
16879   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16880     New->startDefinition();
16881 
16882   ProcessDeclAttributeList(S, New, Attrs);
16883   AddPragmaAttributes(S, New);
16884 
16885   // If this has an identifier, add it to the scope stack.
16886   if (TUK == TUK_Friend) {
16887     // We might be replacing an existing declaration in the lookup tables;
16888     // if so, borrow its access specifier.
16889     if (PrevDecl)
16890       New->setAccess(PrevDecl->getAccess());
16891 
16892     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16893     DC->makeDeclVisibleInContext(New);
16894     if (Name) // can be null along some error paths
16895       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16896         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16897   } else if (Name) {
16898     S = getNonFieldDeclScope(S);
16899     PushOnScopeChains(New, S, true);
16900   } else {
16901     CurContext->addDecl(New);
16902   }
16903 
16904   // If this is the C FILE type, notify the AST context.
16905   if (IdentifierInfo *II = New->getIdentifier())
16906     if (!New->isInvalidDecl() &&
16907         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16908         II->isStr("FILE"))
16909       Context.setFILEDecl(New);
16910 
16911   if (PrevDecl)
16912     mergeDeclAttributes(New, PrevDecl);
16913 
16914   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16915     inferGslOwnerPointerAttribute(CXXRD);
16916 
16917   // If there's a #pragma GCC visibility in scope, set the visibility of this
16918   // record.
16919   AddPushedVisibilityAttribute(New);
16920 
16921   if (isMemberSpecialization && !New->isInvalidDecl())
16922     CompleteMemberSpecialization(New, Previous);
16923 
16924   OwnedDecl = true;
16925   // In C++, don't return an invalid declaration. We can't recover well from
16926   // the cases where we make the type anonymous.
16927   if (Invalid && getLangOpts().CPlusPlus) {
16928     if (New->isBeingDefined())
16929       if (auto RD = dyn_cast<RecordDecl>(New))
16930         RD->completeDefinition();
16931     return nullptr;
16932   } else if (SkipBody && SkipBody->ShouldSkip) {
16933     return SkipBody->Previous;
16934   } else {
16935     return New;
16936   }
16937 }
16938 
16939 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16940   AdjustDeclIfTemplate(TagD);
16941   TagDecl *Tag = cast<TagDecl>(TagD);
16942 
16943   // Enter the tag context.
16944   PushDeclContext(S, Tag);
16945 
16946   ActOnDocumentableDecl(TagD);
16947 
16948   // If there's a #pragma GCC visibility in scope, set the visibility of this
16949   // record.
16950   AddPushedVisibilityAttribute(Tag);
16951 }
16952 
16953 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
16954   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16955     return false;
16956 
16957   // Make the previous decl visible.
16958   makeMergedDefinitionVisible(SkipBody.Previous);
16959   return true;
16960 }
16961 
16962 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
16963   assert(IDecl->getLexicalParent() == CurContext &&
16964       "The next DeclContext should be lexically contained in the current one.");
16965   CurContext = IDecl;
16966 }
16967 
16968 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16969                                            SourceLocation FinalLoc,
16970                                            bool IsFinalSpelledSealed,
16971                                            bool IsAbstract,
16972                                            SourceLocation LBraceLoc) {
16973   AdjustDeclIfTemplate(TagD);
16974   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16975 
16976   FieldCollector->StartClass();
16977 
16978   if (!Record->getIdentifier())
16979     return;
16980 
16981   if (IsAbstract)
16982     Record->markAbstract();
16983 
16984   if (FinalLoc.isValid()) {
16985     Record->addAttr(FinalAttr::Create(
16986         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16987         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16988   }
16989   // C++ [class]p2:
16990   //   [...] The class-name is also inserted into the scope of the
16991   //   class itself; this is known as the injected-class-name. For
16992   //   purposes of access checking, the injected-class-name is treated
16993   //   as if it were a public member name.
16994   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16995       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16996       Record->getLocation(), Record->getIdentifier(),
16997       /*PrevDecl=*/nullptr,
16998       /*DelayTypeCreation=*/true);
16999   Context.getTypeDeclType(InjectedClassName, Record);
17000   InjectedClassName->setImplicit();
17001   InjectedClassName->setAccess(AS_public);
17002   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17003       InjectedClassName->setDescribedClassTemplate(Template);
17004   PushOnScopeChains(InjectedClassName, S);
17005   assert(InjectedClassName->isInjectedClassName() &&
17006          "Broken injected-class-name");
17007 }
17008 
17009 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17010                                     SourceRange BraceRange) {
17011   AdjustDeclIfTemplate(TagD);
17012   TagDecl *Tag = cast<TagDecl>(TagD);
17013   Tag->setBraceRange(BraceRange);
17014 
17015   // Make sure we "complete" the definition even it is invalid.
17016   if (Tag->isBeingDefined()) {
17017     assert(Tag->isInvalidDecl() && "We should already have completed it");
17018     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17019       RD->completeDefinition();
17020   }
17021 
17022   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17023     FieldCollector->FinishClass();
17024     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17025       auto *Def = RD->getDefinition();
17026       assert(Def && "The record is expected to have a completed definition");
17027       unsigned NumInitMethods = 0;
17028       for (auto *Method : Def->methods()) {
17029         if (!Method->getIdentifier())
17030             continue;
17031         if (Method->getName() == "__init")
17032           NumInitMethods++;
17033       }
17034       if (NumInitMethods > 1 || !Def->hasInitMethod())
17035         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17036     }
17037   }
17038 
17039   // Exit this scope of this tag's definition.
17040   PopDeclContext();
17041 
17042   if (getCurLexicalContext()->isObjCContainer() &&
17043       Tag->getDeclContext()->isFileContext())
17044     Tag->setTopLevelDeclInObjCContainer();
17045 
17046   // Notify the consumer that we've defined a tag.
17047   if (!Tag->isInvalidDecl())
17048     Consumer.HandleTagDeclDefinition(Tag);
17049 
17050   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17051   // from XLs and instead matches the XL #pragma pack(1) behavior.
17052   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17053       AlignPackStack.hasValue()) {
17054     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17055     // Only diagnose #pragma align(packed).
17056     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17057       return;
17058     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17059     if (!RD)
17060       return;
17061     // Only warn if there is at least 1 bitfield member.
17062     if (llvm::any_of(RD->fields(),
17063                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17064       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17065   }
17066 }
17067 
17068 void Sema::ActOnObjCContainerFinishDefinition() {
17069   // Exit this scope of this interface definition.
17070   PopDeclContext();
17071 }
17072 
17073 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17074   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17075   OriginalLexicalContext = ObjCCtx;
17076   ActOnObjCContainerFinishDefinition();
17077 }
17078 
17079 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17080   ActOnObjCContainerStartDefinition(ObjCCtx);
17081   OriginalLexicalContext = nullptr;
17082 }
17083 
17084 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17085   AdjustDeclIfTemplate(TagD);
17086   TagDecl *Tag = cast<TagDecl>(TagD);
17087   Tag->setInvalidDecl();
17088 
17089   // Make sure we "complete" the definition even it is invalid.
17090   if (Tag->isBeingDefined()) {
17091     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17092       RD->completeDefinition();
17093   }
17094 
17095   // We're undoing ActOnTagStartDefinition here, not
17096   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17097   // the FieldCollector.
17098 
17099   PopDeclContext();
17100 }
17101 
17102 // Note that FieldName may be null for anonymous bitfields.
17103 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17104                                 IdentifierInfo *FieldName, QualType FieldTy,
17105                                 bool IsMsStruct, Expr *BitWidth) {
17106   assert(BitWidth);
17107   if (BitWidth->containsErrors())
17108     return ExprError();
17109 
17110   // C99 6.7.2.1p4 - verify the field type.
17111   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17112   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17113     // Handle incomplete and sizeless types with a specific error.
17114     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17115                                  diag::err_field_incomplete_or_sizeless))
17116       return ExprError();
17117     if (FieldName)
17118       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17119         << FieldName << FieldTy << BitWidth->getSourceRange();
17120     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17121       << FieldTy << BitWidth->getSourceRange();
17122   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17123                                              UPPC_BitFieldWidth))
17124     return ExprError();
17125 
17126   // If the bit-width is type- or value-dependent, don't try to check
17127   // it now.
17128   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17129     return BitWidth;
17130 
17131   llvm::APSInt Value;
17132   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17133   if (ICE.isInvalid())
17134     return ICE;
17135   BitWidth = ICE.get();
17136 
17137   // Zero-width bitfield is ok for anonymous field.
17138   if (Value == 0 && FieldName)
17139     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17140 
17141   if (Value.isSigned() && Value.isNegative()) {
17142     if (FieldName)
17143       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17144                << FieldName << toString(Value, 10);
17145     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17146       << toString(Value, 10);
17147   }
17148 
17149   // The size of the bit-field must not exceed our maximum permitted object
17150   // size.
17151   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17152     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17153            << !FieldName << FieldName << toString(Value, 10);
17154   }
17155 
17156   if (!FieldTy->isDependentType()) {
17157     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17158     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17159     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17160 
17161     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17162     // ABI.
17163     bool CStdConstraintViolation =
17164         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17165     bool MSBitfieldViolation =
17166         Value.ugt(TypeStorageSize) &&
17167         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17168     if (CStdConstraintViolation || MSBitfieldViolation) {
17169       unsigned DiagWidth =
17170           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17171       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17172              << (bool)FieldName << FieldName << toString(Value, 10)
17173              << !CStdConstraintViolation << DiagWidth;
17174     }
17175 
17176     // Warn on types where the user might conceivably expect to get all
17177     // specified bits as value bits: that's all integral types other than
17178     // 'bool'.
17179     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17180       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17181           << FieldName << toString(Value, 10)
17182           << (unsigned)TypeWidth;
17183     }
17184   }
17185 
17186   return BitWidth;
17187 }
17188 
17189 /// ActOnField - Each field of a C struct/union is passed into this in order
17190 /// to create a FieldDecl object for it.
17191 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17192                        Declarator &D, Expr *BitfieldWidth) {
17193   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17194                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17195                                /*InitStyle=*/ICIS_NoInit, AS_public);
17196   return Res;
17197 }
17198 
17199 /// HandleField - Analyze a field of a C struct or a C++ data member.
17200 ///
17201 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17202                              SourceLocation DeclStart,
17203                              Declarator &D, Expr *BitWidth,
17204                              InClassInitStyle InitStyle,
17205                              AccessSpecifier AS) {
17206   if (D.isDecompositionDeclarator()) {
17207     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17208     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17209       << Decomp.getSourceRange();
17210     return nullptr;
17211   }
17212 
17213   IdentifierInfo *II = D.getIdentifier();
17214   SourceLocation Loc = DeclStart;
17215   if (II) Loc = D.getIdentifierLoc();
17216 
17217   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17218   QualType T = TInfo->getType();
17219   if (getLangOpts().CPlusPlus) {
17220     CheckExtraCXXDefaultArguments(D);
17221 
17222     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17223                                         UPPC_DataMemberType)) {
17224       D.setInvalidType();
17225       T = Context.IntTy;
17226       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17227     }
17228   }
17229 
17230   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17231 
17232   if (D.getDeclSpec().isInlineSpecified())
17233     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17234         << getLangOpts().CPlusPlus17;
17235   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17236     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17237          diag::err_invalid_thread)
17238       << DeclSpec::getSpecifierName(TSCS);
17239 
17240   // Check to see if this name was declared as a member previously
17241   NamedDecl *PrevDecl = nullptr;
17242   LookupResult Previous(*this, II, Loc, LookupMemberName,
17243                         ForVisibleRedeclaration);
17244   LookupName(Previous, S);
17245   switch (Previous.getResultKind()) {
17246     case LookupResult::Found:
17247     case LookupResult::FoundUnresolvedValue:
17248       PrevDecl = Previous.getAsSingle<NamedDecl>();
17249       break;
17250 
17251     case LookupResult::FoundOverloaded:
17252       PrevDecl = Previous.getRepresentativeDecl();
17253       break;
17254 
17255     case LookupResult::NotFound:
17256     case LookupResult::NotFoundInCurrentInstantiation:
17257     case LookupResult::Ambiguous:
17258       break;
17259   }
17260   Previous.suppressDiagnostics();
17261 
17262   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17263     // Maybe we will complain about the shadowed template parameter.
17264     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17265     // Just pretend that we didn't see the previous declaration.
17266     PrevDecl = nullptr;
17267   }
17268 
17269   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17270     PrevDecl = nullptr;
17271 
17272   bool Mutable
17273     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17274   SourceLocation TSSL = D.getBeginLoc();
17275   FieldDecl *NewFD
17276     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17277                      TSSL, AS, PrevDecl, &D);
17278 
17279   if (NewFD->isInvalidDecl())
17280     Record->setInvalidDecl();
17281 
17282   if (D.getDeclSpec().isModulePrivateSpecified())
17283     NewFD->setModulePrivate();
17284 
17285   if (NewFD->isInvalidDecl() && PrevDecl) {
17286     // Don't introduce NewFD into scope; there's already something
17287     // with the same name in the same scope.
17288   } else if (II) {
17289     PushOnScopeChains(NewFD, S);
17290   } else
17291     Record->addDecl(NewFD);
17292 
17293   return NewFD;
17294 }
17295 
17296 /// Build a new FieldDecl and check its well-formedness.
17297 ///
17298 /// This routine builds a new FieldDecl given the fields name, type,
17299 /// record, etc. \p PrevDecl should refer to any previous declaration
17300 /// with the same name and in the same scope as the field to be
17301 /// created.
17302 ///
17303 /// \returns a new FieldDecl.
17304 ///
17305 /// \todo The Declarator argument is a hack. It will be removed once
17306 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17307                                 TypeSourceInfo *TInfo,
17308                                 RecordDecl *Record, SourceLocation Loc,
17309                                 bool Mutable, Expr *BitWidth,
17310                                 InClassInitStyle InitStyle,
17311                                 SourceLocation TSSL,
17312                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17313                                 Declarator *D) {
17314   IdentifierInfo *II = Name.getAsIdentifierInfo();
17315   bool InvalidDecl = false;
17316   if (D) InvalidDecl = D->isInvalidType();
17317 
17318   // If we receive a broken type, recover by assuming 'int' and
17319   // marking this declaration as invalid.
17320   if (T.isNull() || T->containsErrors()) {
17321     InvalidDecl = true;
17322     T = Context.IntTy;
17323   }
17324 
17325   QualType EltTy = Context.getBaseElementType(T);
17326   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17327     if (RequireCompleteSizedType(Loc, EltTy,
17328                                  diag::err_field_incomplete_or_sizeless)) {
17329       // Fields of incomplete type force their record to be invalid.
17330       Record->setInvalidDecl();
17331       InvalidDecl = true;
17332     } else {
17333       NamedDecl *Def;
17334       EltTy->isIncompleteType(&Def);
17335       if (Def && Def->isInvalidDecl()) {
17336         Record->setInvalidDecl();
17337         InvalidDecl = true;
17338       }
17339     }
17340   }
17341 
17342   // TR 18037 does not allow fields to be declared with address space
17343   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17344       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17345     Diag(Loc, diag::err_field_with_address_space);
17346     Record->setInvalidDecl();
17347     InvalidDecl = true;
17348   }
17349 
17350   if (LangOpts.OpenCL) {
17351     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17352     // used as structure or union field: image, sampler, event or block types.
17353     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17354         T->isBlockPointerType()) {
17355       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17356       Record->setInvalidDecl();
17357       InvalidDecl = true;
17358     }
17359     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17360     // is enabled.
17361     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17362                         "__cl_clang_bitfields", LangOpts)) {
17363       Diag(Loc, diag::err_opencl_bitfields);
17364       InvalidDecl = true;
17365     }
17366   }
17367 
17368   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17369   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17370       T.hasQualifiers()) {
17371     InvalidDecl = true;
17372     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17373   }
17374 
17375   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17376   // than a variably modified type.
17377   if (!InvalidDecl && T->isVariablyModifiedType()) {
17378     if (!tryToFixVariablyModifiedVarType(
17379             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17380       InvalidDecl = true;
17381   }
17382 
17383   // Fields can not have abstract class types
17384   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17385                                              diag::err_abstract_type_in_decl,
17386                                              AbstractFieldType))
17387     InvalidDecl = true;
17388 
17389   if (InvalidDecl)
17390     BitWidth = nullptr;
17391   // If this is declared as a bit-field, check the bit-field.
17392   if (BitWidth) {
17393     BitWidth =
17394         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17395     if (!BitWidth) {
17396       InvalidDecl = true;
17397       BitWidth = nullptr;
17398     }
17399   }
17400 
17401   // Check that 'mutable' is consistent with the type of the declaration.
17402   if (!InvalidDecl && Mutable) {
17403     unsigned DiagID = 0;
17404     if (T->isReferenceType())
17405       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17406                                         : diag::err_mutable_reference;
17407     else if (T.isConstQualified())
17408       DiagID = diag::err_mutable_const;
17409 
17410     if (DiagID) {
17411       SourceLocation ErrLoc = Loc;
17412       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17413         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17414       Diag(ErrLoc, DiagID);
17415       if (DiagID != diag::ext_mutable_reference) {
17416         Mutable = false;
17417         InvalidDecl = true;
17418       }
17419     }
17420   }
17421 
17422   // C++11 [class.union]p8 (DR1460):
17423   //   At most one variant member of a union may have a
17424   //   brace-or-equal-initializer.
17425   if (InitStyle != ICIS_NoInit)
17426     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17427 
17428   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17429                                        BitWidth, Mutable, InitStyle);
17430   if (InvalidDecl)
17431     NewFD->setInvalidDecl();
17432 
17433   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17434     Diag(Loc, diag::err_duplicate_member) << II;
17435     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17436     NewFD->setInvalidDecl();
17437   }
17438 
17439   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17440     if (Record->isUnion()) {
17441       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17442         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17443         if (RDecl->getDefinition()) {
17444           // C++ [class.union]p1: An object of a class with a non-trivial
17445           // constructor, a non-trivial copy constructor, a non-trivial
17446           // destructor, or a non-trivial copy assignment operator
17447           // cannot be a member of a union, nor can an array of such
17448           // objects.
17449           if (CheckNontrivialField(NewFD))
17450             NewFD->setInvalidDecl();
17451         }
17452       }
17453 
17454       // C++ [class.union]p1: If a union contains a member of reference type,
17455       // the program is ill-formed, except when compiling with MSVC extensions
17456       // enabled.
17457       if (EltTy->isReferenceType()) {
17458         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17459                                     diag::ext_union_member_of_reference_type :
17460                                     diag::err_union_member_of_reference_type)
17461           << NewFD->getDeclName() << EltTy;
17462         if (!getLangOpts().MicrosoftExt)
17463           NewFD->setInvalidDecl();
17464       }
17465     }
17466   }
17467 
17468   // FIXME: We need to pass in the attributes given an AST
17469   // representation, not a parser representation.
17470   if (D) {
17471     // FIXME: The current scope is almost... but not entirely... correct here.
17472     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17473 
17474     if (NewFD->hasAttrs())
17475       CheckAlignasUnderalignment(NewFD);
17476   }
17477 
17478   // In auto-retain/release, infer strong retension for fields of
17479   // retainable type.
17480   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17481     NewFD->setInvalidDecl();
17482 
17483   if (T.isObjCGCWeak())
17484     Diag(Loc, diag::warn_attribute_weak_on_field);
17485 
17486   // PPC MMA non-pointer types are not allowed as field types.
17487   if (Context.getTargetInfo().getTriple().isPPC64() &&
17488       CheckPPCMMAType(T, NewFD->getLocation()))
17489     NewFD->setInvalidDecl();
17490 
17491   NewFD->setAccess(AS);
17492   return NewFD;
17493 }
17494 
17495 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17496   assert(FD);
17497   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17498 
17499   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17500     return false;
17501 
17502   QualType EltTy = Context.getBaseElementType(FD->getType());
17503   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17504     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17505     if (RDecl->getDefinition()) {
17506       // We check for copy constructors before constructors
17507       // because otherwise we'll never get complaints about
17508       // copy constructors.
17509 
17510       CXXSpecialMember member = CXXInvalid;
17511       // We're required to check for any non-trivial constructors. Since the
17512       // implicit default constructor is suppressed if there are any
17513       // user-declared constructors, we just need to check that there is a
17514       // trivial default constructor and a trivial copy constructor. (We don't
17515       // worry about move constructors here, since this is a C++98 check.)
17516       if (RDecl->hasNonTrivialCopyConstructor())
17517         member = CXXCopyConstructor;
17518       else if (!RDecl->hasTrivialDefaultConstructor())
17519         member = CXXDefaultConstructor;
17520       else if (RDecl->hasNonTrivialCopyAssignment())
17521         member = CXXCopyAssignment;
17522       else if (RDecl->hasNonTrivialDestructor())
17523         member = CXXDestructor;
17524 
17525       if (member != CXXInvalid) {
17526         if (!getLangOpts().CPlusPlus11 &&
17527             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17528           // Objective-C++ ARC: it is an error to have a non-trivial field of
17529           // a union. However, system headers in Objective-C programs
17530           // occasionally have Objective-C lifetime objects within unions,
17531           // and rather than cause the program to fail, we make those
17532           // members unavailable.
17533           SourceLocation Loc = FD->getLocation();
17534           if (getSourceManager().isInSystemHeader(Loc)) {
17535             if (!FD->hasAttr<UnavailableAttr>())
17536               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17537                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17538             return false;
17539           }
17540         }
17541 
17542         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17543                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17544                diag::err_illegal_union_or_anon_struct_member)
17545           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17546         DiagnoseNontrivial(RDecl, member);
17547         return !getLangOpts().CPlusPlus11;
17548       }
17549     }
17550   }
17551 
17552   return false;
17553 }
17554 
17555 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17556 ///  AST enum value.
17557 static ObjCIvarDecl::AccessControl
17558 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17559   switch (ivarVisibility) {
17560   default: llvm_unreachable("Unknown visitibility kind");
17561   case tok::objc_private: return ObjCIvarDecl::Private;
17562   case tok::objc_public: return ObjCIvarDecl::Public;
17563   case tok::objc_protected: return ObjCIvarDecl::Protected;
17564   case tok::objc_package: return ObjCIvarDecl::Package;
17565   }
17566 }
17567 
17568 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17569 /// in order to create an IvarDecl object for it.
17570 Decl *Sema::ActOnIvar(Scope *S,
17571                                 SourceLocation DeclStart,
17572                                 Declarator &D, Expr *BitfieldWidth,
17573                                 tok::ObjCKeywordKind Visibility) {
17574 
17575   IdentifierInfo *II = D.getIdentifier();
17576   Expr *BitWidth = (Expr*)BitfieldWidth;
17577   SourceLocation Loc = DeclStart;
17578   if (II) Loc = D.getIdentifierLoc();
17579 
17580   // FIXME: Unnamed fields can be handled in various different ways, for
17581   // example, unnamed unions inject all members into the struct namespace!
17582 
17583   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17584   QualType T = TInfo->getType();
17585 
17586   if (BitWidth) {
17587     // 6.7.2.1p3, 6.7.2.1p4
17588     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17589     if (!BitWidth)
17590       D.setInvalidType();
17591   } else {
17592     // Not a bitfield.
17593 
17594     // validate II.
17595 
17596   }
17597   if (T->isReferenceType()) {
17598     Diag(Loc, diag::err_ivar_reference_type);
17599     D.setInvalidType();
17600   }
17601   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17602   // than a variably modified type.
17603   else if (T->isVariablyModifiedType()) {
17604     if (!tryToFixVariablyModifiedVarType(
17605             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17606       D.setInvalidType();
17607   }
17608 
17609   // Get the visibility (access control) for this ivar.
17610   ObjCIvarDecl::AccessControl ac =
17611     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17612                                         : ObjCIvarDecl::None;
17613   // Must set ivar's DeclContext to its enclosing interface.
17614   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17615   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17616     return nullptr;
17617   ObjCContainerDecl *EnclosingContext;
17618   if (ObjCImplementationDecl *IMPDecl =
17619       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17620     if (LangOpts.ObjCRuntime.isFragile()) {
17621     // Case of ivar declared in an implementation. Context is that of its class.
17622       EnclosingContext = IMPDecl->getClassInterface();
17623       assert(EnclosingContext && "Implementation has no class interface!");
17624     }
17625     else
17626       EnclosingContext = EnclosingDecl;
17627   } else {
17628     if (ObjCCategoryDecl *CDecl =
17629         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17630       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17631         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17632         return nullptr;
17633       }
17634     }
17635     EnclosingContext = EnclosingDecl;
17636   }
17637 
17638   // Construct the decl.
17639   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17640                                              DeclStart, Loc, II, T,
17641                                              TInfo, ac, (Expr *)BitfieldWidth);
17642 
17643   if (II) {
17644     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17645                                            ForVisibleRedeclaration);
17646     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17647         && !isa<TagDecl>(PrevDecl)) {
17648       Diag(Loc, diag::err_duplicate_member) << II;
17649       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17650       NewID->setInvalidDecl();
17651     }
17652   }
17653 
17654   // Process attributes attached to the ivar.
17655   ProcessDeclAttributes(S, NewID, D);
17656 
17657   if (D.isInvalidType())
17658     NewID->setInvalidDecl();
17659 
17660   // In ARC, infer 'retaining' for ivars of retainable type.
17661   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17662     NewID->setInvalidDecl();
17663 
17664   if (D.getDeclSpec().isModulePrivateSpecified())
17665     NewID->setModulePrivate();
17666 
17667   if (II) {
17668     // FIXME: When interfaces are DeclContexts, we'll need to add
17669     // these to the interface.
17670     S->AddDecl(NewID);
17671     IdResolver.AddDecl(NewID);
17672   }
17673 
17674   if (LangOpts.ObjCRuntime.isNonFragile() &&
17675       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17676     Diag(Loc, diag::warn_ivars_in_interface);
17677 
17678   return NewID;
17679 }
17680 
17681 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17682 /// class and class extensions. For every class \@interface and class
17683 /// extension \@interface, if the last ivar is a bitfield of any type,
17684 /// then add an implicit `char :0` ivar to the end of that interface.
17685 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17686                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17687   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17688     return;
17689 
17690   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17691   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17692 
17693   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17694     return;
17695   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17696   if (!ID) {
17697     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17698       if (!CD->IsClassExtension())
17699         return;
17700     }
17701     // No need to add this to end of @implementation.
17702     else
17703       return;
17704   }
17705   // All conditions are met. Add a new bitfield to the tail end of ivars.
17706   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17707   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17708 
17709   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17710                               DeclLoc, DeclLoc, nullptr,
17711                               Context.CharTy,
17712                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17713                                                                DeclLoc),
17714                               ObjCIvarDecl::Private, BW,
17715                               true);
17716   AllIvarDecls.push_back(Ivar);
17717 }
17718 
17719 namespace {
17720 /// [class.dtor]p4:
17721 ///   At the end of the definition of a class, overload resolution is
17722 ///   performed among the prospective destructors declared in that class with
17723 ///   an empty argument list to select the destructor for the class, also
17724 ///   known as the selected destructor.
17725 ///
17726 /// We do the overload resolution here, then mark the selected constructor in the AST.
17727 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17728 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17729   if (!Record->hasUserDeclaredDestructor()) {
17730     return;
17731   }
17732 
17733   SourceLocation Loc = Record->getLocation();
17734   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17735 
17736   for (auto *Decl : Record->decls()) {
17737     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17738       if (DD->isInvalidDecl())
17739         continue;
17740       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17741                              OCS);
17742       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17743     }
17744   }
17745 
17746   if (OCS.empty()) {
17747     return;
17748   }
17749   OverloadCandidateSet::iterator Best;
17750   unsigned Msg = 0;
17751   OverloadCandidateDisplayKind DisplayKind;
17752 
17753   switch (OCS.BestViableFunction(S, Loc, Best)) {
17754   case OR_Success:
17755   case OR_Deleted:
17756     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17757     break;
17758 
17759   case OR_Ambiguous:
17760     Msg = diag::err_ambiguous_destructor;
17761     DisplayKind = OCD_AmbiguousCandidates;
17762     break;
17763 
17764   case OR_No_Viable_Function:
17765     Msg = diag::err_no_viable_destructor;
17766     DisplayKind = OCD_AllCandidates;
17767     break;
17768   }
17769 
17770   if (Msg) {
17771     // OpenCL have got their own thing going with destructors. It's slightly broken,
17772     // but we allow it.
17773     if (!S.LangOpts.OpenCL) {
17774       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17775       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17776       Record->setInvalidDecl();
17777     }
17778     // It's a bit hacky: At this point we've raised an error but we want the
17779     // rest of the compiler to continue somehow working. However almost
17780     // everything we'll try to do with the class will depend on there being a
17781     // destructor. So let's pretend the first one is selected and hope for the
17782     // best.
17783     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17784   }
17785 }
17786 } // namespace
17787 
17788 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17789                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17790                        SourceLocation RBrac,
17791                        const ParsedAttributesView &Attrs) {
17792   assert(EnclosingDecl && "missing record or interface decl");
17793 
17794   // If this is an Objective-C @implementation or category and we have
17795   // new fields here we should reset the layout of the interface since
17796   // it will now change.
17797   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17798     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17799     switch (DC->getKind()) {
17800     default: break;
17801     case Decl::ObjCCategory:
17802       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17803       break;
17804     case Decl::ObjCImplementation:
17805       Context.
17806         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17807       break;
17808     }
17809   }
17810 
17811   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17812   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17813 
17814   if (CXXRecord && !CXXRecord->isDependentType())
17815     ComputeSelectedDestructor(*this, CXXRecord);
17816 
17817   // Start counting up the number of named members; make sure to include
17818   // members of anonymous structs and unions in the total.
17819   unsigned NumNamedMembers = 0;
17820   if (Record) {
17821     for (const auto *I : Record->decls()) {
17822       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17823         if (IFD->getDeclName())
17824           ++NumNamedMembers;
17825     }
17826   }
17827 
17828   // Verify that all the fields are okay.
17829   SmallVector<FieldDecl*, 32> RecFields;
17830 
17831   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17832        i != end; ++i) {
17833     FieldDecl *FD = cast<FieldDecl>(*i);
17834 
17835     // Get the type for the field.
17836     const Type *FDTy = FD->getType().getTypePtr();
17837 
17838     if (!FD->isAnonymousStructOrUnion()) {
17839       // Remember all fields written by the user.
17840       RecFields.push_back(FD);
17841     }
17842 
17843     // If the field is already invalid for some reason, don't emit more
17844     // diagnostics about it.
17845     if (FD->isInvalidDecl()) {
17846       EnclosingDecl->setInvalidDecl();
17847       continue;
17848     }
17849 
17850     // C99 6.7.2.1p2:
17851     //   A structure or union shall not contain a member with
17852     //   incomplete or function type (hence, a structure shall not
17853     //   contain an instance of itself, but may contain a pointer to
17854     //   an instance of itself), except that the last member of a
17855     //   structure with more than one named member may have incomplete
17856     //   array type; such a structure (and any union containing,
17857     //   possibly recursively, a member that is such a structure)
17858     //   shall not be a member of a structure or an element of an
17859     //   array.
17860     bool IsLastField = (i + 1 == Fields.end());
17861     if (FDTy->isFunctionType()) {
17862       // Field declared as a function.
17863       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17864         << FD->getDeclName();
17865       FD->setInvalidDecl();
17866       EnclosingDecl->setInvalidDecl();
17867       continue;
17868     } else if (FDTy->isIncompleteArrayType() &&
17869                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17870       if (Record) {
17871         // Flexible array member.
17872         // Microsoft and g++ is more permissive regarding flexible array.
17873         // It will accept flexible array in union and also
17874         // as the sole element of a struct/class.
17875         unsigned DiagID = 0;
17876         if (!Record->isUnion() && !IsLastField) {
17877           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17878             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17879           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17880           FD->setInvalidDecl();
17881           EnclosingDecl->setInvalidDecl();
17882           continue;
17883         } else if (Record->isUnion())
17884           DiagID = getLangOpts().MicrosoftExt
17885                        ? diag::ext_flexible_array_union_ms
17886                        : getLangOpts().CPlusPlus
17887                              ? diag::ext_flexible_array_union_gnu
17888                              : diag::err_flexible_array_union;
17889         else if (NumNamedMembers < 1)
17890           DiagID = getLangOpts().MicrosoftExt
17891                        ? diag::ext_flexible_array_empty_aggregate_ms
17892                        : getLangOpts().CPlusPlus
17893                              ? diag::ext_flexible_array_empty_aggregate_gnu
17894                              : diag::err_flexible_array_empty_aggregate;
17895 
17896         if (DiagID)
17897           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17898                                           << Record->getTagKind();
17899         // While the layout of types that contain virtual bases is not specified
17900         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17901         // virtual bases after the derived members.  This would make a flexible
17902         // array member declared at the end of an object not adjacent to the end
17903         // of the type.
17904         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17905           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17906               << FD->getDeclName() << Record->getTagKind();
17907         if (!getLangOpts().C99)
17908           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17909             << FD->getDeclName() << Record->getTagKind();
17910 
17911         // If the element type has a non-trivial destructor, we would not
17912         // implicitly destroy the elements, so disallow it for now.
17913         //
17914         // FIXME: GCC allows this. We should probably either implicitly delete
17915         // the destructor of the containing class, or just allow this.
17916         QualType BaseElem = Context.getBaseElementType(FD->getType());
17917         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17918           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17919             << FD->getDeclName() << FD->getType();
17920           FD->setInvalidDecl();
17921           EnclosingDecl->setInvalidDecl();
17922           continue;
17923         }
17924         // Okay, we have a legal flexible array member at the end of the struct.
17925         Record->setHasFlexibleArrayMember(true);
17926       } else {
17927         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17928         // unless they are followed by another ivar. That check is done
17929         // elsewhere, after synthesized ivars are known.
17930       }
17931     } else if (!FDTy->isDependentType() &&
17932                RequireCompleteSizedType(
17933                    FD->getLocation(), FD->getType(),
17934                    diag::err_field_incomplete_or_sizeless)) {
17935       // Incomplete type
17936       FD->setInvalidDecl();
17937       EnclosingDecl->setInvalidDecl();
17938       continue;
17939     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17940       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17941         // A type which contains a flexible array member is considered to be a
17942         // flexible array member.
17943         Record->setHasFlexibleArrayMember(true);
17944         if (!Record->isUnion()) {
17945           // If this is a struct/class and this is not the last element, reject
17946           // it.  Note that GCC supports variable sized arrays in the middle of
17947           // structures.
17948           if (!IsLastField)
17949             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17950               << FD->getDeclName() << FD->getType();
17951           else {
17952             // We support flexible arrays at the end of structs in
17953             // other structs as an extension.
17954             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17955               << FD->getDeclName();
17956           }
17957         }
17958       }
17959       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17960           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17961                                  diag::err_abstract_type_in_decl,
17962                                  AbstractIvarType)) {
17963         // Ivars can not have abstract class types
17964         FD->setInvalidDecl();
17965       }
17966       if (Record && FDTTy->getDecl()->hasObjectMember())
17967         Record->setHasObjectMember(true);
17968       if (Record && FDTTy->getDecl()->hasVolatileMember())
17969         Record->setHasVolatileMember(true);
17970     } else if (FDTy->isObjCObjectType()) {
17971       /// A field cannot be an Objective-c object
17972       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17973         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17974       QualType T = Context.getObjCObjectPointerType(FD->getType());
17975       FD->setType(T);
17976     } else if (Record && Record->isUnion() &&
17977                FD->getType().hasNonTrivialObjCLifetime() &&
17978                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17979                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17980                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17981                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17982       // For backward compatibility, fields of C unions declared in system
17983       // headers that have non-trivial ObjC ownership qualifications are marked
17984       // as unavailable unless the qualifier is explicit and __strong. This can
17985       // break ABI compatibility between programs compiled with ARC and MRR, but
17986       // is a better option than rejecting programs using those unions under
17987       // ARC.
17988       FD->addAttr(UnavailableAttr::CreateImplicit(
17989           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17990           FD->getLocation()));
17991     } else if (getLangOpts().ObjC &&
17992                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17993                !Record->hasObjectMember()) {
17994       if (FD->getType()->isObjCObjectPointerType() ||
17995           FD->getType().isObjCGCStrong())
17996         Record->setHasObjectMember(true);
17997       else if (Context.getAsArrayType(FD->getType())) {
17998         QualType BaseType = Context.getBaseElementType(FD->getType());
17999         if (BaseType->isRecordType() &&
18000             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18001           Record->setHasObjectMember(true);
18002         else if (BaseType->isObjCObjectPointerType() ||
18003                  BaseType.isObjCGCStrong())
18004                Record->setHasObjectMember(true);
18005       }
18006     }
18007 
18008     if (Record && !getLangOpts().CPlusPlus &&
18009         !shouldIgnoreForRecordTriviality(FD)) {
18010       QualType FT = FD->getType();
18011       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18012         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18013         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18014             Record->isUnion())
18015           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18016       }
18017       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18018       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18019         Record->setNonTrivialToPrimitiveCopy(true);
18020         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18021           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18022       }
18023       if (FT.isDestructedType()) {
18024         Record->setNonTrivialToPrimitiveDestroy(true);
18025         Record->setParamDestroyedInCallee(true);
18026         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18027           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18028       }
18029 
18030       if (const auto *RT = FT->getAs<RecordType>()) {
18031         if (RT->getDecl()->getArgPassingRestrictions() ==
18032             RecordDecl::APK_CanNeverPassInRegs)
18033           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18034       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18035         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18036     }
18037 
18038     if (Record && FD->getType().isVolatileQualified())
18039       Record->setHasVolatileMember(true);
18040     // Keep track of the number of named members.
18041     if (FD->getIdentifier())
18042       ++NumNamedMembers;
18043   }
18044 
18045   // Okay, we successfully defined 'Record'.
18046   if (Record) {
18047     bool Completed = false;
18048     if (CXXRecord) {
18049       if (!CXXRecord->isInvalidDecl()) {
18050         // Set access bits correctly on the directly-declared conversions.
18051         for (CXXRecordDecl::conversion_iterator
18052                I = CXXRecord->conversion_begin(),
18053                E = CXXRecord->conversion_end(); I != E; ++I)
18054           I.setAccess((*I)->getAccess());
18055       }
18056 
18057       // Add any implicitly-declared members to this class.
18058       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18059 
18060       if (!CXXRecord->isDependentType()) {
18061         if (!CXXRecord->isInvalidDecl()) {
18062           // If we have virtual base classes, we may end up finding multiple
18063           // final overriders for a given virtual function. Check for this
18064           // problem now.
18065           if (CXXRecord->getNumVBases()) {
18066             CXXFinalOverriderMap FinalOverriders;
18067             CXXRecord->getFinalOverriders(FinalOverriders);
18068 
18069             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18070                                              MEnd = FinalOverriders.end();
18071                  M != MEnd; ++M) {
18072               for (OverridingMethods::iterator SO = M->second.begin(),
18073                                             SOEnd = M->second.end();
18074                    SO != SOEnd; ++SO) {
18075                 assert(SO->second.size() > 0 &&
18076                        "Virtual function without overriding functions?");
18077                 if (SO->second.size() == 1)
18078                   continue;
18079 
18080                 // C++ [class.virtual]p2:
18081                 //   In a derived class, if a virtual member function of a base
18082                 //   class subobject has more than one final overrider the
18083                 //   program is ill-formed.
18084                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18085                   << (const NamedDecl *)M->first << Record;
18086                 Diag(M->first->getLocation(),
18087                      diag::note_overridden_virtual_function);
18088                 for (OverridingMethods::overriding_iterator
18089                           OM = SO->second.begin(),
18090                        OMEnd = SO->second.end();
18091                      OM != OMEnd; ++OM)
18092                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18093                     << (const NamedDecl *)M->first << OM->Method->getParent();
18094 
18095                 Record->setInvalidDecl();
18096               }
18097             }
18098             CXXRecord->completeDefinition(&FinalOverriders);
18099             Completed = true;
18100           }
18101         }
18102       }
18103     }
18104 
18105     if (!Completed)
18106       Record->completeDefinition();
18107 
18108     // Handle attributes before checking the layout.
18109     ProcessDeclAttributeList(S, Record, Attrs);
18110 
18111     // Check to see if a FieldDecl is a pointer to a function.
18112     auto IsFunctionPointer = [&](const Decl *D) {
18113       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18114       if (!FD)
18115         return false;
18116       QualType FieldType = FD->getType().getDesugaredType(Context);
18117       if (isa<PointerType>(FieldType)) {
18118         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18119         return PointeeType.getDesugaredType(Context)->isFunctionType();
18120       }
18121       return false;
18122     };
18123 
18124     // Maybe randomize the record's decls. We automatically randomize a record
18125     // of function pointers, unless it has the "no_randomize_layout" attribute.
18126     if (!getLangOpts().CPlusPlus &&
18127         (Record->hasAttr<RandomizeLayoutAttr>() ||
18128          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18129           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18130         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18131         !Record->isRandomized()) {
18132       SmallVector<Decl *, 32> NewDeclOrdering;
18133       if (randstruct::randomizeStructureLayout(Context, Record,
18134                                                NewDeclOrdering))
18135         Record->reorderDecls(NewDeclOrdering);
18136     }
18137 
18138     // We may have deferred checking for a deleted destructor. Check now.
18139     if (CXXRecord) {
18140       auto *Dtor = CXXRecord->getDestructor();
18141       if (Dtor && Dtor->isImplicit() &&
18142           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18143         CXXRecord->setImplicitDestructorIsDeleted();
18144         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18145       }
18146     }
18147 
18148     if (Record->hasAttrs()) {
18149       CheckAlignasUnderalignment(Record);
18150 
18151       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18152         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18153                                            IA->getRange(), IA->getBestCase(),
18154                                            IA->getInheritanceModel());
18155     }
18156 
18157     // Check if the structure/union declaration is a type that can have zero
18158     // size in C. For C this is a language extension, for C++ it may cause
18159     // compatibility problems.
18160     bool CheckForZeroSize;
18161     if (!getLangOpts().CPlusPlus) {
18162       CheckForZeroSize = true;
18163     } else {
18164       // For C++ filter out types that cannot be referenced in C code.
18165       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18166       CheckForZeroSize =
18167           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18168           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18169           CXXRecord->isCLike();
18170     }
18171     if (CheckForZeroSize) {
18172       bool ZeroSize = true;
18173       bool IsEmpty = true;
18174       unsigned NonBitFields = 0;
18175       for (RecordDecl::field_iterator I = Record->field_begin(),
18176                                       E = Record->field_end();
18177            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18178         IsEmpty = false;
18179         if (I->isUnnamedBitfield()) {
18180           if (!I->isZeroLengthBitField(Context))
18181             ZeroSize = false;
18182         } else {
18183           ++NonBitFields;
18184           QualType FieldType = I->getType();
18185           if (FieldType->isIncompleteType() ||
18186               !Context.getTypeSizeInChars(FieldType).isZero())
18187             ZeroSize = false;
18188         }
18189       }
18190 
18191       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18192       // allowed in C++, but warn if its declaration is inside
18193       // extern "C" block.
18194       if (ZeroSize) {
18195         Diag(RecLoc, getLangOpts().CPlusPlus ?
18196                          diag::warn_zero_size_struct_union_in_extern_c :
18197                          diag::warn_zero_size_struct_union_compat)
18198           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18199       }
18200 
18201       // Structs without named members are extension in C (C99 6.7.2.1p7),
18202       // but are accepted by GCC.
18203       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18204         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18205                                diag::ext_no_named_members_in_struct_union)
18206           << Record->isUnion();
18207       }
18208     }
18209   } else {
18210     ObjCIvarDecl **ClsFields =
18211       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18212     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18213       ID->setEndOfDefinitionLoc(RBrac);
18214       // Add ivar's to class's DeclContext.
18215       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18216         ClsFields[i]->setLexicalDeclContext(ID);
18217         ID->addDecl(ClsFields[i]);
18218       }
18219       // Must enforce the rule that ivars in the base classes may not be
18220       // duplicates.
18221       if (ID->getSuperClass())
18222         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18223     } else if (ObjCImplementationDecl *IMPDecl =
18224                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18225       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18226       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18227         // Ivar declared in @implementation never belongs to the implementation.
18228         // Only it is in implementation's lexical context.
18229         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18230       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18231       IMPDecl->setIvarLBraceLoc(LBrac);
18232       IMPDecl->setIvarRBraceLoc(RBrac);
18233     } else if (ObjCCategoryDecl *CDecl =
18234                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18235       // case of ivars in class extension; all other cases have been
18236       // reported as errors elsewhere.
18237       // FIXME. Class extension does not have a LocEnd field.
18238       // CDecl->setLocEnd(RBrac);
18239       // Add ivar's to class extension's DeclContext.
18240       // Diagnose redeclaration of private ivars.
18241       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18242       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18243         if (IDecl) {
18244           if (const ObjCIvarDecl *ClsIvar =
18245               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18246             Diag(ClsFields[i]->getLocation(),
18247                  diag::err_duplicate_ivar_declaration);
18248             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18249             continue;
18250           }
18251           for (const auto *Ext : IDecl->known_extensions()) {
18252             if (const ObjCIvarDecl *ClsExtIvar
18253                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18254               Diag(ClsFields[i]->getLocation(),
18255                    diag::err_duplicate_ivar_declaration);
18256               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18257               continue;
18258             }
18259           }
18260         }
18261         ClsFields[i]->setLexicalDeclContext(CDecl);
18262         CDecl->addDecl(ClsFields[i]);
18263       }
18264       CDecl->setIvarLBraceLoc(LBrac);
18265       CDecl->setIvarRBraceLoc(RBrac);
18266     }
18267   }
18268 }
18269 
18270 /// Determine whether the given integral value is representable within
18271 /// the given type T.
18272 static bool isRepresentableIntegerValue(ASTContext &Context,
18273                                         llvm::APSInt &Value,
18274                                         QualType T) {
18275   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18276          "Integral type required!");
18277   unsigned BitWidth = Context.getIntWidth(T);
18278 
18279   if (Value.isUnsigned() || Value.isNonNegative()) {
18280     if (T->isSignedIntegerOrEnumerationType())
18281       --BitWidth;
18282     return Value.getActiveBits() <= BitWidth;
18283   }
18284   return Value.getMinSignedBits() <= BitWidth;
18285 }
18286 
18287 // Given an integral type, return the next larger integral type
18288 // (or a NULL type of no such type exists).
18289 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18290   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18291   // enum checking below.
18292   assert((T->isIntegralType(Context) ||
18293          T->isEnumeralType()) && "Integral type required!");
18294   const unsigned NumTypes = 4;
18295   QualType SignedIntegralTypes[NumTypes] = {
18296     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18297   };
18298   QualType UnsignedIntegralTypes[NumTypes] = {
18299     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18300     Context.UnsignedLongLongTy
18301   };
18302 
18303   unsigned BitWidth = Context.getTypeSize(T);
18304   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18305                                                         : UnsignedIntegralTypes;
18306   for (unsigned I = 0; I != NumTypes; ++I)
18307     if (Context.getTypeSize(Types[I]) > BitWidth)
18308       return Types[I];
18309 
18310   return QualType();
18311 }
18312 
18313 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18314                                           EnumConstantDecl *LastEnumConst,
18315                                           SourceLocation IdLoc,
18316                                           IdentifierInfo *Id,
18317                                           Expr *Val) {
18318   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18319   llvm::APSInt EnumVal(IntWidth);
18320   QualType EltTy;
18321 
18322   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18323     Val = nullptr;
18324 
18325   if (Val)
18326     Val = DefaultLvalueConversion(Val).get();
18327 
18328   if (Val) {
18329     if (Enum->isDependentType() || Val->isTypeDependent() ||
18330         Val->containsErrors())
18331       EltTy = Context.DependentTy;
18332     else {
18333       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18334       // underlying type, but do allow it in all other contexts.
18335       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18336         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18337         // constant-expression in the enumerator-definition shall be a converted
18338         // constant expression of the underlying type.
18339         EltTy = Enum->getIntegerType();
18340         ExprResult Converted =
18341           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18342                                            CCEK_Enumerator);
18343         if (Converted.isInvalid())
18344           Val = nullptr;
18345         else
18346           Val = Converted.get();
18347       } else if (!Val->isValueDependent() &&
18348                  !(Val =
18349                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18350                            .get())) {
18351         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18352       } else {
18353         if (Enum->isComplete()) {
18354           EltTy = Enum->getIntegerType();
18355 
18356           // In Obj-C and Microsoft mode, require the enumeration value to be
18357           // representable in the underlying type of the enumeration. In C++11,
18358           // we perform a non-narrowing conversion as part of converted constant
18359           // expression checking.
18360           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18361             if (Context.getTargetInfo()
18362                     .getTriple()
18363                     .isWindowsMSVCEnvironment()) {
18364               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18365             } else {
18366               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18367             }
18368           }
18369 
18370           // Cast to the underlying type.
18371           Val = ImpCastExprToType(Val, EltTy,
18372                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18373                                                          : CK_IntegralCast)
18374                     .get();
18375         } else if (getLangOpts().CPlusPlus) {
18376           // C++11 [dcl.enum]p5:
18377           //   If the underlying type is not fixed, the type of each enumerator
18378           //   is the type of its initializing value:
18379           //     - If an initializer is specified for an enumerator, the
18380           //       initializing value has the same type as the expression.
18381           EltTy = Val->getType();
18382         } else {
18383           // C99 6.7.2.2p2:
18384           //   The expression that defines the value of an enumeration constant
18385           //   shall be an integer constant expression that has a value
18386           //   representable as an int.
18387 
18388           // Complain if the value is not representable in an int.
18389           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18390             Diag(IdLoc, diag::ext_enum_value_not_int)
18391               << toString(EnumVal, 10) << Val->getSourceRange()
18392               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18393           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18394             // Force the type of the expression to 'int'.
18395             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18396           }
18397           EltTy = Val->getType();
18398         }
18399       }
18400     }
18401   }
18402 
18403   if (!Val) {
18404     if (Enum->isDependentType())
18405       EltTy = Context.DependentTy;
18406     else if (!LastEnumConst) {
18407       // C++0x [dcl.enum]p5:
18408       //   If the underlying type is not fixed, the type of each enumerator
18409       //   is the type of its initializing value:
18410       //     - If no initializer is specified for the first enumerator, the
18411       //       initializing value has an unspecified integral type.
18412       //
18413       // GCC uses 'int' for its unspecified integral type, as does
18414       // C99 6.7.2.2p3.
18415       if (Enum->isFixed()) {
18416         EltTy = Enum->getIntegerType();
18417       }
18418       else {
18419         EltTy = Context.IntTy;
18420       }
18421     } else {
18422       // Assign the last value + 1.
18423       EnumVal = LastEnumConst->getInitVal();
18424       ++EnumVal;
18425       EltTy = LastEnumConst->getType();
18426 
18427       // Check for overflow on increment.
18428       if (EnumVal < LastEnumConst->getInitVal()) {
18429         // C++0x [dcl.enum]p5:
18430         //   If the underlying type is not fixed, the type of each enumerator
18431         //   is the type of its initializing value:
18432         //
18433         //     - Otherwise the type of the initializing value is the same as
18434         //       the type of the initializing value of the preceding enumerator
18435         //       unless the incremented value is not representable in that type,
18436         //       in which case the type is an unspecified integral type
18437         //       sufficient to contain the incremented value. If no such type
18438         //       exists, the program is ill-formed.
18439         QualType T = getNextLargerIntegralType(Context, EltTy);
18440         if (T.isNull() || Enum->isFixed()) {
18441           // There is no integral type larger enough to represent this
18442           // value. Complain, then allow the value to wrap around.
18443           EnumVal = LastEnumConst->getInitVal();
18444           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18445           ++EnumVal;
18446           if (Enum->isFixed())
18447             // When the underlying type is fixed, this is ill-formed.
18448             Diag(IdLoc, diag::err_enumerator_wrapped)
18449               << toString(EnumVal, 10)
18450               << EltTy;
18451           else
18452             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18453               << toString(EnumVal, 10);
18454         } else {
18455           EltTy = T;
18456         }
18457 
18458         // Retrieve the last enumerator's value, extent that type to the
18459         // type that is supposed to be large enough to represent the incremented
18460         // value, then increment.
18461         EnumVal = LastEnumConst->getInitVal();
18462         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18463         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18464         ++EnumVal;
18465 
18466         // If we're not in C++, diagnose the overflow of enumerator values,
18467         // which in C99 means that the enumerator value is not representable in
18468         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18469         // permits enumerator values that are representable in some larger
18470         // integral type.
18471         if (!getLangOpts().CPlusPlus && !T.isNull())
18472           Diag(IdLoc, diag::warn_enum_value_overflow);
18473       } else if (!getLangOpts().CPlusPlus &&
18474                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18475         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18476         Diag(IdLoc, diag::ext_enum_value_not_int)
18477           << toString(EnumVal, 10) << 1;
18478       }
18479     }
18480   }
18481 
18482   if (!EltTy->isDependentType()) {
18483     // Make the enumerator value match the signedness and size of the
18484     // enumerator's type.
18485     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18486     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18487   }
18488 
18489   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18490                                   Val, EnumVal);
18491 }
18492 
18493 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18494                                                 SourceLocation IILoc) {
18495   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18496       !getLangOpts().CPlusPlus)
18497     return SkipBodyInfo();
18498 
18499   // We have an anonymous enum definition. Look up the first enumerator to
18500   // determine if we should merge the definition with an existing one and
18501   // skip the body.
18502   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18503                                          forRedeclarationInCurContext());
18504   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18505   if (!PrevECD)
18506     return SkipBodyInfo();
18507 
18508   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18509   NamedDecl *Hidden;
18510   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18511     SkipBodyInfo Skip;
18512     Skip.Previous = Hidden;
18513     return Skip;
18514   }
18515 
18516   return SkipBodyInfo();
18517 }
18518 
18519 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18520                               SourceLocation IdLoc, IdentifierInfo *Id,
18521                               const ParsedAttributesView &Attrs,
18522                               SourceLocation EqualLoc, Expr *Val) {
18523   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18524   EnumConstantDecl *LastEnumConst =
18525     cast_or_null<EnumConstantDecl>(lastEnumConst);
18526 
18527   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18528   // we find one that is.
18529   S = getNonFieldDeclScope(S);
18530 
18531   // Verify that there isn't already something declared with this name in this
18532   // scope.
18533   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18534   LookupName(R, S);
18535   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18536 
18537   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18538     // Maybe we will complain about the shadowed template parameter.
18539     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18540     // Just pretend that we didn't see the previous declaration.
18541     PrevDecl = nullptr;
18542   }
18543 
18544   // C++ [class.mem]p15:
18545   // If T is the name of a class, then each of the following shall have a name
18546   // different from T:
18547   // - every enumerator of every member of class T that is an unscoped
18548   // enumerated type
18549   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18550     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18551                             DeclarationNameInfo(Id, IdLoc));
18552 
18553   EnumConstantDecl *New =
18554     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18555   if (!New)
18556     return nullptr;
18557 
18558   if (PrevDecl) {
18559     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18560       // Check for other kinds of shadowing not already handled.
18561       CheckShadow(New, PrevDecl, R);
18562     }
18563 
18564     // When in C++, we may get a TagDecl with the same name; in this case the
18565     // enum constant will 'hide' the tag.
18566     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18567            "Received TagDecl when not in C++!");
18568     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18569       if (isa<EnumConstantDecl>(PrevDecl))
18570         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18571       else
18572         Diag(IdLoc, diag::err_redefinition) << Id;
18573       notePreviousDefinition(PrevDecl, IdLoc);
18574       return nullptr;
18575     }
18576   }
18577 
18578   // Process attributes.
18579   ProcessDeclAttributeList(S, New, Attrs);
18580   AddPragmaAttributes(S, New);
18581 
18582   // Register this decl in the current scope stack.
18583   New->setAccess(TheEnumDecl->getAccess());
18584   PushOnScopeChains(New, S);
18585 
18586   ActOnDocumentableDecl(New);
18587 
18588   return New;
18589 }
18590 
18591 // Returns true when the enum initial expression does not trigger the
18592 // duplicate enum warning.  A few common cases are exempted as follows:
18593 // Element2 = Element1
18594 // Element2 = Element1 + 1
18595 // Element2 = Element1 - 1
18596 // Where Element2 and Element1 are from the same enum.
18597 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18598   Expr *InitExpr = ECD->getInitExpr();
18599   if (!InitExpr)
18600     return true;
18601   InitExpr = InitExpr->IgnoreImpCasts();
18602 
18603   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18604     if (!BO->isAdditiveOp())
18605       return true;
18606     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18607     if (!IL)
18608       return true;
18609     if (IL->getValue() != 1)
18610       return true;
18611 
18612     InitExpr = BO->getLHS();
18613   }
18614 
18615   // This checks if the elements are from the same enum.
18616   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18617   if (!DRE)
18618     return true;
18619 
18620   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18621   if (!EnumConstant)
18622     return true;
18623 
18624   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18625       Enum)
18626     return true;
18627 
18628   return false;
18629 }
18630 
18631 // Emits a warning when an element is implicitly set a value that
18632 // a previous element has already been set to.
18633 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18634                                         EnumDecl *Enum, QualType EnumType) {
18635   // Avoid anonymous enums
18636   if (!Enum->getIdentifier())
18637     return;
18638 
18639   // Only check for small enums.
18640   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18641     return;
18642 
18643   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18644     return;
18645 
18646   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18647   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18648 
18649   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18650 
18651   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18652   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18653 
18654   // Use int64_t as a key to avoid needing special handling for map keys.
18655   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18656     llvm::APSInt Val = D->getInitVal();
18657     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18658   };
18659 
18660   DuplicatesVector DupVector;
18661   ValueToVectorMap EnumMap;
18662 
18663   // Populate the EnumMap with all values represented by enum constants without
18664   // an initializer.
18665   for (auto *Element : Elements) {
18666     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18667 
18668     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18669     // this constant.  Skip this enum since it may be ill-formed.
18670     if (!ECD) {
18671       return;
18672     }
18673 
18674     // Constants with initalizers are handled in the next loop.
18675     if (ECD->getInitExpr())
18676       continue;
18677 
18678     // Duplicate values are handled in the next loop.
18679     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18680   }
18681 
18682   if (EnumMap.size() == 0)
18683     return;
18684 
18685   // Create vectors for any values that has duplicates.
18686   for (auto *Element : Elements) {
18687     // The last loop returned if any constant was null.
18688     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18689     if (!ValidDuplicateEnum(ECD, Enum))
18690       continue;
18691 
18692     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18693     if (Iter == EnumMap.end())
18694       continue;
18695 
18696     DeclOrVector& Entry = Iter->second;
18697     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18698       // Ensure constants are different.
18699       if (D == ECD)
18700         continue;
18701 
18702       // Create new vector and push values onto it.
18703       auto Vec = std::make_unique<ECDVector>();
18704       Vec->push_back(D);
18705       Vec->push_back(ECD);
18706 
18707       // Update entry to point to the duplicates vector.
18708       Entry = Vec.get();
18709 
18710       // Store the vector somewhere we can consult later for quick emission of
18711       // diagnostics.
18712       DupVector.emplace_back(std::move(Vec));
18713       continue;
18714     }
18715 
18716     ECDVector *Vec = Entry.get<ECDVector*>();
18717     // Make sure constants are not added more than once.
18718     if (*Vec->begin() == ECD)
18719       continue;
18720 
18721     Vec->push_back(ECD);
18722   }
18723 
18724   // Emit diagnostics.
18725   for (const auto &Vec : DupVector) {
18726     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18727 
18728     // Emit warning for one enum constant.
18729     auto *FirstECD = Vec->front();
18730     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18731       << FirstECD << toString(FirstECD->getInitVal(), 10)
18732       << FirstECD->getSourceRange();
18733 
18734     // Emit one note for each of the remaining enum constants with
18735     // the same value.
18736     for (auto *ECD : llvm::drop_begin(*Vec))
18737       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18738         << ECD << toString(ECD->getInitVal(), 10)
18739         << ECD->getSourceRange();
18740   }
18741 }
18742 
18743 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18744                              bool AllowMask) const {
18745   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18746   assert(ED->isCompleteDefinition() && "expected enum definition");
18747 
18748   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18749   llvm::APInt &FlagBits = R.first->second;
18750 
18751   if (R.second) {
18752     for (auto *E : ED->enumerators()) {
18753       const auto &EVal = E->getInitVal();
18754       // Only single-bit enumerators introduce new flag values.
18755       if (EVal.isPowerOf2())
18756         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18757     }
18758   }
18759 
18760   // A value is in a flag enum if either its bits are a subset of the enum's
18761   // flag bits (the first condition) or we are allowing masks and the same is
18762   // true of its complement (the second condition). When masks are allowed, we
18763   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18764   //
18765   // While it's true that any value could be used as a mask, the assumption is
18766   // that a mask will have all of the insignificant bits set. Anything else is
18767   // likely a logic error.
18768   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18769   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18770 }
18771 
18772 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18773                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18774                          const ParsedAttributesView &Attrs) {
18775   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18776   QualType EnumType = Context.getTypeDeclType(Enum);
18777 
18778   ProcessDeclAttributeList(S, Enum, Attrs);
18779 
18780   if (Enum->isDependentType()) {
18781     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18782       EnumConstantDecl *ECD =
18783         cast_or_null<EnumConstantDecl>(Elements[i]);
18784       if (!ECD) continue;
18785 
18786       ECD->setType(EnumType);
18787     }
18788 
18789     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18790     return;
18791   }
18792 
18793   // TODO: If the result value doesn't fit in an int, it must be a long or long
18794   // long value.  ISO C does not support this, but GCC does as an extension,
18795   // emit a warning.
18796   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18797   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18798   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18799 
18800   // Verify that all the values are okay, compute the size of the values, and
18801   // reverse the list.
18802   unsigned NumNegativeBits = 0;
18803   unsigned NumPositiveBits = 0;
18804 
18805   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18806     EnumConstantDecl *ECD =
18807       cast_or_null<EnumConstantDecl>(Elements[i]);
18808     if (!ECD) continue;  // Already issued a diagnostic.
18809 
18810     const llvm::APSInt &InitVal = ECD->getInitVal();
18811 
18812     // Keep track of the size of positive and negative values.
18813     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18814       NumPositiveBits = std::max(NumPositiveBits,
18815                                  (unsigned)InitVal.getActiveBits());
18816     else
18817       NumNegativeBits = std::max(NumNegativeBits,
18818                                  (unsigned)InitVal.getMinSignedBits());
18819   }
18820 
18821   // Figure out the type that should be used for this enum.
18822   QualType BestType;
18823   unsigned BestWidth;
18824 
18825   // C++0x N3000 [conv.prom]p3:
18826   //   An rvalue of an unscoped enumeration type whose underlying
18827   //   type is not fixed can be converted to an rvalue of the first
18828   //   of the following types that can represent all the values of
18829   //   the enumeration: int, unsigned int, long int, unsigned long
18830   //   int, long long int, or unsigned long long int.
18831   // C99 6.4.4.3p2:
18832   //   An identifier declared as an enumeration constant has type int.
18833   // The C99 rule is modified by a gcc extension
18834   QualType BestPromotionType;
18835 
18836   bool Packed = Enum->hasAttr<PackedAttr>();
18837   // -fshort-enums is the equivalent to specifying the packed attribute on all
18838   // enum definitions.
18839   if (LangOpts.ShortEnums)
18840     Packed = true;
18841 
18842   // If the enum already has a type because it is fixed or dictated by the
18843   // target, promote that type instead of analyzing the enumerators.
18844   if (Enum->isComplete()) {
18845     BestType = Enum->getIntegerType();
18846     if (BestType->isPromotableIntegerType())
18847       BestPromotionType = Context.getPromotedIntegerType(BestType);
18848     else
18849       BestPromotionType = BestType;
18850 
18851     BestWidth = Context.getIntWidth(BestType);
18852   }
18853   else if (NumNegativeBits) {
18854     // If there is a negative value, figure out the smallest integer type (of
18855     // int/long/longlong) that fits.
18856     // If it's packed, check also if it fits a char or a short.
18857     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18858       BestType = Context.SignedCharTy;
18859       BestWidth = CharWidth;
18860     } else if (Packed && NumNegativeBits <= ShortWidth &&
18861                NumPositiveBits < ShortWidth) {
18862       BestType = Context.ShortTy;
18863       BestWidth = ShortWidth;
18864     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18865       BestType = Context.IntTy;
18866       BestWidth = IntWidth;
18867     } else {
18868       BestWidth = Context.getTargetInfo().getLongWidth();
18869 
18870       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18871         BestType = Context.LongTy;
18872       } else {
18873         BestWidth = Context.getTargetInfo().getLongLongWidth();
18874 
18875         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18876           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18877         BestType = Context.LongLongTy;
18878       }
18879     }
18880     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18881   } else {
18882     // If there is no negative value, figure out the smallest type that fits
18883     // all of the enumerator values.
18884     // If it's packed, check also if it fits a char or a short.
18885     if (Packed && NumPositiveBits <= CharWidth) {
18886       BestType = Context.UnsignedCharTy;
18887       BestPromotionType = Context.IntTy;
18888       BestWidth = CharWidth;
18889     } else if (Packed && NumPositiveBits <= ShortWidth) {
18890       BestType = Context.UnsignedShortTy;
18891       BestPromotionType = Context.IntTy;
18892       BestWidth = ShortWidth;
18893     } else if (NumPositiveBits <= IntWidth) {
18894       BestType = Context.UnsignedIntTy;
18895       BestWidth = IntWidth;
18896       BestPromotionType
18897         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18898                            ? Context.UnsignedIntTy : Context.IntTy;
18899     } else if (NumPositiveBits <=
18900                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18901       BestType = Context.UnsignedLongTy;
18902       BestPromotionType
18903         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18904                            ? Context.UnsignedLongTy : Context.LongTy;
18905     } else {
18906       BestWidth = Context.getTargetInfo().getLongLongWidth();
18907       assert(NumPositiveBits <= BestWidth &&
18908              "How could an initializer get larger than ULL?");
18909       BestType = Context.UnsignedLongLongTy;
18910       BestPromotionType
18911         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18912                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18913     }
18914   }
18915 
18916   // Loop over all of the enumerator constants, changing their types to match
18917   // the type of the enum if needed.
18918   for (auto *D : Elements) {
18919     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18920     if (!ECD) continue;  // Already issued a diagnostic.
18921 
18922     // Standard C says the enumerators have int type, but we allow, as an
18923     // extension, the enumerators to be larger than int size.  If each
18924     // enumerator value fits in an int, type it as an int, otherwise type it the
18925     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18926     // that X has type 'int', not 'unsigned'.
18927 
18928     // Determine whether the value fits into an int.
18929     llvm::APSInt InitVal = ECD->getInitVal();
18930 
18931     // If it fits into an integer type, force it.  Otherwise force it to match
18932     // the enum decl type.
18933     QualType NewTy;
18934     unsigned NewWidth;
18935     bool NewSign;
18936     if (!getLangOpts().CPlusPlus &&
18937         !Enum->isFixed() &&
18938         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18939       NewTy = Context.IntTy;
18940       NewWidth = IntWidth;
18941       NewSign = true;
18942     } else if (ECD->getType() == BestType) {
18943       // Already the right type!
18944       if (getLangOpts().CPlusPlus)
18945         // C++ [dcl.enum]p4: Following the closing brace of an
18946         // enum-specifier, each enumerator has the type of its
18947         // enumeration.
18948         ECD->setType(EnumType);
18949       continue;
18950     } else {
18951       NewTy = BestType;
18952       NewWidth = BestWidth;
18953       NewSign = BestType->isSignedIntegerOrEnumerationType();
18954     }
18955 
18956     // Adjust the APSInt value.
18957     InitVal = InitVal.extOrTrunc(NewWidth);
18958     InitVal.setIsSigned(NewSign);
18959     ECD->setInitVal(InitVal);
18960 
18961     // Adjust the Expr initializer and type.
18962     if (ECD->getInitExpr() &&
18963         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18964       ECD->setInitExpr(ImplicitCastExpr::Create(
18965           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18966           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18967     if (getLangOpts().CPlusPlus)
18968       // C++ [dcl.enum]p4: Following the closing brace of an
18969       // enum-specifier, each enumerator has the type of its
18970       // enumeration.
18971       ECD->setType(EnumType);
18972     else
18973       ECD->setType(NewTy);
18974   }
18975 
18976   Enum->completeDefinition(BestType, BestPromotionType,
18977                            NumPositiveBits, NumNegativeBits);
18978 
18979   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18980 
18981   if (Enum->isClosedFlag()) {
18982     for (Decl *D : Elements) {
18983       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18984       if (!ECD) continue;  // Already issued a diagnostic.
18985 
18986       llvm::APSInt InitVal = ECD->getInitVal();
18987       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18988           !IsValueInFlagEnum(Enum, InitVal, true))
18989         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18990           << ECD << Enum;
18991     }
18992   }
18993 
18994   // Now that the enum type is defined, ensure it's not been underaligned.
18995   if (Enum->hasAttrs())
18996     CheckAlignasUnderalignment(Enum);
18997 }
18998 
18999 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19000                                   SourceLocation StartLoc,
19001                                   SourceLocation EndLoc) {
19002   StringLiteral *AsmString = cast<StringLiteral>(expr);
19003 
19004   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19005                                                    AsmString, StartLoc,
19006                                                    EndLoc);
19007   CurContext->addDecl(New);
19008   return New;
19009 }
19010 
19011 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19012                                       IdentifierInfo* AliasName,
19013                                       SourceLocation PragmaLoc,
19014                                       SourceLocation NameLoc,
19015                                       SourceLocation AliasNameLoc) {
19016   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19017                                          LookupOrdinaryName);
19018   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19019                            AttributeCommonInfo::AS_Pragma);
19020   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19021       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19022 
19023   // If a declaration that:
19024   // 1) declares a function or a variable
19025   // 2) has external linkage
19026   // already exists, add a label attribute to it.
19027   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19028     if (isDeclExternC(PrevDecl))
19029       PrevDecl->addAttr(Attr);
19030     else
19031       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19032           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19033   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19034   } else
19035     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19036 }
19037 
19038 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19039                              SourceLocation PragmaLoc,
19040                              SourceLocation NameLoc) {
19041   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19042 
19043   if (PrevDecl) {
19044     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19045   } else {
19046     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19047   }
19048 }
19049 
19050 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19051                                 IdentifierInfo* AliasName,
19052                                 SourceLocation PragmaLoc,
19053                                 SourceLocation NameLoc,
19054                                 SourceLocation AliasNameLoc) {
19055   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19056                                     LookupOrdinaryName);
19057   WeakInfo W = WeakInfo(Name, NameLoc);
19058 
19059   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19060     if (!PrevDecl->hasAttr<AliasAttr>())
19061       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19062         DeclApplyPragmaWeak(TUScope, ND, W);
19063   } else {
19064     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19065   }
19066 }
19067 
19068 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19069   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19070 }
19071 
19072 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19073                                                      bool Final) {
19074   assert(FD && "Expected non-null FunctionDecl");
19075 
19076   // SYCL functions can be template, so we check if they have appropriate
19077   // attribute prior to checking if it is a template.
19078   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19079     return FunctionEmissionStatus::Emitted;
19080 
19081   // Templates are emitted when they're instantiated.
19082   if (FD->isDependentContext())
19083     return FunctionEmissionStatus::TemplateDiscarded;
19084 
19085   // Check whether this function is an externally visible definition.
19086   auto IsEmittedForExternalSymbol = [this, FD]() {
19087     // We have to check the GVA linkage of the function's *definition* -- if we
19088     // only have a declaration, we don't know whether or not the function will
19089     // be emitted, because (say) the definition could include "inline".
19090     FunctionDecl *Def = FD->getDefinition();
19091 
19092     return Def && !isDiscardableGVALinkage(
19093                       getASTContext().GetGVALinkageForFunction(Def));
19094   };
19095 
19096   if (LangOpts.OpenMPIsDevice) {
19097     // In OpenMP device mode we will not emit host only functions, or functions
19098     // we don't need due to their linkage.
19099     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19100         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19101     // DevTy may be changed later by
19102     //  #pragma omp declare target to(*) device_type(*).
19103     // Therefore DevTy having no value does not imply host. The emission status
19104     // will be checked again at the end of compilation unit with Final = true.
19105     if (DevTy)
19106       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19107         return FunctionEmissionStatus::OMPDiscarded;
19108     // If we have an explicit value for the device type, or we are in a target
19109     // declare context, we need to emit all extern and used symbols.
19110     if (isInOpenMPDeclareTargetContext() || DevTy)
19111       if (IsEmittedForExternalSymbol())
19112         return FunctionEmissionStatus::Emitted;
19113     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19114     // we'll omit it.
19115     if (Final)
19116       return FunctionEmissionStatus::OMPDiscarded;
19117   } else if (LangOpts.OpenMP > 45) {
19118     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19119     // function. In 5.0, no_host was introduced which might cause a function to
19120     // be ommitted.
19121     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19122         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19123     if (DevTy)
19124       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19125         return FunctionEmissionStatus::OMPDiscarded;
19126   }
19127 
19128   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19129     return FunctionEmissionStatus::Emitted;
19130 
19131   if (LangOpts.CUDA) {
19132     // When compiling for device, host functions are never emitted.  Similarly,
19133     // when compiling for host, device and global functions are never emitted.
19134     // (Technically, we do emit a host-side stub for global functions, but this
19135     // doesn't count for our purposes here.)
19136     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19137     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19138       return FunctionEmissionStatus::CUDADiscarded;
19139     if (!LangOpts.CUDAIsDevice &&
19140         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19141       return FunctionEmissionStatus::CUDADiscarded;
19142 
19143     if (IsEmittedForExternalSymbol())
19144       return FunctionEmissionStatus::Emitted;
19145   }
19146 
19147   // Otherwise, the function is known-emitted if it's in our set of
19148   // known-emitted functions.
19149   return FunctionEmissionStatus::Unknown;
19150 }
19151 
19152 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19153   // Host-side references to a __global__ function refer to the stub, so the
19154   // function itself is never emitted and therefore should not be marked.
19155   // If we have host fn calls kernel fn calls host+device, the HD function
19156   // does not get instantiated on the host. We model this by omitting at the
19157   // call to the kernel from the callgraph. This ensures that, when compiling
19158   // for host, only HD functions actually called from the host get marked as
19159   // known-emitted.
19160   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19161          IdentifyCUDATarget(Callee) == CFT_Global;
19162 }
19163