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->isPrivateModule())
1629     NewM = NewM->Parent;
1630   if (OldM && OldM->isPrivateModule())
1631     OldM = OldM->Parent;
1632 
1633   if (NewM == OldM)
1634     return false;
1635 
1636   // Partitions are part of the module, but a partition could import another
1637   // module, so verify that the PMIs agree.
1638   if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition()))
1639     return NewM->getPrimaryModuleInterfaceName() ==
1640            OldM->getPrimaryModuleInterfaceName();
1641 
1642   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1643   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1644   if (NewIsModuleInterface || OldIsModuleInterface) {
1645     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1646     //   if a declaration of D [...] appears in the purview of a module, all
1647     //   other such declarations shall appear in the purview of the same module
1648     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1649       << New
1650       << NewIsModuleInterface
1651       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1652       << OldIsModuleInterface
1653       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1654     Diag(Old->getLocation(), diag::note_previous_declaration);
1655     New->setInvalidDecl();
1656     return true;
1657   }
1658 
1659   return false;
1660 }
1661 
1662 // [module.interface]p6:
1663 // A redeclaration of an entity X is implicitly exported if X was introduced by
1664 // an exported declaration; otherwise it shall not be exported.
1665 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1666   // [module.interface]p1:
1667   // An export-declaration shall inhabit a namespace scope.
1668   //
1669   // So it is meaningless to talk about redeclaration which is not at namespace
1670   // scope.
1671   if (!New->getLexicalDeclContext()
1672            ->getNonTransparentContext()
1673            ->isFileContext() ||
1674       !Old->getLexicalDeclContext()
1675            ->getNonTransparentContext()
1676            ->isFileContext())
1677     return false;
1678 
1679   bool IsNewExported = New->isInExportDeclContext();
1680   bool IsOldExported = Old->isInExportDeclContext();
1681 
1682   // It should be irrevelant if both of them are not exported.
1683   if (!IsNewExported && !IsOldExported)
1684     return false;
1685 
1686   if (IsOldExported)
1687     return false;
1688 
1689   assert(IsNewExported);
1690 
1691   auto Lk = Old->getFormalLinkage();
1692   int S = 0;
1693   if (Lk == Linkage::InternalLinkage)
1694     S = 1;
1695   else if (Lk == Linkage::ModuleLinkage)
1696     S = 2;
1697   Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1698   Diag(Old->getLocation(), diag::note_previous_declaration);
1699   return true;
1700 }
1701 
1702 // A wrapper function for checking the semantic restrictions of
1703 // a redeclaration within a module.
1704 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1705   if (CheckRedeclarationModuleOwnership(New, Old))
1706     return true;
1707 
1708   if (CheckRedeclarationExported(New, Old))
1709     return true;
1710 
1711   return false;
1712 }
1713 
1714 static bool isUsingDecl(NamedDecl *D) {
1715   return isa<UsingShadowDecl>(D) ||
1716          isa<UnresolvedUsingTypenameDecl>(D) ||
1717          isa<UnresolvedUsingValueDecl>(D);
1718 }
1719 
1720 /// Removes using shadow declarations from the lookup results.
1721 static void RemoveUsingDecls(LookupResult &R) {
1722   LookupResult::Filter F = R.makeFilter();
1723   while (F.hasNext())
1724     if (isUsingDecl(F.next()))
1725       F.erase();
1726 
1727   F.done();
1728 }
1729 
1730 /// Check for this common pattern:
1731 /// @code
1732 /// class S {
1733 ///   S(const S&); // DO NOT IMPLEMENT
1734 ///   void operator=(const S&); // DO NOT IMPLEMENT
1735 /// };
1736 /// @endcode
1737 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1738   // FIXME: Should check for private access too but access is set after we get
1739   // the decl here.
1740   if (D->doesThisDeclarationHaveABody())
1741     return false;
1742 
1743   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1744     return CD->isCopyConstructor();
1745   return D->isCopyAssignmentOperator();
1746 }
1747 
1748 // We need this to handle
1749 //
1750 // typedef struct {
1751 //   void *foo() { return 0; }
1752 // } A;
1753 //
1754 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1755 // for example. If 'A', foo will have external linkage. If we have '*A',
1756 // foo will have no linkage. Since we can't know until we get to the end
1757 // of the typedef, this function finds out if D might have non-external linkage.
1758 // Callers should verify at the end of the TU if it D has external linkage or
1759 // not.
1760 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1761   const DeclContext *DC = D->getDeclContext();
1762   while (!DC->isTranslationUnit()) {
1763     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1764       if (!RD->hasNameForLinkage())
1765         return true;
1766     }
1767     DC = DC->getParent();
1768   }
1769 
1770   return !D->isExternallyVisible();
1771 }
1772 
1773 // FIXME: This needs to be refactored; some other isInMainFile users want
1774 // these semantics.
1775 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1776   if (S.TUKind != TU_Complete)
1777     return false;
1778   return S.SourceMgr.isInMainFile(Loc);
1779 }
1780 
1781 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1782   assert(D);
1783 
1784   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1785     return false;
1786 
1787   // Ignore all entities declared within templates, and out-of-line definitions
1788   // of members of class templates.
1789   if (D->getDeclContext()->isDependentContext() ||
1790       D->getLexicalDeclContext()->isDependentContext())
1791     return false;
1792 
1793   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1794     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1795       return false;
1796     // A non-out-of-line declaration of a member specialization was implicitly
1797     // instantiated; it's the out-of-line declaration that we're interested in.
1798     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1799         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1800       return false;
1801 
1802     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1803       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1804         return false;
1805     } else {
1806       // 'static inline' functions are defined in headers; don't warn.
1807       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1808         return false;
1809     }
1810 
1811     if (FD->doesThisDeclarationHaveABody() &&
1812         Context.DeclMustBeEmitted(FD))
1813       return false;
1814   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1815     // Constants and utility variables are defined in headers with internal
1816     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1817     // like "inline".)
1818     if (!isMainFileLoc(*this, VD->getLocation()))
1819       return false;
1820 
1821     if (Context.DeclMustBeEmitted(VD))
1822       return false;
1823 
1824     if (VD->isStaticDataMember() &&
1825         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1826       return false;
1827     if (VD->isStaticDataMember() &&
1828         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1829         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1830       return false;
1831 
1832     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1833       return false;
1834   } else {
1835     return false;
1836   }
1837 
1838   // Only warn for unused decls internal to the translation unit.
1839   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1840   // for inline functions defined in the main source file, for instance.
1841   return mightHaveNonExternalLinkage(D);
1842 }
1843 
1844 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1845   if (!D)
1846     return;
1847 
1848   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1849     const FunctionDecl *First = FD->getFirstDecl();
1850     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1851       return; // First should already be in the vector.
1852   }
1853 
1854   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1855     const VarDecl *First = VD->getFirstDecl();
1856     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1857       return; // First should already be in the vector.
1858   }
1859 
1860   if (ShouldWarnIfUnusedFileScopedDecl(D))
1861     UnusedFileScopedDecls.push_back(D);
1862 }
1863 
1864 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1865   if (D->isInvalidDecl())
1866     return false;
1867 
1868   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1869     // For a decomposition declaration, warn if none of the bindings are
1870     // referenced, instead of if the variable itself is referenced (which
1871     // it is, by the bindings' expressions).
1872     for (auto *BD : DD->bindings())
1873       if (BD->isReferenced())
1874         return false;
1875   } else if (!D->getDeclName()) {
1876     return false;
1877   } else if (D->isReferenced() || D->isUsed()) {
1878     return false;
1879   }
1880 
1881   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1882     return false;
1883 
1884   if (isa<LabelDecl>(D))
1885     return true;
1886 
1887   // Except for labels, we only care about unused decls that are local to
1888   // functions.
1889   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1890   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1891     // For dependent types, the diagnostic is deferred.
1892     WithinFunction =
1893         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1894   if (!WithinFunction)
1895     return false;
1896 
1897   if (isa<TypedefNameDecl>(D))
1898     return true;
1899 
1900   // White-list anything that isn't a local variable.
1901   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1902     return false;
1903 
1904   // Types of valid local variables should be complete, so this should succeed.
1905   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906 
1907     const Expr *Init = VD->getInit();
1908     if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
1909       Init = Cleanups->getSubExpr();
1910 
1911     const auto *Ty = VD->getType().getTypePtr();
1912 
1913     // Only look at the outermost level of typedef.
1914     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1915       // Allow anything marked with __attribute__((unused)).
1916       if (TT->getDecl()->hasAttr<UnusedAttr>())
1917         return false;
1918     }
1919 
1920     // Warn for reference variables whose initializtion performs lifetime
1921     // extension.
1922     if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
1923       if (MTE->getExtendingDecl()) {
1924         Ty = VD->getType().getNonReferenceType().getTypePtr();
1925         Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1926       }
1927     }
1928 
1929     // If we failed to complete the type for some reason, or if the type is
1930     // dependent, don't diagnose the variable.
1931     if (Ty->isIncompleteType() || Ty->isDependentType())
1932       return false;
1933 
1934     // Look at the element type to ensure that the warning behaviour is
1935     // consistent for both scalars and arrays.
1936     Ty = Ty->getBaseElementTypeUnsafe();
1937 
1938     if (const TagType *TT = Ty->getAs<TagType>()) {
1939       const TagDecl *Tag = TT->getDecl();
1940       if (Tag->hasAttr<UnusedAttr>())
1941         return false;
1942 
1943       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1944         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1945           return false;
1946 
1947         if (Init) {
1948           const CXXConstructExpr *Construct =
1949             dyn_cast<CXXConstructExpr>(Init);
1950           if (Construct && !Construct->isElidable()) {
1951             CXXConstructorDecl *CD = Construct->getConstructor();
1952             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1953                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1954               return false;
1955           }
1956 
1957           // Suppress the warning if we don't know how this is constructed, and
1958           // it could possibly be non-trivial constructor.
1959           if (Init->isTypeDependent()) {
1960             for (const CXXConstructorDecl *Ctor : RD->ctors())
1961               if (!Ctor->isTrivial())
1962                 return false;
1963           }
1964 
1965           // Suppress the warning if the constructor is unresolved because
1966           // its arguments are dependent.
1967           if (isa<CXXUnresolvedConstructExpr>(Init))
1968             return false;
1969         }
1970       }
1971     }
1972 
1973     // TODO: __attribute__((unused)) templates?
1974   }
1975 
1976   return true;
1977 }
1978 
1979 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1980                                      FixItHint &Hint) {
1981   if (isa<LabelDecl>(D)) {
1982     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1983         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1984         true);
1985     if (AfterColon.isInvalid())
1986       return;
1987     Hint = FixItHint::CreateRemoval(
1988         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1989   }
1990 }
1991 
1992 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1993   if (D->getTypeForDecl()->isDependentType())
1994     return;
1995 
1996   for (auto *TmpD : D->decls()) {
1997     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1998       DiagnoseUnusedDecl(T);
1999     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2000       DiagnoseUnusedNestedTypedefs(R);
2001   }
2002 }
2003 
2004 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2005 /// unless they are marked attr(unused).
2006 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2007   if (!ShouldDiagnoseUnusedDecl(D))
2008     return;
2009 
2010   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2011     // typedefs can be referenced later on, so the diagnostics are emitted
2012     // at end-of-translation-unit.
2013     UnusedLocalTypedefNameCandidates.insert(TD);
2014     return;
2015   }
2016 
2017   FixItHint Hint;
2018   GenerateFixForUnusedDecl(D, Context, Hint);
2019 
2020   unsigned DiagID;
2021   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2022     DiagID = diag::warn_unused_exception_param;
2023   else if (isa<LabelDecl>(D))
2024     DiagID = diag::warn_unused_label;
2025   else
2026     DiagID = diag::warn_unused_variable;
2027 
2028   Diag(D->getLocation(), DiagID) << D << Hint;
2029 }
2030 
2031 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
2032   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2033   // it's not really unused.
2034   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2035       VD->hasAttr<CleanupAttr>())
2036     return;
2037 
2038   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2039 
2040   if (Ty->isReferenceType() || Ty->isDependentType())
2041     return;
2042 
2043   if (const TagType *TT = Ty->getAs<TagType>()) {
2044     const TagDecl *Tag = TT->getDecl();
2045     if (Tag->hasAttr<UnusedAttr>())
2046       return;
2047     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2048     // mimic gcc's behavior.
2049     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2050       if (!RD->hasAttr<WarnUnusedAttr>())
2051         return;
2052     }
2053   }
2054 
2055   // Don't warn about __block Objective-C pointer variables, as they might
2056   // be assigned in the block but not used elsewhere for the purpose of lifetime
2057   // extension.
2058   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2059     return;
2060 
2061   // Don't warn about Objective-C pointer variables with precise lifetime
2062   // semantics; they can be used to ensure ARC releases the object at a known
2063   // time, which may mean assignment but no other references.
2064   if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2065     return;
2066 
2067   auto iter = RefsMinusAssignments.find(VD);
2068   if (iter == RefsMinusAssignments.end())
2069     return;
2070 
2071   assert(iter->getSecond() >= 0 &&
2072          "Found a negative number of references to a VarDecl");
2073   if (iter->getSecond() != 0)
2074     return;
2075   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2076                                          : diag::warn_unused_but_set_variable;
2077   Diag(VD->getLocation(), DiagID) << VD;
2078 }
2079 
2080 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2081   // Verify that we have no forward references left.  If so, there was a goto
2082   // or address of a label taken, but no definition of it.  Label fwd
2083   // definitions are indicated with a null substmt which is also not a resolved
2084   // MS inline assembly label name.
2085   bool Diagnose = false;
2086   if (L->isMSAsmLabel())
2087     Diagnose = !L->isResolvedMSAsmLabel();
2088   else
2089     Diagnose = L->getStmt() == nullptr;
2090   if (Diagnose)
2091     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2092 }
2093 
2094 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2095   S->mergeNRVOIntoParent();
2096 
2097   if (S->decl_empty()) return;
2098   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2099          "Scope shouldn't contain decls!");
2100 
2101   for (auto *TmpD : S->decls()) {
2102     assert(TmpD && "This decl didn't get pushed??");
2103 
2104     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2105     NamedDecl *D = cast<NamedDecl>(TmpD);
2106 
2107     // Diagnose unused variables in this scope.
2108     if (!S->hasUnrecoverableErrorOccurred()) {
2109       DiagnoseUnusedDecl(D);
2110       if (const auto *RD = dyn_cast<RecordDecl>(D))
2111         DiagnoseUnusedNestedTypedefs(RD);
2112       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2113         DiagnoseUnusedButSetDecl(VD);
2114         RefsMinusAssignments.erase(VD);
2115       }
2116     }
2117 
2118     if (!D->getDeclName()) continue;
2119 
2120     // If this was a forward reference to a label, verify it was defined.
2121     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2122       CheckPoppedLabel(LD, *this);
2123 
2124     // Remove this name from our lexical scope, and warn on it if we haven't
2125     // already.
2126     IdResolver.RemoveDecl(D);
2127     auto ShadowI = ShadowingDecls.find(D);
2128     if (ShadowI != ShadowingDecls.end()) {
2129       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2130         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2131             << D << FD << FD->getParent();
2132         Diag(FD->getLocation(), diag::note_previous_declaration);
2133       }
2134       ShadowingDecls.erase(ShadowI);
2135     }
2136   }
2137 }
2138 
2139 /// Look for an Objective-C class in the translation unit.
2140 ///
2141 /// \param Id The name of the Objective-C class we're looking for. If
2142 /// typo-correction fixes this name, the Id will be updated
2143 /// to the fixed name.
2144 ///
2145 /// \param IdLoc The location of the name in the translation unit.
2146 ///
2147 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2148 /// if there is no class with the given name.
2149 ///
2150 /// \returns The declaration of the named Objective-C class, or NULL if the
2151 /// class could not be found.
2152 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2153                                               SourceLocation IdLoc,
2154                                               bool DoTypoCorrection) {
2155   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2156   // creation from this context.
2157   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2158 
2159   if (!IDecl && DoTypoCorrection) {
2160     // Perform typo correction at the given location, but only if we
2161     // find an Objective-C class name.
2162     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2163     if (TypoCorrection C =
2164             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2165                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2166       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2167       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2168       Id = IDecl->getIdentifier();
2169     }
2170   }
2171   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2172   // This routine must always return a class definition, if any.
2173   if (Def && Def->getDefinition())
2174       Def = Def->getDefinition();
2175   return Def;
2176 }
2177 
2178 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2179 /// from S, where a non-field would be declared. This routine copes
2180 /// with the difference between C and C++ scoping rules in structs and
2181 /// unions. For example, the following code is well-formed in C but
2182 /// ill-formed in C++:
2183 /// @code
2184 /// struct S6 {
2185 ///   enum { BAR } e;
2186 /// };
2187 ///
2188 /// void test_S6() {
2189 ///   struct S6 a;
2190 ///   a.e = BAR;
2191 /// }
2192 /// @endcode
2193 /// For the declaration of BAR, this routine will return a different
2194 /// scope. The scope S will be the scope of the unnamed enumeration
2195 /// within S6. In C++, this routine will return the scope associated
2196 /// with S6, because the enumeration's scope is a transparent
2197 /// context but structures can contain non-field names. In C, this
2198 /// routine will return the translation unit scope, since the
2199 /// enumeration's scope is a transparent context and structures cannot
2200 /// contain non-field names.
2201 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2202   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2203          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2204          (S->isClassScope() && !getLangOpts().CPlusPlus))
2205     S = S->getParent();
2206   return S;
2207 }
2208 
2209 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2210                                ASTContext::GetBuiltinTypeError Error) {
2211   switch (Error) {
2212   case ASTContext::GE_None:
2213     return "";
2214   case ASTContext::GE_Missing_type:
2215     return BuiltinInfo.getHeaderName(ID);
2216   case ASTContext::GE_Missing_stdio:
2217     return "stdio.h";
2218   case ASTContext::GE_Missing_setjmp:
2219     return "setjmp.h";
2220   case ASTContext::GE_Missing_ucontext:
2221     return "ucontext.h";
2222   }
2223   llvm_unreachable("unhandled error kind");
2224 }
2225 
2226 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2227                                   unsigned ID, SourceLocation Loc) {
2228   DeclContext *Parent = Context.getTranslationUnitDecl();
2229 
2230   if (getLangOpts().CPlusPlus) {
2231     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2232         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2233     CLinkageDecl->setImplicit();
2234     Parent->addDecl(CLinkageDecl);
2235     Parent = CLinkageDecl;
2236   }
2237 
2238   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2239                                            /*TInfo=*/nullptr, SC_Extern,
2240                                            getCurFPFeatures().isFPConstrained(),
2241                                            false, Type->isFunctionProtoType());
2242   New->setImplicit();
2243   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2244 
2245   // Create Decl objects for each parameter, adding them to the
2246   // FunctionDecl.
2247   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2248     SmallVector<ParmVarDecl *, 16> Params;
2249     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2250       ParmVarDecl *parm = ParmVarDecl::Create(
2251           Context, New, SourceLocation(), SourceLocation(), nullptr,
2252           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2253       parm->setScopeInfo(0, i);
2254       Params.push_back(parm);
2255     }
2256     New->setParams(Params);
2257   }
2258 
2259   AddKnownFunctionAttributes(New);
2260   return New;
2261 }
2262 
2263 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2264 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2265 /// if we're creating this built-in in anticipation of redeclaring the
2266 /// built-in.
2267 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2268                                      Scope *S, bool ForRedeclaration,
2269                                      SourceLocation Loc) {
2270   LookupNecessaryTypesForBuiltin(S, ID);
2271 
2272   ASTContext::GetBuiltinTypeError Error;
2273   QualType R = Context.GetBuiltinType(ID, Error);
2274   if (Error) {
2275     if (!ForRedeclaration)
2276       return nullptr;
2277 
2278     // If we have a builtin without an associated type we should not emit a
2279     // warning when we were not able to find a type for it.
2280     if (Error == ASTContext::GE_Missing_type ||
2281         Context.BuiltinInfo.allowTypeMismatch(ID))
2282       return nullptr;
2283 
2284     // If we could not find a type for setjmp it is because the jmp_buf type was
2285     // not defined prior to the setjmp declaration.
2286     if (Error == ASTContext::GE_Missing_setjmp) {
2287       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2288           << Context.BuiltinInfo.getName(ID);
2289       return nullptr;
2290     }
2291 
2292     // Generally, we emit a warning that the declaration requires the
2293     // appropriate header.
2294     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2295         << getHeaderName(Context.BuiltinInfo, ID, Error)
2296         << Context.BuiltinInfo.getName(ID);
2297     return nullptr;
2298   }
2299 
2300   if (!ForRedeclaration &&
2301       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2302        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2303     Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2304                            : diag::ext_implicit_lib_function_decl)
2305         << Context.BuiltinInfo.getName(ID) << R;
2306     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2307       Diag(Loc, diag::note_include_header_or_declare)
2308           << Header << Context.BuiltinInfo.getName(ID);
2309   }
2310 
2311   if (R.isNull())
2312     return nullptr;
2313 
2314   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2315   RegisterLocallyScopedExternCDecl(New, S);
2316 
2317   // TUScope is the translation-unit scope to insert this function into.
2318   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2319   // relate Scopes to DeclContexts, and probably eliminate CurContext
2320   // entirely, but we're not there yet.
2321   DeclContext *SavedContext = CurContext;
2322   CurContext = New->getDeclContext();
2323   PushOnScopeChains(New, TUScope);
2324   CurContext = SavedContext;
2325   return New;
2326 }
2327 
2328 /// Typedef declarations don't have linkage, but they still denote the same
2329 /// entity if their types are the same.
2330 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2331 /// isSameEntity.
2332 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2333                                                      TypedefNameDecl *Decl,
2334                                                      LookupResult &Previous) {
2335   // This is only interesting when modules are enabled.
2336   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2337     return;
2338 
2339   // Empty sets are uninteresting.
2340   if (Previous.empty())
2341     return;
2342 
2343   LookupResult::Filter Filter = Previous.makeFilter();
2344   while (Filter.hasNext()) {
2345     NamedDecl *Old = Filter.next();
2346 
2347     // Non-hidden declarations are never ignored.
2348     if (S.isVisible(Old))
2349       continue;
2350 
2351     // Declarations of the same entity are not ignored, even if they have
2352     // different linkages.
2353     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2354       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2355                                 Decl->getUnderlyingType()))
2356         continue;
2357 
2358       // If both declarations give a tag declaration a typedef name for linkage
2359       // purposes, then they declare the same entity.
2360       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2361           Decl->getAnonDeclWithTypedefName())
2362         continue;
2363     }
2364 
2365     Filter.erase();
2366   }
2367 
2368   Filter.done();
2369 }
2370 
2371 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2372   QualType OldType;
2373   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2374     OldType = OldTypedef->getUnderlyingType();
2375   else
2376     OldType = Context.getTypeDeclType(Old);
2377   QualType NewType = New->getUnderlyingType();
2378 
2379   if (NewType->isVariablyModifiedType()) {
2380     // Must not redefine a typedef with a variably-modified type.
2381     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2382     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2383       << Kind << NewType;
2384     if (Old->getLocation().isValid())
2385       notePreviousDefinition(Old, New->getLocation());
2386     New->setInvalidDecl();
2387     return true;
2388   }
2389 
2390   if (OldType != NewType &&
2391       !OldType->isDependentType() &&
2392       !NewType->isDependentType() &&
2393       !Context.hasSameType(OldType, NewType)) {
2394     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2395     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2396       << Kind << NewType << OldType;
2397     if (Old->getLocation().isValid())
2398       notePreviousDefinition(Old, New->getLocation());
2399     New->setInvalidDecl();
2400     return true;
2401   }
2402   return false;
2403 }
2404 
2405 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2406 /// same name and scope as a previous declaration 'Old'.  Figure out
2407 /// how to resolve this situation, merging decls or emitting
2408 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2409 ///
2410 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2411                                 LookupResult &OldDecls) {
2412   // If the new decl is known invalid already, don't bother doing any
2413   // merging checks.
2414   if (New->isInvalidDecl()) return;
2415 
2416   // Allow multiple definitions for ObjC built-in typedefs.
2417   // FIXME: Verify the underlying types are equivalent!
2418   if (getLangOpts().ObjC) {
2419     const IdentifierInfo *TypeID = New->getIdentifier();
2420     switch (TypeID->getLength()) {
2421     default: break;
2422     case 2:
2423       {
2424         if (!TypeID->isStr("id"))
2425           break;
2426         QualType T = New->getUnderlyingType();
2427         if (!T->isPointerType())
2428           break;
2429         if (!T->isVoidPointerType()) {
2430           QualType PT = T->castAs<PointerType>()->getPointeeType();
2431           if (!PT->isStructureType())
2432             break;
2433         }
2434         Context.setObjCIdRedefinitionType(T);
2435         // Install the built-in type for 'id', ignoring the current definition.
2436         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2437         return;
2438       }
2439     case 5:
2440       if (!TypeID->isStr("Class"))
2441         break;
2442       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2443       // Install the built-in type for 'Class', ignoring the current definition.
2444       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2445       return;
2446     case 3:
2447       if (!TypeID->isStr("SEL"))
2448         break;
2449       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2450       // Install the built-in type for 'SEL', ignoring the current definition.
2451       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2452       return;
2453     }
2454     // Fall through - the typedef name was not a builtin type.
2455   }
2456 
2457   // Verify the old decl was also a type.
2458   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2459   if (!Old) {
2460     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2461       << New->getDeclName();
2462 
2463     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2464     if (OldD->getLocation().isValid())
2465       notePreviousDefinition(OldD, New->getLocation());
2466 
2467     return New->setInvalidDecl();
2468   }
2469 
2470   // If the old declaration is invalid, just give up here.
2471   if (Old->isInvalidDecl())
2472     return New->setInvalidDecl();
2473 
2474   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2475     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2476     auto *NewTag = New->getAnonDeclWithTypedefName();
2477     NamedDecl *Hidden = nullptr;
2478     if (OldTag && NewTag &&
2479         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2480         !hasVisibleDefinition(OldTag, &Hidden)) {
2481       // There is a definition of this tag, but it is not visible. Use it
2482       // instead of our tag.
2483       New->setTypeForDecl(OldTD->getTypeForDecl());
2484       if (OldTD->isModed())
2485         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2486                                     OldTD->getUnderlyingType());
2487       else
2488         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2489 
2490       // Make the old tag definition visible.
2491       makeMergedDefinitionVisible(Hidden);
2492 
2493       // If this was an unscoped enumeration, yank all of its enumerators
2494       // out of the scope.
2495       if (isa<EnumDecl>(NewTag)) {
2496         Scope *EnumScope = getNonFieldDeclScope(S);
2497         for (auto *D : NewTag->decls()) {
2498           auto *ED = cast<EnumConstantDecl>(D);
2499           assert(EnumScope->isDeclScope(ED));
2500           EnumScope->RemoveDecl(ED);
2501           IdResolver.RemoveDecl(ED);
2502           ED->getLexicalDeclContext()->removeDecl(ED);
2503         }
2504       }
2505     }
2506   }
2507 
2508   // If the typedef types are not identical, reject them in all languages and
2509   // with any extensions enabled.
2510   if (isIncompatibleTypedef(Old, New))
2511     return;
2512 
2513   // The types match.  Link up the redeclaration chain and merge attributes if
2514   // the old declaration was a typedef.
2515   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2516     New->setPreviousDecl(Typedef);
2517     mergeDeclAttributes(New, Old);
2518   }
2519 
2520   if (getLangOpts().MicrosoftExt)
2521     return;
2522 
2523   if (getLangOpts().CPlusPlus) {
2524     // C++ [dcl.typedef]p2:
2525     //   In a given non-class scope, a typedef specifier can be used to
2526     //   redefine the name of any type declared in that scope to refer
2527     //   to the type to which it already refers.
2528     if (!isa<CXXRecordDecl>(CurContext))
2529       return;
2530 
2531     // C++0x [dcl.typedef]p4:
2532     //   In a given class scope, a typedef specifier can be used to redefine
2533     //   any class-name declared in that scope that is not also a typedef-name
2534     //   to refer to the type to which it already refers.
2535     //
2536     // This wording came in via DR424, which was a correction to the
2537     // wording in DR56, which accidentally banned code like:
2538     //
2539     //   struct S {
2540     //     typedef struct A { } A;
2541     //   };
2542     //
2543     // in the C++03 standard. We implement the C++0x semantics, which
2544     // allow the above but disallow
2545     //
2546     //   struct S {
2547     //     typedef int I;
2548     //     typedef int I;
2549     //   };
2550     //
2551     // since that was the intent of DR56.
2552     if (!isa<TypedefNameDecl>(Old))
2553       return;
2554 
2555     Diag(New->getLocation(), diag::err_redefinition)
2556       << New->getDeclName();
2557     notePreviousDefinition(Old, New->getLocation());
2558     return New->setInvalidDecl();
2559   }
2560 
2561   // Modules always permit redefinition of typedefs, as does C11.
2562   if (getLangOpts().Modules || getLangOpts().C11)
2563     return;
2564 
2565   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2566   // is normally mapped to an error, but can be controlled with
2567   // -Wtypedef-redefinition.  If either the original or the redefinition is
2568   // in a system header, don't emit this for compatibility with GCC.
2569   if (getDiagnostics().getSuppressSystemWarnings() &&
2570       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2571       (Old->isImplicit() ||
2572        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2573        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2574     return;
2575 
2576   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2577     << New->getDeclName();
2578   notePreviousDefinition(Old, New->getLocation());
2579 }
2580 
2581 /// DeclhasAttr - returns true if decl Declaration already has the target
2582 /// attribute.
2583 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2584   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2585   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2586   for (const auto *i : D->attrs())
2587     if (i->getKind() == A->getKind()) {
2588       if (Ann) {
2589         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2590           return true;
2591         continue;
2592       }
2593       // FIXME: Don't hardcode this check
2594       if (OA && isa<OwnershipAttr>(i))
2595         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2596       return true;
2597     }
2598 
2599   return false;
2600 }
2601 
2602 static bool isAttributeTargetADefinition(Decl *D) {
2603   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2604     return VD->isThisDeclarationADefinition();
2605   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2606     return TD->isCompleteDefinition() || TD->isBeingDefined();
2607   return true;
2608 }
2609 
2610 /// Merge alignment attributes from \p Old to \p New, taking into account the
2611 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2612 ///
2613 /// \return \c true if any attributes were added to \p New.
2614 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2615   // Look for alignas attributes on Old, and pick out whichever attribute
2616   // specifies the strictest alignment requirement.
2617   AlignedAttr *OldAlignasAttr = nullptr;
2618   AlignedAttr *OldStrictestAlignAttr = nullptr;
2619   unsigned OldAlign = 0;
2620   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2621     // FIXME: We have no way of representing inherited dependent alignments
2622     // in a case like:
2623     //   template<int A, int B> struct alignas(A) X;
2624     //   template<int A, int B> struct alignas(B) X {};
2625     // For now, we just ignore any alignas attributes which are not on the
2626     // definition in such a case.
2627     if (I->isAlignmentDependent())
2628       return false;
2629 
2630     if (I->isAlignas())
2631       OldAlignasAttr = I;
2632 
2633     unsigned Align = I->getAlignment(S.Context);
2634     if (Align > OldAlign) {
2635       OldAlign = Align;
2636       OldStrictestAlignAttr = I;
2637     }
2638   }
2639 
2640   // Look for alignas attributes on New.
2641   AlignedAttr *NewAlignasAttr = nullptr;
2642   unsigned NewAlign = 0;
2643   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2644     if (I->isAlignmentDependent())
2645       return false;
2646 
2647     if (I->isAlignas())
2648       NewAlignasAttr = I;
2649 
2650     unsigned Align = I->getAlignment(S.Context);
2651     if (Align > NewAlign)
2652       NewAlign = Align;
2653   }
2654 
2655   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2656     // Both declarations have 'alignas' attributes. We require them to match.
2657     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2658     // fall short. (If two declarations both have alignas, they must both match
2659     // every definition, and so must match each other if there is a definition.)
2660 
2661     // If either declaration only contains 'alignas(0)' specifiers, then it
2662     // specifies the natural alignment for the type.
2663     if (OldAlign == 0 || NewAlign == 0) {
2664       QualType Ty;
2665       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2666         Ty = VD->getType();
2667       else
2668         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2669 
2670       if (OldAlign == 0)
2671         OldAlign = S.Context.getTypeAlign(Ty);
2672       if (NewAlign == 0)
2673         NewAlign = S.Context.getTypeAlign(Ty);
2674     }
2675 
2676     if (OldAlign != NewAlign) {
2677       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2678         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2679         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2680       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2681     }
2682   }
2683 
2684   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2685     // C++11 [dcl.align]p6:
2686     //   if any declaration of an entity has an alignment-specifier,
2687     //   every defining declaration of that entity shall specify an
2688     //   equivalent alignment.
2689     // C11 6.7.5/7:
2690     //   If the definition of an object does not have an alignment
2691     //   specifier, any other declaration of that object shall also
2692     //   have no alignment specifier.
2693     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2694       << OldAlignasAttr;
2695     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2696       << OldAlignasAttr;
2697   }
2698 
2699   bool AnyAdded = false;
2700 
2701   // Ensure we have an attribute representing the strictest alignment.
2702   if (OldAlign > NewAlign) {
2703     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2704     Clone->setInherited(true);
2705     New->addAttr(Clone);
2706     AnyAdded = true;
2707   }
2708 
2709   // Ensure we have an alignas attribute if the old declaration had one.
2710   if (OldAlignasAttr && !NewAlignasAttr &&
2711       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2712     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2713     Clone->setInherited(true);
2714     New->addAttr(Clone);
2715     AnyAdded = true;
2716   }
2717 
2718   return AnyAdded;
2719 }
2720 
2721 #define WANT_DECL_MERGE_LOGIC
2722 #include "clang/Sema/AttrParsedAttrImpl.inc"
2723 #undef WANT_DECL_MERGE_LOGIC
2724 
2725 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2726                                const InheritableAttr *Attr,
2727                                Sema::AvailabilityMergeKind AMK) {
2728   // Diagnose any mutual exclusions between the attribute that we want to add
2729   // and attributes that already exist on the declaration.
2730   if (!DiagnoseMutualExclusions(S, D, Attr))
2731     return false;
2732 
2733   // This function copies an attribute Attr from a previous declaration to the
2734   // new declaration D if the new declaration doesn't itself have that attribute
2735   // yet or if that attribute allows duplicates.
2736   // If you're adding a new attribute that requires logic different from
2737   // "use explicit attribute on decl if present, else use attribute from
2738   // previous decl", for example if the attribute needs to be consistent
2739   // between redeclarations, you need to call a custom merge function here.
2740   InheritableAttr *NewAttr = nullptr;
2741   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2742     NewAttr = S.mergeAvailabilityAttr(
2743         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2744         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2745         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2746         AA->getPriority());
2747   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2748     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2749   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2750     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2751   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2752     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2753   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2754     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2755   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2756     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2757   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2758     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2759                                 FA->getFirstArg());
2760   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2761     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2762   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2763     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2764   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2765     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2766                                        IA->getInheritanceModel());
2767   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2768     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2769                                       &S.Context.Idents.get(AA->getSpelling()));
2770   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2771            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2772             isa<CUDAGlobalAttr>(Attr))) {
2773     // CUDA target attributes are part of function signature for
2774     // overloading purposes and must not be merged.
2775     return false;
2776   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2777     NewAttr = S.mergeMinSizeAttr(D, *MA);
2778   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2779     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2780   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2781     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2782   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2783     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2784   else if (isa<AlignedAttr>(Attr))
2785     // AlignedAttrs are handled separately, because we need to handle all
2786     // such attributes on a declaration at the same time.
2787     NewAttr = nullptr;
2788   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2789            (AMK == Sema::AMK_Override ||
2790             AMK == Sema::AMK_ProtocolImplementation ||
2791             AMK == Sema::AMK_OptionalProtocolImplementation))
2792     NewAttr = nullptr;
2793   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2794     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2795   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2796     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2797   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2798     NewAttr = S.mergeImportNameAttr(D, *INA);
2799   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2800     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2801   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2802     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2803   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2804     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2805   else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2806     NewAttr =
2807         S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2808   else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2809     NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2810   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2811     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2812 
2813   if (NewAttr) {
2814     NewAttr->setInherited(true);
2815     D->addAttr(NewAttr);
2816     if (isa<MSInheritanceAttr>(NewAttr))
2817       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2818     return true;
2819   }
2820 
2821   return false;
2822 }
2823 
2824 static const NamedDecl *getDefinition(const Decl *D) {
2825   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2826     return TD->getDefinition();
2827   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2828     const VarDecl *Def = VD->getDefinition();
2829     if (Def)
2830       return Def;
2831     return VD->getActingDefinition();
2832   }
2833   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2834     const FunctionDecl *Def = nullptr;
2835     if (FD->isDefined(Def, true))
2836       return Def;
2837   }
2838   return nullptr;
2839 }
2840 
2841 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2842   for (const auto *Attribute : D->attrs())
2843     if (Attribute->getKind() == Kind)
2844       return true;
2845   return false;
2846 }
2847 
2848 /// checkNewAttributesAfterDef - If we already have a definition, check that
2849 /// there are no new attributes in this declaration.
2850 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2851   if (!New->hasAttrs())
2852     return;
2853 
2854   const NamedDecl *Def = getDefinition(Old);
2855   if (!Def || Def == New)
2856     return;
2857 
2858   AttrVec &NewAttributes = New->getAttrs();
2859   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2860     const Attr *NewAttribute = NewAttributes[I];
2861 
2862     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2863       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2864         Sema::SkipBodyInfo SkipBody;
2865         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2866 
2867         // If we're skipping this definition, drop the "alias" attribute.
2868         if (SkipBody.ShouldSkip) {
2869           NewAttributes.erase(NewAttributes.begin() + I);
2870           --E;
2871           continue;
2872         }
2873       } else {
2874         VarDecl *VD = cast<VarDecl>(New);
2875         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2876                                 VarDecl::TentativeDefinition
2877                             ? diag::err_alias_after_tentative
2878                             : diag::err_redefinition;
2879         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2880         if (Diag == diag::err_redefinition)
2881           S.notePreviousDefinition(Def, VD->getLocation());
2882         else
2883           S.Diag(Def->getLocation(), diag::note_previous_definition);
2884         VD->setInvalidDecl();
2885       }
2886       ++I;
2887       continue;
2888     }
2889 
2890     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2891       // Tentative definitions are only interesting for the alias check above.
2892       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2893         ++I;
2894         continue;
2895       }
2896     }
2897 
2898     if (hasAttribute(Def, NewAttribute->getKind())) {
2899       ++I;
2900       continue; // regular attr merging will take care of validating this.
2901     }
2902 
2903     if (isa<C11NoReturnAttr>(NewAttribute)) {
2904       // C's _Noreturn is allowed to be added to a function after it is defined.
2905       ++I;
2906       continue;
2907     } else if (isa<UuidAttr>(NewAttribute)) {
2908       // msvc will allow a subsequent definition to add an uuid to a class
2909       ++I;
2910       continue;
2911     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2912       if (AA->isAlignas()) {
2913         // C++11 [dcl.align]p6:
2914         //   if any declaration of an entity has an alignment-specifier,
2915         //   every defining declaration of that entity shall specify an
2916         //   equivalent alignment.
2917         // C11 6.7.5/7:
2918         //   If the definition of an object does not have an alignment
2919         //   specifier, any other declaration of that object shall also
2920         //   have no alignment specifier.
2921         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2922           << AA;
2923         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2924           << AA;
2925         NewAttributes.erase(NewAttributes.begin() + I);
2926         --E;
2927         continue;
2928       }
2929     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2930       // If there is a C definition followed by a redeclaration with this
2931       // attribute then there are two different definitions. In C++, prefer the
2932       // standard diagnostics.
2933       if (!S.getLangOpts().CPlusPlus) {
2934         S.Diag(NewAttribute->getLocation(),
2935                diag::err_loader_uninitialized_redeclaration);
2936         S.Diag(Def->getLocation(), diag::note_previous_definition);
2937         NewAttributes.erase(NewAttributes.begin() + I);
2938         --E;
2939         continue;
2940       }
2941     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2942                cast<VarDecl>(New)->isInline() &&
2943                !cast<VarDecl>(New)->isInlineSpecified()) {
2944       // Don't warn about applying selectany to implicitly inline variables.
2945       // Older compilers and language modes would require the use of selectany
2946       // to make such variables inline, and it would have no effect if we
2947       // honored it.
2948       ++I;
2949       continue;
2950     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2951       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2952       // declarations after defintions.
2953       ++I;
2954       continue;
2955     }
2956 
2957     S.Diag(NewAttribute->getLocation(),
2958            diag::warn_attribute_precede_definition);
2959     S.Diag(Def->getLocation(), diag::note_previous_definition);
2960     NewAttributes.erase(NewAttributes.begin() + I);
2961     --E;
2962   }
2963 }
2964 
2965 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2966                                      const ConstInitAttr *CIAttr,
2967                                      bool AttrBeforeInit) {
2968   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2969 
2970   // Figure out a good way to write this specifier on the old declaration.
2971   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2972   // enough of the attribute list spelling information to extract that without
2973   // heroics.
2974   std::string SuitableSpelling;
2975   if (S.getLangOpts().CPlusPlus20)
2976     SuitableSpelling = std::string(
2977         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2978   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2979     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2980         InsertLoc, {tok::l_square, tok::l_square,
2981                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2982                     S.PP.getIdentifierInfo("require_constant_initialization"),
2983                     tok::r_square, tok::r_square}));
2984   if (SuitableSpelling.empty())
2985     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2986         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2987                     S.PP.getIdentifierInfo("require_constant_initialization"),
2988                     tok::r_paren, tok::r_paren}));
2989   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2990     SuitableSpelling = "constinit";
2991   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2992     SuitableSpelling = "[[clang::require_constant_initialization]]";
2993   if (SuitableSpelling.empty())
2994     SuitableSpelling = "__attribute__((require_constant_initialization))";
2995   SuitableSpelling += " ";
2996 
2997   if (AttrBeforeInit) {
2998     // extern constinit int a;
2999     // int a = 0; // error (missing 'constinit'), accepted as extension
3000     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3001     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3002         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3003     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3004   } else {
3005     // int a = 0;
3006     // constinit extern int a; // error (missing 'constinit')
3007     S.Diag(CIAttr->getLocation(),
3008            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3009                                  : diag::warn_require_const_init_added_too_late)
3010         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3011     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3012         << CIAttr->isConstinit()
3013         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3014   }
3015 }
3016 
3017 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3018 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3019                                AvailabilityMergeKind AMK) {
3020   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3021     UsedAttr *NewAttr = OldAttr->clone(Context);
3022     NewAttr->setInherited(true);
3023     New->addAttr(NewAttr);
3024   }
3025   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3026     RetainAttr *NewAttr = OldAttr->clone(Context);
3027     NewAttr->setInherited(true);
3028     New->addAttr(NewAttr);
3029   }
3030 
3031   if (!Old->hasAttrs() && !New->hasAttrs())
3032     return;
3033 
3034   // [dcl.constinit]p1:
3035   //   If the [constinit] specifier is applied to any declaration of a
3036   //   variable, it shall be applied to the initializing declaration.
3037   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3038   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3039   if (bool(OldConstInit) != bool(NewConstInit)) {
3040     const auto *OldVD = cast<VarDecl>(Old);
3041     auto *NewVD = cast<VarDecl>(New);
3042 
3043     // Find the initializing declaration. Note that we might not have linked
3044     // the new declaration into the redeclaration chain yet.
3045     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3046     if (!InitDecl &&
3047         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3048       InitDecl = NewVD;
3049 
3050     if (InitDecl == NewVD) {
3051       // This is the initializing declaration. If it would inherit 'constinit',
3052       // that's ill-formed. (Note that we do not apply this to the attribute
3053       // form).
3054       if (OldConstInit && OldConstInit->isConstinit())
3055         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3056                                  /*AttrBeforeInit=*/true);
3057     } else if (NewConstInit) {
3058       // This is the first time we've been told that this declaration should
3059       // have a constant initializer. If we already saw the initializing
3060       // declaration, this is too late.
3061       if (InitDecl && InitDecl != NewVD) {
3062         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3063                                  /*AttrBeforeInit=*/false);
3064         NewVD->dropAttr<ConstInitAttr>();
3065       }
3066     }
3067   }
3068 
3069   // Attributes declared post-definition are currently ignored.
3070   checkNewAttributesAfterDef(*this, New, Old);
3071 
3072   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3073     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3074       if (!OldA->isEquivalent(NewA)) {
3075         // This redeclaration changes __asm__ label.
3076         Diag(New->getLocation(), diag::err_different_asm_label);
3077         Diag(OldA->getLocation(), diag::note_previous_declaration);
3078       }
3079     } else if (Old->isUsed()) {
3080       // This redeclaration adds an __asm__ label to a declaration that has
3081       // already been ODR-used.
3082       Diag(New->getLocation(), diag::err_late_asm_label_name)
3083         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3084     }
3085   }
3086 
3087   // Re-declaration cannot add abi_tag's.
3088   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3089     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3090       for (const auto &NewTag : NewAbiTagAttr->tags()) {
3091         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3092           Diag(NewAbiTagAttr->getLocation(),
3093                diag::err_new_abi_tag_on_redeclaration)
3094               << NewTag;
3095           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3096         }
3097       }
3098     } else {
3099       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3100       Diag(Old->getLocation(), diag::note_previous_declaration);
3101     }
3102   }
3103 
3104   // This redeclaration adds a section attribute.
3105   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3106     if (auto *VD = dyn_cast<VarDecl>(New)) {
3107       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3108         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3109         Diag(Old->getLocation(), diag::note_previous_declaration);
3110       }
3111     }
3112   }
3113 
3114   // Redeclaration adds code-seg attribute.
3115   const auto *NewCSA = New->getAttr<CodeSegAttr>();
3116   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3117       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3118     Diag(New->getLocation(), diag::warn_mismatched_section)
3119          << 0 /*codeseg*/;
3120     Diag(Old->getLocation(), diag::note_previous_declaration);
3121   }
3122 
3123   if (!Old->hasAttrs())
3124     return;
3125 
3126   bool foundAny = New->hasAttrs();
3127 
3128   // Ensure that any moving of objects within the allocated map is done before
3129   // we process them.
3130   if (!foundAny) New->setAttrs(AttrVec());
3131 
3132   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3133     // Ignore deprecated/unavailable/availability attributes if requested.
3134     AvailabilityMergeKind LocalAMK = AMK_None;
3135     if (isa<DeprecatedAttr>(I) ||
3136         isa<UnavailableAttr>(I) ||
3137         isa<AvailabilityAttr>(I)) {
3138       switch (AMK) {
3139       case AMK_None:
3140         continue;
3141 
3142       case AMK_Redeclaration:
3143       case AMK_Override:
3144       case AMK_ProtocolImplementation:
3145       case AMK_OptionalProtocolImplementation:
3146         LocalAMK = AMK;
3147         break;
3148       }
3149     }
3150 
3151     // Already handled.
3152     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3153       continue;
3154 
3155     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3156       foundAny = true;
3157   }
3158 
3159   if (mergeAlignedAttrs(*this, New, Old))
3160     foundAny = true;
3161 
3162   if (!foundAny) New->dropAttrs();
3163 }
3164 
3165 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3166 /// to the new one.
3167 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3168                                      const ParmVarDecl *oldDecl,
3169                                      Sema &S) {
3170   // C++11 [dcl.attr.depend]p2:
3171   //   The first declaration of a function shall specify the
3172   //   carries_dependency attribute for its declarator-id if any declaration
3173   //   of the function specifies the carries_dependency attribute.
3174   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3175   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3176     S.Diag(CDA->getLocation(),
3177            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3178     // Find the first declaration of the parameter.
3179     // FIXME: Should we build redeclaration chains for function parameters?
3180     const FunctionDecl *FirstFD =
3181       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3182     const ParmVarDecl *FirstVD =
3183       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3184     S.Diag(FirstVD->getLocation(),
3185            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3186   }
3187 
3188   if (!oldDecl->hasAttrs())
3189     return;
3190 
3191   bool foundAny = newDecl->hasAttrs();
3192 
3193   // Ensure that any moving of objects within the allocated map is
3194   // done before we process them.
3195   if (!foundAny) newDecl->setAttrs(AttrVec());
3196 
3197   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3198     if (!DeclHasAttr(newDecl, I)) {
3199       InheritableAttr *newAttr =
3200         cast<InheritableParamAttr>(I->clone(S.Context));
3201       newAttr->setInherited(true);
3202       newDecl->addAttr(newAttr);
3203       foundAny = true;
3204     }
3205   }
3206 
3207   if (!foundAny) newDecl->dropAttrs();
3208 }
3209 
3210 static bool EquivalentArrayTypes(QualType Old, QualType New,
3211                                  const ASTContext &Ctx) {
3212 
3213   auto NoSizeInfo = [&Ctx](QualType Ty) {
3214     if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3215       return true;
3216     if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3217       return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3218     return false;
3219   };
3220 
3221   // `type[]` is equivalent to `type *` and `type[*]`.
3222   if (NoSizeInfo(Old) && NoSizeInfo(New))
3223     return true;
3224 
3225   // Don't try to compare VLA sizes, unless one of them has the star modifier.
3226   if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3227     const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3228     const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3229     if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3230         (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3231       return false;
3232     return true;
3233   }
3234 
3235   // Only compare size, ignore Size modifiers and CVR.
3236   if (Old->isConstantArrayType() && New->isConstantArrayType())
3237     return Ctx.getAsConstantArrayType(Old)->getSize() ==
3238            Ctx.getAsConstantArrayType(New)->getSize();
3239 
3240   return Old == New;
3241 }
3242 
3243 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3244                                 const ParmVarDecl *OldParam,
3245                                 Sema &S) {
3246   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3247     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3248       if (*Oldnullability != *Newnullability) {
3249         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3250           << DiagNullabilityKind(
3251                *Newnullability,
3252                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3253                 != 0))
3254           << DiagNullabilityKind(
3255                *Oldnullability,
3256                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3257                 != 0));
3258         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3259       }
3260     } else {
3261       QualType NewT = NewParam->getType();
3262       NewT = S.Context.getAttributedType(
3263                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3264                          NewT, NewT);
3265       NewParam->setType(NewT);
3266     }
3267   }
3268   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3269   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3270   if (OldParamDT && NewParamDT &&
3271       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3272     QualType OldParamOT = OldParamDT->getOriginalType();
3273     QualType NewParamOT = NewParamDT->getOriginalType();
3274     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3275       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3276           << NewParam << NewParamOT;
3277       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3278           << OldParamOT;
3279     }
3280   }
3281 }
3282 
3283 namespace {
3284 
3285 /// Used in MergeFunctionDecl to keep track of function parameters in
3286 /// C.
3287 struct GNUCompatibleParamWarning {
3288   ParmVarDecl *OldParm;
3289   ParmVarDecl *NewParm;
3290   QualType PromotedType;
3291 };
3292 
3293 } // end anonymous namespace
3294 
3295 // Determine whether the previous declaration was a definition, implicit
3296 // declaration, or a declaration.
3297 template <typename T>
3298 static std::pair<diag::kind, SourceLocation>
3299 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3300   diag::kind PrevDiag;
3301   SourceLocation OldLocation = Old->getLocation();
3302   if (Old->isThisDeclarationADefinition())
3303     PrevDiag = diag::note_previous_definition;
3304   else if (Old->isImplicit()) {
3305     PrevDiag = diag::note_previous_implicit_declaration;
3306     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3307       if (FD->getBuiltinID())
3308         PrevDiag = diag::note_previous_builtin_declaration;
3309     }
3310     if (OldLocation.isInvalid())
3311       OldLocation = New->getLocation();
3312   } else
3313     PrevDiag = diag::note_previous_declaration;
3314   return std::make_pair(PrevDiag, OldLocation);
3315 }
3316 
3317 /// canRedefineFunction - checks if a function can be redefined. Currently,
3318 /// only extern inline functions can be redefined, and even then only in
3319 /// GNU89 mode.
3320 static bool canRedefineFunction(const FunctionDecl *FD,
3321                                 const LangOptions& LangOpts) {
3322   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3323           !LangOpts.CPlusPlus &&
3324           FD->isInlineSpecified() &&
3325           FD->getStorageClass() == SC_Extern);
3326 }
3327 
3328 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3329   const AttributedType *AT = T->getAs<AttributedType>();
3330   while (AT && !AT->isCallingConv())
3331     AT = AT->getModifiedType()->getAs<AttributedType>();
3332   return AT;
3333 }
3334 
3335 template <typename T>
3336 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3337   const DeclContext *DC = Old->getDeclContext();
3338   if (DC->isRecord())
3339     return false;
3340 
3341   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3342   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3343     return true;
3344   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3345     return true;
3346   return false;
3347 }
3348 
3349 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3350 static bool isExternC(VarTemplateDecl *) { return false; }
3351 static bool isExternC(FunctionTemplateDecl *) { return false; }
3352 
3353 /// Check whether a redeclaration of an entity introduced by a
3354 /// using-declaration is valid, given that we know it's not an overload
3355 /// (nor a hidden tag declaration).
3356 template<typename ExpectedDecl>
3357 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3358                                    ExpectedDecl *New) {
3359   // C++11 [basic.scope.declarative]p4:
3360   //   Given a set of declarations in a single declarative region, each of
3361   //   which specifies the same unqualified name,
3362   //   -- they shall all refer to the same entity, or all refer to functions
3363   //      and function templates; or
3364   //   -- exactly one declaration shall declare a class name or enumeration
3365   //      name that is not a typedef name and the other declarations shall all
3366   //      refer to the same variable or enumerator, or all refer to functions
3367   //      and function templates; in this case the class name or enumeration
3368   //      name is hidden (3.3.10).
3369 
3370   // C++11 [namespace.udecl]p14:
3371   //   If a function declaration in namespace scope or block scope has the
3372   //   same name and the same parameter-type-list as a function introduced
3373   //   by a using-declaration, and the declarations do not declare the same
3374   //   function, the program is ill-formed.
3375 
3376   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3377   if (Old &&
3378       !Old->getDeclContext()->getRedeclContext()->Equals(
3379           New->getDeclContext()->getRedeclContext()) &&
3380       !(isExternC(Old) && isExternC(New)))
3381     Old = nullptr;
3382 
3383   if (!Old) {
3384     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3385     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3386     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3387     return true;
3388   }
3389   return false;
3390 }
3391 
3392 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3393                                             const FunctionDecl *B) {
3394   assert(A->getNumParams() == B->getNumParams());
3395 
3396   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3397     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3398     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3399     if (AttrA == AttrB)
3400       return true;
3401     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3402            AttrA->isDynamic() == AttrB->isDynamic();
3403   };
3404 
3405   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3406 }
3407 
3408 /// If necessary, adjust the semantic declaration context for a qualified
3409 /// declaration to name the correct inline namespace within the qualifier.
3410 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3411                                                DeclaratorDecl *OldD) {
3412   // The only case where we need to update the DeclContext is when
3413   // redeclaration lookup for a qualified name finds a declaration
3414   // in an inline namespace within the context named by the qualifier:
3415   //
3416   //   inline namespace N { int f(); }
3417   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3418   //
3419   // For unqualified declarations, the semantic context *can* change
3420   // along the redeclaration chain (for local extern declarations,
3421   // extern "C" declarations, and friend declarations in particular).
3422   if (!NewD->getQualifier())
3423     return;
3424 
3425   // NewD is probably already in the right context.
3426   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3427   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3428   if (NamedDC->Equals(SemaDC))
3429     return;
3430 
3431   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3432           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3433          "unexpected context for redeclaration");
3434 
3435   auto *LexDC = NewD->getLexicalDeclContext();
3436   auto FixSemaDC = [=](NamedDecl *D) {
3437     if (!D)
3438       return;
3439     D->setDeclContext(SemaDC);
3440     D->setLexicalDeclContext(LexDC);
3441   };
3442 
3443   FixSemaDC(NewD);
3444   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3445     FixSemaDC(FD->getDescribedFunctionTemplate());
3446   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3447     FixSemaDC(VD->getDescribedVarTemplate());
3448 }
3449 
3450 /// MergeFunctionDecl - We just parsed a function 'New' from
3451 /// declarator D which has the same name and scope as a previous
3452 /// declaration 'Old'.  Figure out how to resolve this situation,
3453 /// merging decls or emitting diagnostics as appropriate.
3454 ///
3455 /// In C++, New and Old must be declarations that are not
3456 /// overloaded. Use IsOverload to determine whether New and Old are
3457 /// overloaded, and to select the Old declaration that New should be
3458 /// merged with.
3459 ///
3460 /// Returns true if there was an error, false otherwise.
3461 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3462                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3463   // Verify the old decl was also a function.
3464   FunctionDecl *Old = OldD->getAsFunction();
3465   if (!Old) {
3466     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3467       if (New->getFriendObjectKind()) {
3468         Diag(New->getLocation(), diag::err_using_decl_friend);
3469         Diag(Shadow->getTargetDecl()->getLocation(),
3470              diag::note_using_decl_target);
3471         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3472             << 0;
3473         return true;
3474       }
3475 
3476       // Check whether the two declarations might declare the same function or
3477       // function template.
3478       if (FunctionTemplateDecl *NewTemplate =
3479               New->getDescribedFunctionTemplate()) {
3480         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3481                                                          NewTemplate))
3482           return true;
3483         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3484                          ->getAsFunction();
3485       } else {
3486         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3487           return true;
3488         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3489       }
3490     } else {
3491       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3492         << New->getDeclName();
3493       notePreviousDefinition(OldD, New->getLocation());
3494       return true;
3495     }
3496   }
3497 
3498   // If the old declaration was found in an inline namespace and the new
3499   // declaration was qualified, update the DeclContext to match.
3500   adjustDeclContextForDeclaratorDecl(New, Old);
3501 
3502   // If the old declaration is invalid, just give up here.
3503   if (Old->isInvalidDecl())
3504     return true;
3505 
3506   // Disallow redeclaration of some builtins.
3507   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3508     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3509     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3510         << Old << Old->getType();
3511     return true;
3512   }
3513 
3514   diag::kind PrevDiag;
3515   SourceLocation OldLocation;
3516   std::tie(PrevDiag, OldLocation) =
3517       getNoteDiagForInvalidRedeclaration(Old, New);
3518 
3519   // Don't complain about this if we're in GNU89 mode and the old function
3520   // is an extern inline function.
3521   // Don't complain about specializations. They are not supposed to have
3522   // storage classes.
3523   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3524       New->getStorageClass() == SC_Static &&
3525       Old->hasExternalFormalLinkage() &&
3526       !New->getTemplateSpecializationInfo() &&
3527       !canRedefineFunction(Old, getLangOpts())) {
3528     if (getLangOpts().MicrosoftExt) {
3529       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3530       Diag(OldLocation, PrevDiag);
3531     } else {
3532       Diag(New->getLocation(), diag::err_static_non_static) << New;
3533       Diag(OldLocation, PrevDiag);
3534       return true;
3535     }
3536   }
3537 
3538   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3539     if (!Old->hasAttr<InternalLinkageAttr>()) {
3540       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3541           << ILA;
3542       Diag(Old->getLocation(), diag::note_previous_declaration);
3543       New->dropAttr<InternalLinkageAttr>();
3544     }
3545 
3546   if (auto *EA = New->getAttr<ErrorAttr>()) {
3547     if (!Old->hasAttr<ErrorAttr>()) {
3548       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3549       Diag(Old->getLocation(), diag::note_previous_declaration);
3550       New->dropAttr<ErrorAttr>();
3551     }
3552   }
3553 
3554   if (CheckRedeclarationInModule(New, Old))
3555     return true;
3556 
3557   if (!getLangOpts().CPlusPlus) {
3558     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3559     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3560       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3561         << New << OldOvl;
3562 
3563       // Try our best to find a decl that actually has the overloadable
3564       // attribute for the note. In most cases (e.g. programs with only one
3565       // broken declaration/definition), this won't matter.
3566       //
3567       // FIXME: We could do this if we juggled some extra state in
3568       // OverloadableAttr, rather than just removing it.
3569       const Decl *DiagOld = Old;
3570       if (OldOvl) {
3571         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3572           const auto *A = D->getAttr<OverloadableAttr>();
3573           return A && !A->isImplicit();
3574         });
3575         // If we've implicitly added *all* of the overloadable attrs to this
3576         // chain, emitting a "previous redecl" note is pointless.
3577         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3578       }
3579 
3580       if (DiagOld)
3581         Diag(DiagOld->getLocation(),
3582              diag::note_attribute_overloadable_prev_overload)
3583           << OldOvl;
3584 
3585       if (OldOvl)
3586         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3587       else
3588         New->dropAttr<OverloadableAttr>();
3589     }
3590   }
3591 
3592   // If a function is first declared with a calling convention, but is later
3593   // declared or defined without one, all following decls assume the calling
3594   // convention of the first.
3595   //
3596   // It's OK if a function is first declared without a calling convention,
3597   // but is later declared or defined with the default calling convention.
3598   //
3599   // To test if either decl has an explicit calling convention, we look for
3600   // AttributedType sugar nodes on the type as written.  If they are missing or
3601   // were canonicalized away, we assume the calling convention was implicit.
3602   //
3603   // Note also that we DO NOT return at this point, because we still have
3604   // other tests to run.
3605   QualType OldQType = Context.getCanonicalType(Old->getType());
3606   QualType NewQType = Context.getCanonicalType(New->getType());
3607   const FunctionType *OldType = cast<FunctionType>(OldQType);
3608   const FunctionType *NewType = cast<FunctionType>(NewQType);
3609   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3610   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3611   bool RequiresAdjustment = false;
3612 
3613   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3614     FunctionDecl *First = Old->getFirstDecl();
3615     const FunctionType *FT =
3616         First->getType().getCanonicalType()->castAs<FunctionType>();
3617     FunctionType::ExtInfo FI = FT->getExtInfo();
3618     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3619     if (!NewCCExplicit) {
3620       // Inherit the CC from the previous declaration if it was specified
3621       // there but not here.
3622       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3623       RequiresAdjustment = true;
3624     } else if (Old->getBuiltinID()) {
3625       // Builtin attribute isn't propagated to the new one yet at this point,
3626       // so we check if the old one is a builtin.
3627 
3628       // Calling Conventions on a Builtin aren't really useful and setting a
3629       // default calling convention and cdecl'ing some builtin redeclarations is
3630       // common, so warn and ignore the calling convention on the redeclaration.
3631       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3632           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3633           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3634       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3635       RequiresAdjustment = true;
3636     } else {
3637       // Calling conventions aren't compatible, so complain.
3638       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3639       Diag(New->getLocation(), diag::err_cconv_change)
3640         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3641         << !FirstCCExplicit
3642         << (!FirstCCExplicit ? "" :
3643             FunctionType::getNameForCallConv(FI.getCC()));
3644 
3645       // Put the note on the first decl, since it is the one that matters.
3646       Diag(First->getLocation(), diag::note_previous_declaration);
3647       return true;
3648     }
3649   }
3650 
3651   // FIXME: diagnose the other way around?
3652   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3653     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3654     RequiresAdjustment = true;
3655   }
3656 
3657   // Merge regparm attribute.
3658   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3659       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3660     if (NewTypeInfo.getHasRegParm()) {
3661       Diag(New->getLocation(), diag::err_regparm_mismatch)
3662         << NewType->getRegParmType()
3663         << OldType->getRegParmType();
3664       Diag(OldLocation, diag::note_previous_declaration);
3665       return true;
3666     }
3667 
3668     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3669     RequiresAdjustment = true;
3670   }
3671 
3672   // Merge ns_returns_retained attribute.
3673   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3674     if (NewTypeInfo.getProducesResult()) {
3675       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3676           << "'ns_returns_retained'";
3677       Diag(OldLocation, diag::note_previous_declaration);
3678       return true;
3679     }
3680 
3681     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3682     RequiresAdjustment = true;
3683   }
3684 
3685   if (OldTypeInfo.getNoCallerSavedRegs() !=
3686       NewTypeInfo.getNoCallerSavedRegs()) {
3687     if (NewTypeInfo.getNoCallerSavedRegs()) {
3688       AnyX86NoCallerSavedRegistersAttr *Attr =
3689         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3690       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3691       Diag(OldLocation, diag::note_previous_declaration);
3692       return true;
3693     }
3694 
3695     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3696     RequiresAdjustment = true;
3697   }
3698 
3699   if (RequiresAdjustment) {
3700     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3701     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3702     New->setType(QualType(AdjustedType, 0));
3703     NewQType = Context.getCanonicalType(New->getType());
3704   }
3705 
3706   // If this redeclaration makes the function inline, we may need to add it to
3707   // UndefinedButUsed.
3708   if (!Old->isInlined() && New->isInlined() &&
3709       !New->hasAttr<GNUInlineAttr>() &&
3710       !getLangOpts().GNUInline &&
3711       Old->isUsed(false) &&
3712       !Old->isDefined() && !New->isThisDeclarationADefinition())
3713     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3714                                            SourceLocation()));
3715 
3716   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3717   // about it.
3718   if (New->hasAttr<GNUInlineAttr>() &&
3719       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3720     UndefinedButUsed.erase(Old->getCanonicalDecl());
3721   }
3722 
3723   // If pass_object_size params don't match up perfectly, this isn't a valid
3724   // redeclaration.
3725   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3726       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3727     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3728         << New->getDeclName();
3729     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3730     return true;
3731   }
3732 
3733   if (getLangOpts().CPlusPlus) {
3734     // C++1z [over.load]p2
3735     //   Certain function declarations cannot be overloaded:
3736     //     -- Function declarations that differ only in the return type,
3737     //        the exception specification, or both cannot be overloaded.
3738 
3739     // Check the exception specifications match. This may recompute the type of
3740     // both Old and New if it resolved exception specifications, so grab the
3741     // types again after this. Because this updates the type, we do this before
3742     // any of the other checks below, which may update the "de facto" NewQType
3743     // but do not necessarily update the type of New.
3744     if (CheckEquivalentExceptionSpec(Old, New))
3745       return true;
3746     OldQType = Context.getCanonicalType(Old->getType());
3747     NewQType = Context.getCanonicalType(New->getType());
3748 
3749     // Go back to the type source info to compare the declared return types,
3750     // per C++1y [dcl.type.auto]p13:
3751     //   Redeclarations or specializations of a function or function template
3752     //   with a declared return type that uses a placeholder type shall also
3753     //   use that placeholder, not a deduced type.
3754     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3755     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3756     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3757         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3758                                        OldDeclaredReturnType)) {
3759       QualType ResQT;
3760       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3761           OldDeclaredReturnType->isObjCObjectPointerType())
3762         // FIXME: This does the wrong thing for a deduced return type.
3763         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3764       if (ResQT.isNull()) {
3765         if (New->isCXXClassMember() && New->isOutOfLine())
3766           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3767               << New << New->getReturnTypeSourceRange();
3768         else
3769           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3770               << New->getReturnTypeSourceRange();
3771         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3772                                     << Old->getReturnTypeSourceRange();
3773         return true;
3774       }
3775       else
3776         NewQType = ResQT;
3777     }
3778 
3779     QualType OldReturnType = OldType->getReturnType();
3780     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3781     if (OldReturnType != NewReturnType) {
3782       // If this function has a deduced return type and has already been
3783       // defined, copy the deduced value from the old declaration.
3784       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3785       if (OldAT && OldAT->isDeduced()) {
3786         QualType DT = OldAT->getDeducedType();
3787         if (DT.isNull()) {
3788           New->setType(SubstAutoTypeDependent(New->getType()));
3789           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3790         } else {
3791           New->setType(SubstAutoType(New->getType(), DT));
3792           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3793         }
3794       }
3795     }
3796 
3797     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3798     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3799     if (OldMethod && NewMethod) {
3800       // Preserve triviality.
3801       NewMethod->setTrivial(OldMethod->isTrivial());
3802 
3803       // MSVC allows explicit template specialization at class scope:
3804       // 2 CXXMethodDecls referring to the same function will be injected.
3805       // We don't want a redeclaration error.
3806       bool IsClassScopeExplicitSpecialization =
3807                               OldMethod->isFunctionTemplateSpecialization() &&
3808                               NewMethod->isFunctionTemplateSpecialization();
3809       bool isFriend = NewMethod->getFriendObjectKind();
3810 
3811       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3812           !IsClassScopeExplicitSpecialization) {
3813         //    -- Member function declarations with the same name and the
3814         //       same parameter types cannot be overloaded if any of them
3815         //       is a static member function declaration.
3816         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3817           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3818           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3819           return true;
3820         }
3821 
3822         // C++ [class.mem]p1:
3823         //   [...] A member shall not be declared twice in the
3824         //   member-specification, except that a nested class or member
3825         //   class template can be declared and then later defined.
3826         if (!inTemplateInstantiation()) {
3827           unsigned NewDiag;
3828           if (isa<CXXConstructorDecl>(OldMethod))
3829             NewDiag = diag::err_constructor_redeclared;
3830           else if (isa<CXXDestructorDecl>(NewMethod))
3831             NewDiag = diag::err_destructor_redeclared;
3832           else if (isa<CXXConversionDecl>(NewMethod))
3833             NewDiag = diag::err_conv_function_redeclared;
3834           else
3835             NewDiag = diag::err_member_redeclared;
3836 
3837           Diag(New->getLocation(), NewDiag);
3838         } else {
3839           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3840             << New << New->getType();
3841         }
3842         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3843         return true;
3844 
3845       // Complain if this is an explicit declaration of a special
3846       // member that was initially declared implicitly.
3847       //
3848       // As an exception, it's okay to befriend such methods in order
3849       // to permit the implicit constructor/destructor/operator calls.
3850       } else if (OldMethod->isImplicit()) {
3851         if (isFriend) {
3852           NewMethod->setImplicit();
3853         } else {
3854           Diag(NewMethod->getLocation(),
3855                diag::err_definition_of_implicitly_declared_member)
3856             << New << getSpecialMember(OldMethod);
3857           return true;
3858         }
3859       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3860         Diag(NewMethod->getLocation(),
3861              diag::err_definition_of_explicitly_defaulted_member)
3862           << getSpecialMember(OldMethod);
3863         return true;
3864       }
3865     }
3866 
3867     // C++11 [dcl.attr.noreturn]p1:
3868     //   The first declaration of a function shall specify the noreturn
3869     //   attribute if any declaration of that function specifies the noreturn
3870     //   attribute.
3871     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3872       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3873         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3874             << NRA;
3875         Diag(Old->getLocation(), diag::note_previous_declaration);
3876       }
3877 
3878     // C++11 [dcl.attr.depend]p2:
3879     //   The first declaration of a function shall specify the
3880     //   carries_dependency attribute for its declarator-id if any declaration
3881     //   of the function specifies the carries_dependency attribute.
3882     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3883     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3884       Diag(CDA->getLocation(),
3885            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3886       Diag(Old->getFirstDecl()->getLocation(),
3887            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3888     }
3889 
3890     // (C++98 8.3.5p3):
3891     //   All declarations for a function shall agree exactly in both the
3892     //   return type and the parameter-type-list.
3893     // We also want to respect all the extended bits except noreturn.
3894 
3895     // noreturn should now match unless the old type info didn't have it.
3896     QualType OldQTypeForComparison = OldQType;
3897     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3898       auto *OldType = OldQType->castAs<FunctionProtoType>();
3899       const FunctionType *OldTypeForComparison
3900         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3901       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3902       assert(OldQTypeForComparison.isCanonical());
3903     }
3904 
3905     if (haveIncompatibleLanguageLinkages(Old, New)) {
3906       // As a special case, retain the language linkage from previous
3907       // declarations of a friend function as an extension.
3908       //
3909       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3910       // and is useful because there's otherwise no way to specify language
3911       // linkage within class scope.
3912       //
3913       // Check cautiously as the friend object kind isn't yet complete.
3914       if (New->getFriendObjectKind() != Decl::FOK_None) {
3915         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3916         Diag(OldLocation, PrevDiag);
3917       } else {
3918         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3919         Diag(OldLocation, PrevDiag);
3920         return true;
3921       }
3922     }
3923 
3924     // If the function types are compatible, merge the declarations. Ignore the
3925     // exception specifier because it was already checked above in
3926     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3927     // about incompatible types under -fms-compatibility.
3928     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3929                                                          NewQType))
3930       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3931 
3932     // If the types are imprecise (due to dependent constructs in friends or
3933     // local extern declarations), it's OK if they differ. We'll check again
3934     // during instantiation.
3935     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3936       return false;
3937 
3938     // Fall through for conflicting redeclarations and redefinitions.
3939   }
3940 
3941   // C: Function types need to be compatible, not identical. This handles
3942   // duplicate function decls like "void f(int); void f(enum X);" properly.
3943   if (!getLangOpts().CPlusPlus) {
3944     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3945     // type is specified by a function definition that contains a (possibly
3946     // empty) identifier list, both shall agree in the number of parameters
3947     // and the type of each parameter shall be compatible with the type that
3948     // results from the application of default argument promotions to the
3949     // type of the corresponding identifier. ...
3950     // This cannot be handled by ASTContext::typesAreCompatible() because that
3951     // doesn't know whether the function type is for a definition or not when
3952     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3953     // we need to cover here is that the number of arguments agree as the
3954     // default argument promotion rules were already checked by
3955     // ASTContext::typesAreCompatible().
3956     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3957         Old->getNumParams() != New->getNumParams()) {
3958       if (Old->hasInheritedPrototype())
3959         Old = Old->getCanonicalDecl();
3960       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3961       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3962       return true;
3963     }
3964 
3965     // If we are merging two functions where only one of them has a prototype,
3966     // we may have enough information to decide to issue a diagnostic that the
3967     // function without a protoype will change behavior in C2x. This handles
3968     // cases like:
3969     //   void i(); void i(int j);
3970     //   void i(int j); void i();
3971     //   void i(); void i(int j) {}
3972     // See ActOnFinishFunctionBody() for other cases of the behavior change
3973     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3974     // type without a prototype.
3975     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3976         !New->isImplicit() && !Old->isImplicit()) {
3977       const FunctionDecl *WithProto, *WithoutProto;
3978       if (New->hasWrittenPrototype()) {
3979         WithProto = New;
3980         WithoutProto = Old;
3981       } else {
3982         WithProto = Old;
3983         WithoutProto = New;
3984       }
3985 
3986       if (WithProto->getNumParams() != 0) {
3987         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3988           // The one without the prototype will be changing behavior in C2x, so
3989           // warn about that one so long as it's a user-visible declaration.
3990           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3991           if (WithoutProto == New)
3992             IsWithoutProtoADef = NewDeclIsDefn;
3993           else
3994             IsWithProtoADef = NewDeclIsDefn;
3995           Diag(WithoutProto->getLocation(),
3996                diag::warn_non_prototype_changes_behavior)
3997               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
3998               << (WithoutProto == Old) << IsWithProtoADef;
3999 
4000           // The reason the one without the prototype will be changing behavior
4001           // is because of the one with the prototype, so note that so long as
4002           // it's a user-visible declaration. There is one exception to this:
4003           // when the new declaration is a definition without a prototype, the
4004           // old declaration with a prototype is not the cause of the issue,
4005           // and that does not need to be noted because the one with a
4006           // prototype will not change behavior in C2x.
4007           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4008               !IsWithoutProtoADef)
4009             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4010         }
4011       }
4012     }
4013 
4014     if (Context.typesAreCompatible(OldQType, NewQType)) {
4015       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4016       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4017       const FunctionProtoType *OldProto = nullptr;
4018       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4019           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4020         // The old declaration provided a function prototype, but the
4021         // new declaration does not. Merge in the prototype.
4022         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4023         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4024         NewQType =
4025             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4026                                     OldProto->getExtProtoInfo());
4027         New->setType(NewQType);
4028         New->setHasInheritedPrototype();
4029 
4030         // Synthesize parameters with the same types.
4031         SmallVector<ParmVarDecl *, 16> Params;
4032         for (const auto &ParamType : OldProto->param_types()) {
4033           ParmVarDecl *Param = ParmVarDecl::Create(
4034               Context, New, SourceLocation(), SourceLocation(), nullptr,
4035               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4036           Param->setScopeInfo(0, Params.size());
4037           Param->setImplicit();
4038           Params.push_back(Param);
4039         }
4040 
4041         New->setParams(Params);
4042       }
4043 
4044       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4045     }
4046   }
4047 
4048   // Check if the function types are compatible when pointer size address
4049   // spaces are ignored.
4050   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4051     return false;
4052 
4053   // GNU C permits a K&R definition to follow a prototype declaration
4054   // if the declared types of the parameters in the K&R definition
4055   // match the types in the prototype declaration, even when the
4056   // promoted types of the parameters from the K&R definition differ
4057   // from the types in the prototype. GCC then keeps the types from
4058   // the prototype.
4059   //
4060   // If a variadic prototype is followed by a non-variadic K&R definition,
4061   // the K&R definition becomes variadic.  This is sort of an edge case, but
4062   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4063   // C99 6.9.1p8.
4064   if (!getLangOpts().CPlusPlus &&
4065       Old->hasPrototype() && !New->hasPrototype() &&
4066       New->getType()->getAs<FunctionProtoType>() &&
4067       Old->getNumParams() == New->getNumParams()) {
4068     SmallVector<QualType, 16> ArgTypes;
4069     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4070     const FunctionProtoType *OldProto
4071       = Old->getType()->getAs<FunctionProtoType>();
4072     const FunctionProtoType *NewProto
4073       = New->getType()->getAs<FunctionProtoType>();
4074 
4075     // Determine whether this is the GNU C extension.
4076     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4077                                                NewProto->getReturnType());
4078     bool LooseCompatible = !MergedReturn.isNull();
4079     for (unsigned Idx = 0, End = Old->getNumParams();
4080          LooseCompatible && Idx != End; ++Idx) {
4081       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4082       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4083       if (Context.typesAreCompatible(OldParm->getType(),
4084                                      NewProto->getParamType(Idx))) {
4085         ArgTypes.push_back(NewParm->getType());
4086       } else if (Context.typesAreCompatible(OldParm->getType(),
4087                                             NewParm->getType(),
4088                                             /*CompareUnqualified=*/true)) {
4089         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4090                                            NewProto->getParamType(Idx) };
4091         Warnings.push_back(Warn);
4092         ArgTypes.push_back(NewParm->getType());
4093       } else
4094         LooseCompatible = false;
4095     }
4096 
4097     if (LooseCompatible) {
4098       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4099         Diag(Warnings[Warn].NewParm->getLocation(),
4100              diag::ext_param_promoted_not_compatible_with_prototype)
4101           << Warnings[Warn].PromotedType
4102           << Warnings[Warn].OldParm->getType();
4103         if (Warnings[Warn].OldParm->getLocation().isValid())
4104           Diag(Warnings[Warn].OldParm->getLocation(),
4105                diag::note_previous_declaration);
4106       }
4107 
4108       if (MergeTypeWithOld)
4109         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4110                                              OldProto->getExtProtoInfo()));
4111       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4112     }
4113 
4114     // Fall through to diagnose conflicting types.
4115   }
4116 
4117   // A function that has already been declared has been redeclared or
4118   // defined with a different type; show an appropriate diagnostic.
4119 
4120   // If the previous declaration was an implicitly-generated builtin
4121   // declaration, then at the very least we should use a specialized note.
4122   unsigned BuiltinID;
4123   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4124     // If it's actually a library-defined builtin function like 'malloc'
4125     // or 'printf', just warn about the incompatible redeclaration.
4126     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4127       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4128       Diag(OldLocation, diag::note_previous_builtin_declaration)
4129         << Old << Old->getType();
4130       return false;
4131     }
4132 
4133     PrevDiag = diag::note_previous_builtin_declaration;
4134   }
4135 
4136   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4137   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4138   return true;
4139 }
4140 
4141 /// Completes the merge of two function declarations that are
4142 /// known to be compatible.
4143 ///
4144 /// This routine handles the merging of attributes and other
4145 /// properties of function declarations from the old declaration to
4146 /// the new declaration, once we know that New is in fact a
4147 /// redeclaration of Old.
4148 ///
4149 /// \returns false
4150 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4151                                         Scope *S, bool MergeTypeWithOld) {
4152   // Merge the attributes
4153   mergeDeclAttributes(New, Old);
4154 
4155   // Merge "pure" flag.
4156   if (Old->isPure())
4157     New->setPure();
4158 
4159   // Merge "used" flag.
4160   if (Old->getMostRecentDecl()->isUsed(false))
4161     New->setIsUsed();
4162 
4163   // Merge attributes from the parameters.  These can mismatch with K&R
4164   // declarations.
4165   if (New->getNumParams() == Old->getNumParams())
4166       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4167         ParmVarDecl *NewParam = New->getParamDecl(i);
4168         ParmVarDecl *OldParam = Old->getParamDecl(i);
4169         mergeParamDeclAttributes(NewParam, OldParam, *this);
4170         mergeParamDeclTypes(NewParam, OldParam, *this);
4171       }
4172 
4173   if (getLangOpts().CPlusPlus)
4174     return MergeCXXFunctionDecl(New, Old, S);
4175 
4176   // Merge the function types so the we get the composite types for the return
4177   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4178   // was visible.
4179   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4180   if (!Merged.isNull() && MergeTypeWithOld)
4181     New->setType(Merged);
4182 
4183   return false;
4184 }
4185 
4186 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4187                                 ObjCMethodDecl *oldMethod) {
4188   // Merge the attributes, including deprecated/unavailable
4189   AvailabilityMergeKind MergeKind =
4190       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4191           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4192                                      : AMK_ProtocolImplementation)
4193           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4194                                                            : AMK_Override;
4195 
4196   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4197 
4198   // Merge attributes from the parameters.
4199   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4200                                        oe = oldMethod->param_end();
4201   for (ObjCMethodDecl::param_iterator
4202          ni = newMethod->param_begin(), ne = newMethod->param_end();
4203        ni != ne && oi != oe; ++ni, ++oi)
4204     mergeParamDeclAttributes(*ni, *oi, *this);
4205 
4206   CheckObjCMethodOverride(newMethod, oldMethod);
4207 }
4208 
4209 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4210   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4211 
4212   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4213          ? diag::err_redefinition_different_type
4214          : diag::err_redeclaration_different_type)
4215     << New->getDeclName() << New->getType() << Old->getType();
4216 
4217   diag::kind PrevDiag;
4218   SourceLocation OldLocation;
4219   std::tie(PrevDiag, OldLocation)
4220     = getNoteDiagForInvalidRedeclaration(Old, New);
4221   S.Diag(OldLocation, PrevDiag);
4222   New->setInvalidDecl();
4223 }
4224 
4225 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4226 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4227 /// emitting diagnostics as appropriate.
4228 ///
4229 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4230 /// to here in AddInitializerToDecl. We can't check them before the initializer
4231 /// is attached.
4232 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4233                              bool MergeTypeWithOld) {
4234   if (New->isInvalidDecl() || Old->isInvalidDecl())
4235     return;
4236 
4237   QualType MergedT;
4238   if (getLangOpts().CPlusPlus) {
4239     if (New->getType()->isUndeducedType()) {
4240       // We don't know what the new type is until the initializer is attached.
4241       return;
4242     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4243       // These could still be something that needs exception specs checked.
4244       return MergeVarDeclExceptionSpecs(New, Old);
4245     }
4246     // C++ [basic.link]p10:
4247     //   [...] the types specified by all declarations referring to a given
4248     //   object or function shall be identical, except that declarations for an
4249     //   array object can specify array types that differ by the presence or
4250     //   absence of a major array bound (8.3.4).
4251     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4252       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4253       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4254 
4255       // We are merging a variable declaration New into Old. If it has an array
4256       // bound, and that bound differs from Old's bound, we should diagnose the
4257       // mismatch.
4258       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4259         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4260              PrevVD = PrevVD->getPreviousDecl()) {
4261           QualType PrevVDTy = PrevVD->getType();
4262           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4263             continue;
4264 
4265           if (!Context.hasSameType(New->getType(), PrevVDTy))
4266             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4267         }
4268       }
4269 
4270       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4271         if (Context.hasSameType(OldArray->getElementType(),
4272                                 NewArray->getElementType()))
4273           MergedT = New->getType();
4274       }
4275       // FIXME: Check visibility. New is hidden but has a complete type. If New
4276       // has no array bound, it should not inherit one from Old, if Old is not
4277       // visible.
4278       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4279         if (Context.hasSameType(OldArray->getElementType(),
4280                                 NewArray->getElementType()))
4281           MergedT = Old->getType();
4282       }
4283     }
4284     else if (New->getType()->isObjCObjectPointerType() &&
4285                Old->getType()->isObjCObjectPointerType()) {
4286       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4287                                               Old->getType());
4288     }
4289   } else {
4290     // C 6.2.7p2:
4291     //   All declarations that refer to the same object or function shall have
4292     //   compatible type.
4293     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4294   }
4295   if (MergedT.isNull()) {
4296     // It's OK if we couldn't merge types if either type is dependent, for a
4297     // block-scope variable. In other cases (static data members of class
4298     // templates, variable templates, ...), we require the types to be
4299     // equivalent.
4300     // FIXME: The C++ standard doesn't say anything about this.
4301     if ((New->getType()->isDependentType() ||
4302          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4303       // If the old type was dependent, we can't merge with it, so the new type
4304       // becomes dependent for now. We'll reproduce the original type when we
4305       // instantiate the TypeSourceInfo for the variable.
4306       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4307         New->setType(Context.DependentTy);
4308       return;
4309     }
4310     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4311   }
4312 
4313   // Don't actually update the type on the new declaration if the old
4314   // declaration was an extern declaration in a different scope.
4315   if (MergeTypeWithOld)
4316     New->setType(MergedT);
4317 }
4318 
4319 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4320                                   LookupResult &Previous) {
4321   // C11 6.2.7p4:
4322   //   For an identifier with internal or external linkage declared
4323   //   in a scope in which a prior declaration of that identifier is
4324   //   visible, if the prior declaration specifies internal or
4325   //   external linkage, the type of the identifier at the later
4326   //   declaration becomes the composite type.
4327   //
4328   // If the variable isn't visible, we do not merge with its type.
4329   if (Previous.isShadowed())
4330     return false;
4331 
4332   if (S.getLangOpts().CPlusPlus) {
4333     // C++11 [dcl.array]p3:
4334     //   If there is a preceding declaration of the entity in the same
4335     //   scope in which the bound was specified, an omitted array bound
4336     //   is taken to be the same as in that earlier declaration.
4337     return NewVD->isPreviousDeclInSameBlockScope() ||
4338            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4339             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4340   } else {
4341     // If the old declaration was function-local, don't merge with its
4342     // type unless we're in the same function.
4343     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4344            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4345   }
4346 }
4347 
4348 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4349 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4350 /// situation, merging decls or emitting diagnostics as appropriate.
4351 ///
4352 /// Tentative definition rules (C99 6.9.2p2) are checked by
4353 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4354 /// definitions here, since the initializer hasn't been attached.
4355 ///
4356 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4357   // If the new decl is already invalid, don't do any other checking.
4358   if (New->isInvalidDecl())
4359     return;
4360 
4361   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4362     return;
4363 
4364   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4365 
4366   // Verify the old decl was also a variable or variable template.
4367   VarDecl *Old = nullptr;
4368   VarTemplateDecl *OldTemplate = nullptr;
4369   if (Previous.isSingleResult()) {
4370     if (NewTemplate) {
4371       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4372       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4373 
4374       if (auto *Shadow =
4375               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4376         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4377           return New->setInvalidDecl();
4378     } else {
4379       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4380 
4381       if (auto *Shadow =
4382               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4383         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4384           return New->setInvalidDecl();
4385     }
4386   }
4387   if (!Old) {
4388     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4389         << New->getDeclName();
4390     notePreviousDefinition(Previous.getRepresentativeDecl(),
4391                            New->getLocation());
4392     return New->setInvalidDecl();
4393   }
4394 
4395   // If the old declaration was found in an inline namespace and the new
4396   // declaration was qualified, update the DeclContext to match.
4397   adjustDeclContextForDeclaratorDecl(New, Old);
4398 
4399   // Ensure the template parameters are compatible.
4400   if (NewTemplate &&
4401       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4402                                       OldTemplate->getTemplateParameters(),
4403                                       /*Complain=*/true, TPL_TemplateMatch))
4404     return New->setInvalidDecl();
4405 
4406   // C++ [class.mem]p1:
4407   //   A member shall not be declared twice in the member-specification [...]
4408   //
4409   // Here, we need only consider static data members.
4410   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4411     Diag(New->getLocation(), diag::err_duplicate_member)
4412       << New->getIdentifier();
4413     Diag(Old->getLocation(), diag::note_previous_declaration);
4414     New->setInvalidDecl();
4415   }
4416 
4417   mergeDeclAttributes(New, Old);
4418   // Warn if an already-declared variable is made a weak_import in a subsequent
4419   // declaration
4420   if (New->hasAttr<WeakImportAttr>() &&
4421       Old->getStorageClass() == SC_None &&
4422       !Old->hasAttr<WeakImportAttr>()) {
4423     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4424     Diag(Old->getLocation(), diag::note_previous_declaration);
4425     // Remove weak_import attribute on new declaration.
4426     New->dropAttr<WeakImportAttr>();
4427   }
4428 
4429   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4430     if (!Old->hasAttr<InternalLinkageAttr>()) {
4431       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4432           << ILA;
4433       Diag(Old->getLocation(), diag::note_previous_declaration);
4434       New->dropAttr<InternalLinkageAttr>();
4435     }
4436 
4437   // Merge the types.
4438   VarDecl *MostRecent = Old->getMostRecentDecl();
4439   if (MostRecent != Old) {
4440     MergeVarDeclTypes(New, MostRecent,
4441                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4442     if (New->isInvalidDecl())
4443       return;
4444   }
4445 
4446   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4447   if (New->isInvalidDecl())
4448     return;
4449 
4450   diag::kind PrevDiag;
4451   SourceLocation OldLocation;
4452   std::tie(PrevDiag, OldLocation) =
4453       getNoteDiagForInvalidRedeclaration(Old, New);
4454 
4455   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4456   if (New->getStorageClass() == SC_Static &&
4457       !New->isStaticDataMember() &&
4458       Old->hasExternalFormalLinkage()) {
4459     if (getLangOpts().MicrosoftExt) {
4460       Diag(New->getLocation(), diag::ext_static_non_static)
4461           << New->getDeclName();
4462       Diag(OldLocation, PrevDiag);
4463     } else {
4464       Diag(New->getLocation(), diag::err_static_non_static)
4465           << New->getDeclName();
4466       Diag(OldLocation, PrevDiag);
4467       return New->setInvalidDecl();
4468     }
4469   }
4470   // C99 6.2.2p4:
4471   //   For an identifier declared with the storage-class specifier
4472   //   extern in a scope in which a prior declaration of that
4473   //   identifier is visible,23) if the prior declaration specifies
4474   //   internal or external linkage, the linkage of the identifier at
4475   //   the later declaration is the same as the linkage specified at
4476   //   the prior declaration. If no prior declaration is visible, or
4477   //   if the prior declaration specifies no linkage, then the
4478   //   identifier has external linkage.
4479   if (New->hasExternalStorage() && Old->hasLinkage())
4480     /* Okay */;
4481   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4482            !New->isStaticDataMember() &&
4483            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4484     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4485     Diag(OldLocation, PrevDiag);
4486     return New->setInvalidDecl();
4487   }
4488 
4489   // Check if extern is followed by non-extern and vice-versa.
4490   if (New->hasExternalStorage() &&
4491       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4492     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4493     Diag(OldLocation, PrevDiag);
4494     return New->setInvalidDecl();
4495   }
4496   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4497       !New->hasExternalStorage()) {
4498     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4499     Diag(OldLocation, PrevDiag);
4500     return New->setInvalidDecl();
4501   }
4502 
4503   if (CheckRedeclarationInModule(New, Old))
4504     return;
4505 
4506   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4507 
4508   // FIXME: The test for external storage here seems wrong? We still
4509   // need to check for mismatches.
4510   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4511       // Don't complain about out-of-line definitions of static members.
4512       !(Old->getLexicalDeclContext()->isRecord() &&
4513         !New->getLexicalDeclContext()->isRecord())) {
4514     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4515     Diag(OldLocation, PrevDiag);
4516     return New->setInvalidDecl();
4517   }
4518 
4519   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4520     if (VarDecl *Def = Old->getDefinition()) {
4521       // C++1z [dcl.fcn.spec]p4:
4522       //   If the definition of a variable appears in a translation unit before
4523       //   its first declaration as inline, the program is ill-formed.
4524       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4525       Diag(Def->getLocation(), diag::note_previous_definition);
4526     }
4527   }
4528 
4529   // If this redeclaration makes the variable inline, we may need to add it to
4530   // UndefinedButUsed.
4531   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4532       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4533     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4534                                            SourceLocation()));
4535 
4536   if (New->getTLSKind() != Old->getTLSKind()) {
4537     if (!Old->getTLSKind()) {
4538       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4539       Diag(OldLocation, PrevDiag);
4540     } else if (!New->getTLSKind()) {
4541       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4542       Diag(OldLocation, PrevDiag);
4543     } else {
4544       // Do not allow redeclaration to change the variable between requiring
4545       // static and dynamic initialization.
4546       // FIXME: GCC allows this, but uses the TLS keyword on the first
4547       // declaration to determine the kind. Do we need to be compatible here?
4548       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4549         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4550       Diag(OldLocation, PrevDiag);
4551     }
4552   }
4553 
4554   // C++ doesn't have tentative definitions, so go right ahead and check here.
4555   if (getLangOpts().CPlusPlus) {
4556     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4557         Old->getCanonicalDecl()->isConstexpr()) {
4558       // This definition won't be a definition any more once it's been merged.
4559       Diag(New->getLocation(),
4560            diag::warn_deprecated_redundant_constexpr_static_def);
4561     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4562       VarDecl *Def = Old->getDefinition();
4563       if (Def && checkVarDeclRedefinition(Def, New))
4564         return;
4565     }
4566   }
4567 
4568   if (haveIncompatibleLanguageLinkages(Old, New)) {
4569     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4570     Diag(OldLocation, PrevDiag);
4571     New->setInvalidDecl();
4572     return;
4573   }
4574 
4575   // Merge "used" flag.
4576   if (Old->getMostRecentDecl()->isUsed(false))
4577     New->setIsUsed();
4578 
4579   // Keep a chain of previous declarations.
4580   New->setPreviousDecl(Old);
4581   if (NewTemplate)
4582     NewTemplate->setPreviousDecl(OldTemplate);
4583 
4584   // Inherit access appropriately.
4585   New->setAccess(Old->getAccess());
4586   if (NewTemplate)
4587     NewTemplate->setAccess(New->getAccess());
4588 
4589   if (Old->isInline())
4590     New->setImplicitlyInline();
4591 }
4592 
4593 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4594   SourceManager &SrcMgr = getSourceManager();
4595   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4596   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4597   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4598   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4599   auto &HSI = PP.getHeaderSearchInfo();
4600   StringRef HdrFilename =
4601       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4602 
4603   auto noteFromModuleOrInclude = [&](Module *Mod,
4604                                      SourceLocation IncLoc) -> bool {
4605     // Redefinition errors with modules are common with non modular mapped
4606     // headers, example: a non-modular header H in module A that also gets
4607     // included directly in a TU. Pointing twice to the same header/definition
4608     // is confusing, try to get better diagnostics when modules is on.
4609     if (IncLoc.isValid()) {
4610       if (Mod) {
4611         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4612             << HdrFilename.str() << Mod->getFullModuleName();
4613         if (!Mod->DefinitionLoc.isInvalid())
4614           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4615               << Mod->getFullModuleName();
4616       } else {
4617         Diag(IncLoc, diag::note_redefinition_include_same_file)
4618             << HdrFilename.str();
4619       }
4620       return true;
4621     }
4622 
4623     return false;
4624   };
4625 
4626   // Is it the same file and same offset? Provide more information on why
4627   // this leads to a redefinition error.
4628   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4629     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4630     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4631     bool EmittedDiag =
4632         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4633     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4634 
4635     // If the header has no guards, emit a note suggesting one.
4636     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4637       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4638 
4639     if (EmittedDiag)
4640       return;
4641   }
4642 
4643   // Redefinition coming from different files or couldn't do better above.
4644   if (Old->getLocation().isValid())
4645     Diag(Old->getLocation(), diag::note_previous_definition);
4646 }
4647 
4648 /// We've just determined that \p Old and \p New both appear to be definitions
4649 /// of the same variable. Either diagnose or fix the problem.
4650 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4651   if (!hasVisibleDefinition(Old) &&
4652       (New->getFormalLinkage() == InternalLinkage ||
4653        New->isInline() ||
4654        New->getDescribedVarTemplate() ||
4655        New->getNumTemplateParameterLists() ||
4656        New->getDeclContext()->isDependentContext())) {
4657     // The previous definition is hidden, and multiple definitions are
4658     // permitted (in separate TUs). Demote this to a declaration.
4659     New->demoteThisDefinitionToDeclaration();
4660 
4661     // Make the canonical definition visible.
4662     if (auto *OldTD = Old->getDescribedVarTemplate())
4663       makeMergedDefinitionVisible(OldTD);
4664     makeMergedDefinitionVisible(Old);
4665     return false;
4666   } else {
4667     Diag(New->getLocation(), diag::err_redefinition) << New;
4668     notePreviousDefinition(Old, New->getLocation());
4669     New->setInvalidDecl();
4670     return true;
4671   }
4672 }
4673 
4674 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4675 /// no declarator (e.g. "struct foo;") is parsed.
4676 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4677                                        DeclSpec &DS,
4678                                        const ParsedAttributesView &DeclAttrs,
4679                                        RecordDecl *&AnonRecord) {
4680   return ParsedFreeStandingDeclSpec(
4681       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4682 }
4683 
4684 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4685 // disambiguate entities defined in different scopes.
4686 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4687 // compatibility.
4688 // We will pick our mangling number depending on which version of MSVC is being
4689 // targeted.
4690 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4691   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4692              ? S->getMSCurManglingNumber()
4693              : S->getMSLastManglingNumber();
4694 }
4695 
4696 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4697   if (!Context.getLangOpts().CPlusPlus)
4698     return;
4699 
4700   if (isa<CXXRecordDecl>(Tag->getParent())) {
4701     // If this tag is the direct child of a class, number it if
4702     // it is anonymous.
4703     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4704       return;
4705     MangleNumberingContext &MCtx =
4706         Context.getManglingNumberContext(Tag->getParent());
4707     Context.setManglingNumber(
4708         Tag, MCtx.getManglingNumber(
4709                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4710     return;
4711   }
4712 
4713   // If this tag isn't a direct child of a class, number it if it is local.
4714   MangleNumberingContext *MCtx;
4715   Decl *ManglingContextDecl;
4716   std::tie(MCtx, ManglingContextDecl) =
4717       getCurrentMangleNumberContext(Tag->getDeclContext());
4718   if (MCtx) {
4719     Context.setManglingNumber(
4720         Tag, MCtx->getManglingNumber(
4721                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4722   }
4723 }
4724 
4725 namespace {
4726 struct NonCLikeKind {
4727   enum {
4728     None,
4729     BaseClass,
4730     DefaultMemberInit,
4731     Lambda,
4732     Friend,
4733     OtherMember,
4734     Invalid,
4735   } Kind = None;
4736   SourceRange Range;
4737 
4738   explicit operator bool() { return Kind != None; }
4739 };
4740 }
4741 
4742 /// Determine whether a class is C-like, according to the rules of C++
4743 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4744 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4745   if (RD->isInvalidDecl())
4746     return {NonCLikeKind::Invalid, {}};
4747 
4748   // C++ [dcl.typedef]p9: [P1766R1]
4749   //   An unnamed class with a typedef name for linkage purposes shall not
4750   //
4751   //    -- have any base classes
4752   if (RD->getNumBases())
4753     return {NonCLikeKind::BaseClass,
4754             SourceRange(RD->bases_begin()->getBeginLoc(),
4755                         RD->bases_end()[-1].getEndLoc())};
4756   bool Invalid = false;
4757   for (Decl *D : RD->decls()) {
4758     // Don't complain about things we already diagnosed.
4759     if (D->isInvalidDecl()) {
4760       Invalid = true;
4761       continue;
4762     }
4763 
4764     //  -- have any [...] default member initializers
4765     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4766       if (FD->hasInClassInitializer()) {
4767         auto *Init = FD->getInClassInitializer();
4768         return {NonCLikeKind::DefaultMemberInit,
4769                 Init ? Init->getSourceRange() : D->getSourceRange()};
4770       }
4771       continue;
4772     }
4773 
4774     // FIXME: We don't allow friend declarations. This violates the wording of
4775     // P1766, but not the intent.
4776     if (isa<FriendDecl>(D))
4777       return {NonCLikeKind::Friend, D->getSourceRange()};
4778 
4779     //  -- declare any members other than non-static data members, member
4780     //     enumerations, or member classes,
4781     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4782         isa<EnumDecl>(D))
4783       continue;
4784     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4785     if (!MemberRD) {
4786       if (D->isImplicit())
4787         continue;
4788       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4789     }
4790 
4791     //  -- contain a lambda-expression,
4792     if (MemberRD->isLambda())
4793       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4794 
4795     //  and all member classes shall also satisfy these requirements
4796     //  (recursively).
4797     if (MemberRD->isThisDeclarationADefinition()) {
4798       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4799         return Kind;
4800     }
4801   }
4802 
4803   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4804 }
4805 
4806 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4807                                         TypedefNameDecl *NewTD) {
4808   if (TagFromDeclSpec->isInvalidDecl())
4809     return;
4810 
4811   // Do nothing if the tag already has a name for linkage purposes.
4812   if (TagFromDeclSpec->hasNameForLinkage())
4813     return;
4814 
4815   // A well-formed anonymous tag must always be a TUK_Definition.
4816   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4817 
4818   // The type must match the tag exactly;  no qualifiers allowed.
4819   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4820                            Context.getTagDeclType(TagFromDeclSpec))) {
4821     if (getLangOpts().CPlusPlus)
4822       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4823     return;
4824   }
4825 
4826   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4827   //   An unnamed class with a typedef name for linkage purposes shall [be
4828   //   C-like].
4829   //
4830   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4831   // shouldn't happen, but there are constructs that the language rule doesn't
4832   // disallow for which we can't reasonably avoid computing linkage early.
4833   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4834   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4835                              : NonCLikeKind();
4836   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4837   if (NonCLike || ChangesLinkage) {
4838     if (NonCLike.Kind == NonCLikeKind::Invalid)
4839       return;
4840 
4841     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4842     if (ChangesLinkage) {
4843       // If the linkage changes, we can't accept this as an extension.
4844       if (NonCLike.Kind == NonCLikeKind::None)
4845         DiagID = diag::err_typedef_changes_linkage;
4846       else
4847         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4848     }
4849 
4850     SourceLocation FixitLoc =
4851         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4852     llvm::SmallString<40> TextToInsert;
4853     TextToInsert += ' ';
4854     TextToInsert += NewTD->getIdentifier()->getName();
4855 
4856     Diag(FixitLoc, DiagID)
4857       << isa<TypeAliasDecl>(NewTD)
4858       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4859     if (NonCLike.Kind != NonCLikeKind::None) {
4860       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4861         << NonCLike.Kind - 1 << NonCLike.Range;
4862     }
4863     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4864       << NewTD << isa<TypeAliasDecl>(NewTD);
4865 
4866     if (ChangesLinkage)
4867       return;
4868   }
4869 
4870   // Otherwise, set this as the anon-decl typedef for the tag.
4871   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4872 }
4873 
4874 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4875   switch (T) {
4876   case DeclSpec::TST_class:
4877     return 0;
4878   case DeclSpec::TST_struct:
4879     return 1;
4880   case DeclSpec::TST_interface:
4881     return 2;
4882   case DeclSpec::TST_union:
4883     return 3;
4884   case DeclSpec::TST_enum:
4885     return 4;
4886   default:
4887     llvm_unreachable("unexpected type specifier");
4888   }
4889 }
4890 
4891 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4892 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4893 /// parameters to cope with template friend declarations.
4894 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4895                                        DeclSpec &DS,
4896                                        const ParsedAttributesView &DeclAttrs,
4897                                        MultiTemplateParamsArg TemplateParams,
4898                                        bool IsExplicitInstantiation,
4899                                        RecordDecl *&AnonRecord) {
4900   Decl *TagD = nullptr;
4901   TagDecl *Tag = nullptr;
4902   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4903       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4904       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4905       DS.getTypeSpecType() == DeclSpec::TST_union ||
4906       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4907     TagD = DS.getRepAsDecl();
4908 
4909     if (!TagD) // We probably had an error
4910       return nullptr;
4911 
4912     // Note that the above type specs guarantee that the
4913     // type rep is a Decl, whereas in many of the others
4914     // it's a Type.
4915     if (isa<TagDecl>(TagD))
4916       Tag = cast<TagDecl>(TagD);
4917     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4918       Tag = CTD->getTemplatedDecl();
4919   }
4920 
4921   if (Tag) {
4922     handleTagNumbering(Tag, S);
4923     Tag->setFreeStanding();
4924     if (Tag->isInvalidDecl())
4925       return Tag;
4926   }
4927 
4928   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4929     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4930     // or incomplete types shall not be restrict-qualified."
4931     if (TypeQuals & DeclSpec::TQ_restrict)
4932       Diag(DS.getRestrictSpecLoc(),
4933            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4934            << DS.getSourceRange();
4935   }
4936 
4937   if (DS.isInlineSpecified())
4938     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4939         << getLangOpts().CPlusPlus17;
4940 
4941   if (DS.hasConstexprSpecifier()) {
4942     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4943     // and definitions of functions and variables.
4944     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4945     // the declaration of a function or function template
4946     if (Tag)
4947       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4948           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4949           << static_cast<int>(DS.getConstexprSpecifier());
4950     else
4951       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4952           << static_cast<int>(DS.getConstexprSpecifier());
4953     // Don't emit warnings after this error.
4954     return TagD;
4955   }
4956 
4957   DiagnoseFunctionSpecifiers(DS);
4958 
4959   if (DS.isFriendSpecified()) {
4960     // If we're dealing with a decl but not a TagDecl, assume that
4961     // whatever routines created it handled the friendship aspect.
4962     if (TagD && !Tag)
4963       return nullptr;
4964     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4965   }
4966 
4967   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4968   bool IsExplicitSpecialization =
4969     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4970   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4971       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4972       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4973     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4974     // nested-name-specifier unless it is an explicit instantiation
4975     // or an explicit specialization.
4976     //
4977     // FIXME: We allow class template partial specializations here too, per the
4978     // obvious intent of DR1819.
4979     //
4980     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4981     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4982         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4983     return nullptr;
4984   }
4985 
4986   // Track whether this decl-specifier declares anything.
4987   bool DeclaresAnything = true;
4988 
4989   // Handle anonymous struct definitions.
4990   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4991     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4992         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4993       if (getLangOpts().CPlusPlus ||
4994           Record->getDeclContext()->isRecord()) {
4995         // If CurContext is a DeclContext that can contain statements,
4996         // RecursiveASTVisitor won't visit the decls that
4997         // BuildAnonymousStructOrUnion() will put into CurContext.
4998         // Also store them here so that they can be part of the
4999         // DeclStmt that gets created in this case.
5000         // FIXME: Also return the IndirectFieldDecls created by
5001         // BuildAnonymousStructOr union, for the same reason?
5002         if (CurContext->isFunctionOrMethod())
5003           AnonRecord = Record;
5004         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5005                                            Context.getPrintingPolicy());
5006       }
5007 
5008       DeclaresAnything = false;
5009     }
5010   }
5011 
5012   // C11 6.7.2.1p2:
5013   //   A struct-declaration that does not declare an anonymous structure or
5014   //   anonymous union shall contain a struct-declarator-list.
5015   //
5016   // This rule also existed in C89 and C99; the grammar for struct-declaration
5017   // did not permit a struct-declaration without a struct-declarator-list.
5018   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5019       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5020     // Check for Microsoft C extension: anonymous struct/union member.
5021     // Handle 2 kinds of anonymous struct/union:
5022     //   struct STRUCT;
5023     //   union UNION;
5024     // and
5025     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5026     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5027     if ((Tag && Tag->getDeclName()) ||
5028         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5029       RecordDecl *Record = nullptr;
5030       if (Tag)
5031         Record = dyn_cast<RecordDecl>(Tag);
5032       else if (const RecordType *RT =
5033                    DS.getRepAsType().get()->getAsStructureType())
5034         Record = RT->getDecl();
5035       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5036         Record = UT->getDecl();
5037 
5038       if (Record && getLangOpts().MicrosoftExt) {
5039         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5040             << Record->isUnion() << DS.getSourceRange();
5041         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5042       }
5043 
5044       DeclaresAnything = false;
5045     }
5046   }
5047 
5048   // Skip all the checks below if we have a type error.
5049   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5050       (TagD && TagD->isInvalidDecl()))
5051     return TagD;
5052 
5053   if (getLangOpts().CPlusPlus &&
5054       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5055     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5056       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5057           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5058         DeclaresAnything = false;
5059 
5060   if (!DS.isMissingDeclaratorOk()) {
5061     // Customize diagnostic for a typedef missing a name.
5062     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5063       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5064           << DS.getSourceRange();
5065     else
5066       DeclaresAnything = false;
5067   }
5068 
5069   if (DS.isModulePrivateSpecified() &&
5070       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5071     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5072       << Tag->getTagKind()
5073       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5074 
5075   ActOnDocumentableDecl(TagD);
5076 
5077   // C 6.7/2:
5078   //   A declaration [...] shall declare at least a declarator [...], a tag,
5079   //   or the members of an enumeration.
5080   // C++ [dcl.dcl]p3:
5081   //   [If there are no declarators], and except for the declaration of an
5082   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5083   //   names into the program, or shall redeclare a name introduced by a
5084   //   previous declaration.
5085   if (!DeclaresAnything) {
5086     // In C, we allow this as a (popular) extension / bug. Don't bother
5087     // producing further diagnostics for redundant qualifiers after this.
5088     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5089                                ? diag::err_no_declarators
5090                                : diag::ext_no_declarators)
5091         << DS.getSourceRange();
5092     return TagD;
5093   }
5094 
5095   // C++ [dcl.stc]p1:
5096   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5097   //   init-declarator-list of the declaration shall not be empty.
5098   // C++ [dcl.fct.spec]p1:
5099   //   If a cv-qualifier appears in a decl-specifier-seq, the
5100   //   init-declarator-list of the declaration shall not be empty.
5101   //
5102   // Spurious qualifiers here appear to be valid in C.
5103   unsigned DiagID = diag::warn_standalone_specifier;
5104   if (getLangOpts().CPlusPlus)
5105     DiagID = diag::ext_standalone_specifier;
5106 
5107   // Note that a linkage-specification sets a storage class, but
5108   // 'extern "C" struct foo;' is actually valid and not theoretically
5109   // useless.
5110   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5111     if (SCS == DeclSpec::SCS_mutable)
5112       // Since mutable is not a viable storage class specifier in C, there is
5113       // no reason to treat it as an extension. Instead, diagnose as an error.
5114       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5115     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5116       Diag(DS.getStorageClassSpecLoc(), DiagID)
5117         << DeclSpec::getSpecifierName(SCS);
5118   }
5119 
5120   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5121     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5122       << DeclSpec::getSpecifierName(TSCS);
5123   if (DS.getTypeQualifiers()) {
5124     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5125       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5126     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5127       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5128     // Restrict is covered above.
5129     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5130       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5131     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5132       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5133   }
5134 
5135   // Warn about ignored type attributes, for example:
5136   // __attribute__((aligned)) struct A;
5137   // Attributes should be placed after tag to apply to type declaration.
5138   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5139     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5140     if (TypeSpecType == DeclSpec::TST_class ||
5141         TypeSpecType == DeclSpec::TST_struct ||
5142         TypeSpecType == DeclSpec::TST_interface ||
5143         TypeSpecType == DeclSpec::TST_union ||
5144         TypeSpecType == DeclSpec::TST_enum) {
5145       for (const ParsedAttr &AL : DS.getAttributes())
5146         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5147             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5148       for (const ParsedAttr &AL : DeclAttrs)
5149         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5150             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5151     }
5152   }
5153 
5154   return TagD;
5155 }
5156 
5157 /// We are trying to inject an anonymous member into the given scope;
5158 /// check if there's an existing declaration that can't be overloaded.
5159 ///
5160 /// \return true if this is a forbidden redeclaration
5161 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5162                                          Scope *S,
5163                                          DeclContext *Owner,
5164                                          DeclarationName Name,
5165                                          SourceLocation NameLoc,
5166                                          bool IsUnion) {
5167   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5168                  Sema::ForVisibleRedeclaration);
5169   if (!SemaRef.LookupName(R, S)) return false;
5170 
5171   // Pick a representative declaration.
5172   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5173   assert(PrevDecl && "Expected a non-null Decl");
5174 
5175   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5176     return false;
5177 
5178   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5179     << IsUnion << Name;
5180   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5181 
5182   return true;
5183 }
5184 
5185 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5186 /// anonymous struct or union AnonRecord into the owning context Owner
5187 /// and scope S. This routine will be invoked just after we realize
5188 /// that an unnamed union or struct is actually an anonymous union or
5189 /// struct, e.g.,
5190 ///
5191 /// @code
5192 /// union {
5193 ///   int i;
5194 ///   float f;
5195 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5196 ///    // f into the surrounding scope.x
5197 /// @endcode
5198 ///
5199 /// This routine is recursive, injecting the names of nested anonymous
5200 /// structs/unions into the owning context and scope as well.
5201 static bool
5202 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5203                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5204                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5205   bool Invalid = false;
5206 
5207   // Look every FieldDecl and IndirectFieldDecl with a name.
5208   for (auto *D : AnonRecord->decls()) {
5209     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5210         cast<NamedDecl>(D)->getDeclName()) {
5211       ValueDecl *VD = cast<ValueDecl>(D);
5212       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5213                                        VD->getLocation(),
5214                                        AnonRecord->isUnion())) {
5215         // C++ [class.union]p2:
5216         //   The names of the members of an anonymous union shall be
5217         //   distinct from the names of any other entity in the
5218         //   scope in which the anonymous union is declared.
5219         Invalid = true;
5220       } else {
5221         // C++ [class.union]p2:
5222         //   For the purpose of name lookup, after the anonymous union
5223         //   definition, the members of the anonymous union are
5224         //   considered to have been defined in the scope in which the
5225         //   anonymous union is declared.
5226         unsigned OldChainingSize = Chaining.size();
5227         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5228           Chaining.append(IF->chain_begin(), IF->chain_end());
5229         else
5230           Chaining.push_back(VD);
5231 
5232         assert(Chaining.size() >= 2);
5233         NamedDecl **NamedChain =
5234           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5235         for (unsigned i = 0; i < Chaining.size(); i++)
5236           NamedChain[i] = Chaining[i];
5237 
5238         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5239             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5240             VD->getType(), {NamedChain, Chaining.size()});
5241 
5242         for (const auto *Attr : VD->attrs())
5243           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5244 
5245         IndirectField->setAccess(AS);
5246         IndirectField->setImplicit();
5247         SemaRef.PushOnScopeChains(IndirectField, S);
5248 
5249         // That includes picking up the appropriate access specifier.
5250         if (AS != AS_none) IndirectField->setAccess(AS);
5251 
5252         Chaining.resize(OldChainingSize);
5253       }
5254     }
5255   }
5256 
5257   return Invalid;
5258 }
5259 
5260 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5261 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5262 /// illegal input values are mapped to SC_None.
5263 static StorageClass
5264 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5265   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5266   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5267          "Parser allowed 'typedef' as storage class VarDecl.");
5268   switch (StorageClassSpec) {
5269   case DeclSpec::SCS_unspecified:    return SC_None;
5270   case DeclSpec::SCS_extern:
5271     if (DS.isExternInLinkageSpec())
5272       return SC_None;
5273     return SC_Extern;
5274   case DeclSpec::SCS_static:         return SC_Static;
5275   case DeclSpec::SCS_auto:           return SC_Auto;
5276   case DeclSpec::SCS_register:       return SC_Register;
5277   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5278     // Illegal SCSs map to None: error reporting is up to the caller.
5279   case DeclSpec::SCS_mutable:        // Fall through.
5280   case DeclSpec::SCS_typedef:        return SC_None;
5281   }
5282   llvm_unreachable("unknown storage class specifier");
5283 }
5284 
5285 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5286   assert(Record->hasInClassInitializer());
5287 
5288   for (const auto *I : Record->decls()) {
5289     const auto *FD = dyn_cast<FieldDecl>(I);
5290     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5291       FD = IFD->getAnonField();
5292     if (FD && FD->hasInClassInitializer())
5293       return FD->getLocation();
5294   }
5295 
5296   llvm_unreachable("couldn't find in-class initializer");
5297 }
5298 
5299 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5300                                       SourceLocation DefaultInitLoc) {
5301   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5302     return;
5303 
5304   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5305   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5306 }
5307 
5308 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5309                                       CXXRecordDecl *AnonUnion) {
5310   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5311     return;
5312 
5313   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5314 }
5315 
5316 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5317 /// anonymous structure or union. Anonymous unions are a C++ feature
5318 /// (C++ [class.union]) and a C11 feature; anonymous structures
5319 /// are a C11 feature and GNU C++ extension.
5320 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5321                                         AccessSpecifier AS,
5322                                         RecordDecl *Record,
5323                                         const PrintingPolicy &Policy) {
5324   DeclContext *Owner = Record->getDeclContext();
5325 
5326   // Diagnose whether this anonymous struct/union is an extension.
5327   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5328     Diag(Record->getLocation(), diag::ext_anonymous_union);
5329   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5330     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5331   else if (!Record->isUnion() && !getLangOpts().C11)
5332     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5333 
5334   // C and C++ require different kinds of checks for anonymous
5335   // structs/unions.
5336   bool Invalid = false;
5337   if (getLangOpts().CPlusPlus) {
5338     const char *PrevSpec = nullptr;
5339     if (Record->isUnion()) {
5340       // C++ [class.union]p6:
5341       // C++17 [class.union.anon]p2:
5342       //   Anonymous unions declared in a named namespace or in the
5343       //   global namespace shall be declared static.
5344       unsigned DiagID;
5345       DeclContext *OwnerScope = Owner->getRedeclContext();
5346       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5347           (OwnerScope->isTranslationUnit() ||
5348            (OwnerScope->isNamespace() &&
5349             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5350         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5351           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5352 
5353         // Recover by adding 'static'.
5354         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5355                                PrevSpec, DiagID, Policy);
5356       }
5357       // C++ [class.union]p6:
5358       //   A storage class is not allowed in a declaration of an
5359       //   anonymous union in a class scope.
5360       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5361                isa<RecordDecl>(Owner)) {
5362         Diag(DS.getStorageClassSpecLoc(),
5363              diag::err_anonymous_union_with_storage_spec)
5364           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5365 
5366         // Recover by removing the storage specifier.
5367         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5368                                SourceLocation(),
5369                                PrevSpec, DiagID, Context.getPrintingPolicy());
5370       }
5371     }
5372 
5373     // Ignore const/volatile/restrict qualifiers.
5374     if (DS.getTypeQualifiers()) {
5375       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5376         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5377           << Record->isUnion() << "const"
5378           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5379       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5380         Diag(DS.getVolatileSpecLoc(),
5381              diag::ext_anonymous_struct_union_qualified)
5382           << Record->isUnion() << "volatile"
5383           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5384       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5385         Diag(DS.getRestrictSpecLoc(),
5386              diag::ext_anonymous_struct_union_qualified)
5387           << Record->isUnion() << "restrict"
5388           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5389       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5390         Diag(DS.getAtomicSpecLoc(),
5391              diag::ext_anonymous_struct_union_qualified)
5392           << Record->isUnion() << "_Atomic"
5393           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5394       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5395         Diag(DS.getUnalignedSpecLoc(),
5396              diag::ext_anonymous_struct_union_qualified)
5397           << Record->isUnion() << "__unaligned"
5398           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5399 
5400       DS.ClearTypeQualifiers();
5401     }
5402 
5403     // C++ [class.union]p2:
5404     //   The member-specification of an anonymous union shall only
5405     //   define non-static data members. [Note: nested types and
5406     //   functions cannot be declared within an anonymous union. ]
5407     for (auto *Mem : Record->decls()) {
5408       // Ignore invalid declarations; we already diagnosed them.
5409       if (Mem->isInvalidDecl())
5410         continue;
5411 
5412       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5413         // C++ [class.union]p3:
5414         //   An anonymous union shall not have private or protected
5415         //   members (clause 11).
5416         assert(FD->getAccess() != AS_none);
5417         if (FD->getAccess() != AS_public) {
5418           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5419             << Record->isUnion() << (FD->getAccess() == AS_protected);
5420           Invalid = true;
5421         }
5422 
5423         // C++ [class.union]p1
5424         //   An object of a class with a non-trivial constructor, a non-trivial
5425         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5426         //   assignment operator cannot be a member of a union, nor can an
5427         //   array of such objects.
5428         if (CheckNontrivialField(FD))
5429           Invalid = true;
5430       } else if (Mem->isImplicit()) {
5431         // Any implicit members are fine.
5432       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5433         // This is a type that showed up in an
5434         // elaborated-type-specifier inside the anonymous struct or
5435         // union, but which actually declares a type outside of the
5436         // anonymous struct or union. It's okay.
5437       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5438         if (!MemRecord->isAnonymousStructOrUnion() &&
5439             MemRecord->getDeclName()) {
5440           // Visual C++ allows type definition in anonymous struct or union.
5441           if (getLangOpts().MicrosoftExt)
5442             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5443               << Record->isUnion();
5444           else {
5445             // This is a nested type declaration.
5446             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5447               << Record->isUnion();
5448             Invalid = true;
5449           }
5450         } else {
5451           // This is an anonymous type definition within another anonymous type.
5452           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5453           // not part of standard C++.
5454           Diag(MemRecord->getLocation(),
5455                diag::ext_anonymous_record_with_anonymous_type)
5456             << Record->isUnion();
5457         }
5458       } else if (isa<AccessSpecDecl>(Mem)) {
5459         // Any access specifier is fine.
5460       } else if (isa<StaticAssertDecl>(Mem)) {
5461         // In C++1z, static_assert declarations are also fine.
5462       } else {
5463         // We have something that isn't a non-static data
5464         // member. Complain about it.
5465         unsigned DK = diag::err_anonymous_record_bad_member;
5466         if (isa<TypeDecl>(Mem))
5467           DK = diag::err_anonymous_record_with_type;
5468         else if (isa<FunctionDecl>(Mem))
5469           DK = diag::err_anonymous_record_with_function;
5470         else if (isa<VarDecl>(Mem))
5471           DK = diag::err_anonymous_record_with_static;
5472 
5473         // Visual C++ allows type definition in anonymous struct or union.
5474         if (getLangOpts().MicrosoftExt &&
5475             DK == diag::err_anonymous_record_with_type)
5476           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5477             << Record->isUnion();
5478         else {
5479           Diag(Mem->getLocation(), DK) << Record->isUnion();
5480           Invalid = true;
5481         }
5482       }
5483     }
5484 
5485     // C++11 [class.union]p8 (DR1460):
5486     //   At most one variant member of a union may have a
5487     //   brace-or-equal-initializer.
5488     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5489         Owner->isRecord())
5490       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5491                                 cast<CXXRecordDecl>(Record));
5492   }
5493 
5494   if (!Record->isUnion() && !Owner->isRecord()) {
5495     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5496       << getLangOpts().CPlusPlus;
5497     Invalid = true;
5498   }
5499 
5500   // C++ [dcl.dcl]p3:
5501   //   [If there are no declarators], and except for the declaration of an
5502   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5503   //   names into the program
5504   // C++ [class.mem]p2:
5505   //   each such member-declaration shall either declare at least one member
5506   //   name of the class or declare at least one unnamed bit-field
5507   //
5508   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5509   if (getLangOpts().CPlusPlus && Record->field_empty())
5510     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5511 
5512   // Mock up a declarator.
5513   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5514   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5515   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5516 
5517   // Create a declaration for this anonymous struct/union.
5518   NamedDecl *Anon = nullptr;
5519   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5520     Anon = FieldDecl::Create(
5521         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5522         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5523         /*BitWidth=*/nullptr, /*Mutable=*/false,
5524         /*InitStyle=*/ICIS_NoInit);
5525     Anon->setAccess(AS);
5526     ProcessDeclAttributes(S, Anon, Dc);
5527 
5528     if (getLangOpts().CPlusPlus)
5529       FieldCollector->Add(cast<FieldDecl>(Anon));
5530   } else {
5531     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5532     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5533     if (SCSpec == DeclSpec::SCS_mutable) {
5534       // mutable can only appear on non-static class members, so it's always
5535       // an error here
5536       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5537       Invalid = true;
5538       SC = SC_None;
5539     }
5540 
5541     assert(DS.getAttributes().empty() && "No attribute expected");
5542     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5543                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5544                            Context.getTypeDeclType(Record), TInfo, SC);
5545 
5546     // Default-initialize the implicit variable. This initialization will be
5547     // trivial in almost all cases, except if a union member has an in-class
5548     // initializer:
5549     //   union { int n = 0; };
5550     ActOnUninitializedDecl(Anon);
5551   }
5552   Anon->setImplicit();
5553 
5554   // Mark this as an anonymous struct/union type.
5555   Record->setAnonymousStructOrUnion(true);
5556 
5557   // Add the anonymous struct/union object to the current
5558   // context. We'll be referencing this object when we refer to one of
5559   // its members.
5560   Owner->addDecl(Anon);
5561 
5562   // Inject the members of the anonymous struct/union into the owning
5563   // context and into the identifier resolver chain for name lookup
5564   // purposes.
5565   SmallVector<NamedDecl*, 2> Chain;
5566   Chain.push_back(Anon);
5567 
5568   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5569     Invalid = true;
5570 
5571   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5572     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5573       MangleNumberingContext *MCtx;
5574       Decl *ManglingContextDecl;
5575       std::tie(MCtx, ManglingContextDecl) =
5576           getCurrentMangleNumberContext(NewVD->getDeclContext());
5577       if (MCtx) {
5578         Context.setManglingNumber(
5579             NewVD, MCtx->getManglingNumber(
5580                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5581         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5582       }
5583     }
5584   }
5585 
5586   if (Invalid)
5587     Anon->setInvalidDecl();
5588 
5589   return Anon;
5590 }
5591 
5592 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5593 /// Microsoft C anonymous structure.
5594 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5595 /// Example:
5596 ///
5597 /// struct A { int a; };
5598 /// struct B { struct A; int b; };
5599 ///
5600 /// void foo() {
5601 ///   B var;
5602 ///   var.a = 3;
5603 /// }
5604 ///
5605 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5606                                            RecordDecl *Record) {
5607   assert(Record && "expected a record!");
5608 
5609   // Mock up a declarator.
5610   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5611   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5612   assert(TInfo && "couldn't build declarator info for anonymous struct");
5613 
5614   auto *ParentDecl = cast<RecordDecl>(CurContext);
5615   QualType RecTy = Context.getTypeDeclType(Record);
5616 
5617   // Create a declaration for this anonymous struct.
5618   NamedDecl *Anon =
5619       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5620                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5621                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5622                         /*InitStyle=*/ICIS_NoInit);
5623   Anon->setImplicit();
5624 
5625   // Add the anonymous struct object to the current context.
5626   CurContext->addDecl(Anon);
5627 
5628   // Inject the members of the anonymous struct into the current
5629   // context and into the identifier resolver chain for name lookup
5630   // purposes.
5631   SmallVector<NamedDecl*, 2> Chain;
5632   Chain.push_back(Anon);
5633 
5634   RecordDecl *RecordDef = Record->getDefinition();
5635   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5636                                diag::err_field_incomplete_or_sizeless) ||
5637       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5638                                           AS_none, Chain)) {
5639     Anon->setInvalidDecl();
5640     ParentDecl->setInvalidDecl();
5641   }
5642 
5643   return Anon;
5644 }
5645 
5646 /// GetNameForDeclarator - Determine the full declaration name for the
5647 /// given Declarator.
5648 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5649   return GetNameFromUnqualifiedId(D.getName());
5650 }
5651 
5652 /// Retrieves the declaration name from a parsed unqualified-id.
5653 DeclarationNameInfo
5654 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5655   DeclarationNameInfo NameInfo;
5656   NameInfo.setLoc(Name.StartLocation);
5657 
5658   switch (Name.getKind()) {
5659 
5660   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5661   case UnqualifiedIdKind::IK_Identifier:
5662     NameInfo.setName(Name.Identifier);
5663     return NameInfo;
5664 
5665   case UnqualifiedIdKind::IK_DeductionGuideName: {
5666     // C++ [temp.deduct.guide]p3:
5667     //   The simple-template-id shall name a class template specialization.
5668     //   The template-name shall be the same identifier as the template-name
5669     //   of the simple-template-id.
5670     // These together intend to imply that the template-name shall name a
5671     // class template.
5672     // FIXME: template<typename T> struct X {};
5673     //        template<typename T> using Y = X<T>;
5674     //        Y(int) -> Y<int>;
5675     //   satisfies these rules but does not name a class template.
5676     TemplateName TN = Name.TemplateName.get().get();
5677     auto *Template = TN.getAsTemplateDecl();
5678     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5679       Diag(Name.StartLocation,
5680            diag::err_deduction_guide_name_not_class_template)
5681         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5682       if (Template)
5683         Diag(Template->getLocation(), diag::note_template_decl_here);
5684       return DeclarationNameInfo();
5685     }
5686 
5687     NameInfo.setName(
5688         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5689     return NameInfo;
5690   }
5691 
5692   case UnqualifiedIdKind::IK_OperatorFunctionId:
5693     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5694                                            Name.OperatorFunctionId.Operator));
5695     NameInfo.setCXXOperatorNameRange(SourceRange(
5696         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5697     return NameInfo;
5698 
5699   case UnqualifiedIdKind::IK_LiteralOperatorId:
5700     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5701                                                            Name.Identifier));
5702     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5703     return NameInfo;
5704 
5705   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5706     TypeSourceInfo *TInfo;
5707     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5708     if (Ty.isNull())
5709       return DeclarationNameInfo();
5710     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5711                                                Context.getCanonicalType(Ty)));
5712     NameInfo.setNamedTypeInfo(TInfo);
5713     return NameInfo;
5714   }
5715 
5716   case UnqualifiedIdKind::IK_ConstructorName: {
5717     TypeSourceInfo *TInfo;
5718     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5719     if (Ty.isNull())
5720       return DeclarationNameInfo();
5721     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5722                                               Context.getCanonicalType(Ty)));
5723     NameInfo.setNamedTypeInfo(TInfo);
5724     return NameInfo;
5725   }
5726 
5727   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5728     // In well-formed code, we can only have a constructor
5729     // template-id that refers to the current context, so go there
5730     // to find the actual type being constructed.
5731     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5732     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5733       return DeclarationNameInfo();
5734 
5735     // Determine the type of the class being constructed.
5736     QualType CurClassType = Context.getTypeDeclType(CurClass);
5737 
5738     // FIXME: Check two things: that the template-id names the same type as
5739     // CurClassType, and that the template-id does not occur when the name
5740     // was qualified.
5741 
5742     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5743                                     Context.getCanonicalType(CurClassType)));
5744     // FIXME: should we retrieve TypeSourceInfo?
5745     NameInfo.setNamedTypeInfo(nullptr);
5746     return NameInfo;
5747   }
5748 
5749   case UnqualifiedIdKind::IK_DestructorName: {
5750     TypeSourceInfo *TInfo;
5751     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5752     if (Ty.isNull())
5753       return DeclarationNameInfo();
5754     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5755                                               Context.getCanonicalType(Ty)));
5756     NameInfo.setNamedTypeInfo(TInfo);
5757     return NameInfo;
5758   }
5759 
5760   case UnqualifiedIdKind::IK_TemplateId: {
5761     TemplateName TName = Name.TemplateId->Template.get();
5762     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5763     return Context.getNameForTemplate(TName, TNameLoc);
5764   }
5765 
5766   } // switch (Name.getKind())
5767 
5768   llvm_unreachable("Unknown name kind");
5769 }
5770 
5771 static QualType getCoreType(QualType Ty) {
5772   do {
5773     if (Ty->isPointerType() || Ty->isReferenceType())
5774       Ty = Ty->getPointeeType();
5775     else if (Ty->isArrayType())
5776       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5777     else
5778       return Ty.withoutLocalFastQualifiers();
5779   } while (true);
5780 }
5781 
5782 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5783 /// and Definition have "nearly" matching parameters. This heuristic is
5784 /// used to improve diagnostics in the case where an out-of-line function
5785 /// definition doesn't match any declaration within the class or namespace.
5786 /// Also sets Params to the list of indices to the parameters that differ
5787 /// between the declaration and the definition. If hasSimilarParameters
5788 /// returns true and Params is empty, then all of the parameters match.
5789 static bool hasSimilarParameters(ASTContext &Context,
5790                                      FunctionDecl *Declaration,
5791                                      FunctionDecl *Definition,
5792                                      SmallVectorImpl<unsigned> &Params) {
5793   Params.clear();
5794   if (Declaration->param_size() != Definition->param_size())
5795     return false;
5796   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5797     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5798     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5799 
5800     // The parameter types are identical
5801     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5802       continue;
5803 
5804     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5805     QualType DefParamBaseTy = getCoreType(DefParamTy);
5806     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5807     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5808 
5809     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5810         (DeclTyName && DeclTyName == DefTyName))
5811       Params.push_back(Idx);
5812     else  // The two parameters aren't even close
5813       return false;
5814   }
5815 
5816   return true;
5817 }
5818 
5819 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5820 /// declarator needs to be rebuilt in the current instantiation.
5821 /// Any bits of declarator which appear before the name are valid for
5822 /// consideration here.  That's specifically the type in the decl spec
5823 /// and the base type in any member-pointer chunks.
5824 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5825                                                     DeclarationName Name) {
5826   // The types we specifically need to rebuild are:
5827   //   - typenames, typeofs, and decltypes
5828   //   - types which will become injected class names
5829   // Of course, we also need to rebuild any type referencing such a
5830   // type.  It's safest to just say "dependent", but we call out a
5831   // few cases here.
5832 
5833   DeclSpec &DS = D.getMutableDeclSpec();
5834   switch (DS.getTypeSpecType()) {
5835   case DeclSpec::TST_typename:
5836   case DeclSpec::TST_typeofType:
5837   case DeclSpec::TST_underlyingType:
5838   case DeclSpec::TST_atomic: {
5839     // Grab the type from the parser.
5840     TypeSourceInfo *TSI = nullptr;
5841     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5842     if (T.isNull() || !T->isInstantiationDependentType()) break;
5843 
5844     // Make sure there's a type source info.  This isn't really much
5845     // of a waste; most dependent types should have type source info
5846     // attached already.
5847     if (!TSI)
5848       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5849 
5850     // Rebuild the type in the current instantiation.
5851     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5852     if (!TSI) return true;
5853 
5854     // Store the new type back in the decl spec.
5855     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5856     DS.UpdateTypeRep(LocType);
5857     break;
5858   }
5859 
5860   case DeclSpec::TST_decltype:
5861   case DeclSpec::TST_typeofExpr: {
5862     Expr *E = DS.getRepAsExpr();
5863     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5864     if (Result.isInvalid()) return true;
5865     DS.UpdateExprRep(Result.get());
5866     break;
5867   }
5868 
5869   default:
5870     // Nothing to do for these decl specs.
5871     break;
5872   }
5873 
5874   // It doesn't matter what order we do this in.
5875   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5876     DeclaratorChunk &Chunk = D.getTypeObject(I);
5877 
5878     // The only type information in the declarator which can come
5879     // before the declaration name is the base type of a member
5880     // pointer.
5881     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5882       continue;
5883 
5884     // Rebuild the scope specifier in-place.
5885     CXXScopeSpec &SS = Chunk.Mem.Scope();
5886     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5887       return true;
5888   }
5889 
5890   return false;
5891 }
5892 
5893 /// Returns true if the declaration is declared in a system header or from a
5894 /// system macro.
5895 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5896   return SM.isInSystemHeader(D->getLocation()) ||
5897          SM.isInSystemMacro(D->getLocation());
5898 }
5899 
5900 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5901   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5902   // of system decl.
5903   if (D->getPreviousDecl() || D->isImplicit())
5904     return;
5905   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5906   if (Status != ReservedIdentifierStatus::NotReserved &&
5907       !isFromSystemHeader(Context.getSourceManager(), D)) {
5908     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5909         << D << static_cast<int>(Status);
5910   }
5911 }
5912 
5913 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5914   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5915 
5916   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5917   // declaration only if the `bind_to_declaration` extension is set.
5918   SmallVector<FunctionDecl *, 4> Bases;
5919   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
5920     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
5921               implementation_extension_bind_to_declaration))
5922     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
5923         S, D, MultiTemplateParamsArg(), Bases);
5924 
5925   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5926 
5927   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5928       Dcl && Dcl->getDeclContext()->isFileContext())
5929     Dcl->setTopLevelDeclInObjCContainer();
5930 
5931   if (!Bases.empty())
5932     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
5933 
5934   return Dcl;
5935 }
5936 
5937 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5938 ///   If T is the name of a class, then each of the following shall have a
5939 ///   name different from T:
5940 ///     - every static data member of class T;
5941 ///     - every member function of class T
5942 ///     - every member of class T that is itself a type;
5943 /// \returns true if the declaration name violates these rules.
5944 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5945                                    DeclarationNameInfo NameInfo) {
5946   DeclarationName Name = NameInfo.getName();
5947 
5948   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5949   while (Record && Record->isAnonymousStructOrUnion())
5950     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5951   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5952     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5953     return true;
5954   }
5955 
5956   return false;
5957 }
5958 
5959 /// Diagnose a declaration whose declarator-id has the given
5960 /// nested-name-specifier.
5961 ///
5962 /// \param SS The nested-name-specifier of the declarator-id.
5963 ///
5964 /// \param DC The declaration context to which the nested-name-specifier
5965 /// resolves.
5966 ///
5967 /// \param Name The name of the entity being declared.
5968 ///
5969 /// \param Loc The location of the name of the entity being declared.
5970 ///
5971 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5972 /// we're declaring an explicit / partial specialization / instantiation.
5973 ///
5974 /// \returns true if we cannot safely recover from this error, false otherwise.
5975 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5976                                         DeclarationName Name,
5977                                         SourceLocation Loc, bool IsTemplateId) {
5978   DeclContext *Cur = CurContext;
5979   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5980     Cur = Cur->getParent();
5981 
5982   // If the user provided a superfluous scope specifier that refers back to the
5983   // class in which the entity is already declared, diagnose and ignore it.
5984   //
5985   // class X {
5986   //   void X::f();
5987   // };
5988   //
5989   // Note, it was once ill-formed to give redundant qualification in all
5990   // contexts, but that rule was removed by DR482.
5991   if (Cur->Equals(DC)) {
5992     if (Cur->isRecord()) {
5993       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5994                                       : diag::err_member_extra_qualification)
5995         << Name << FixItHint::CreateRemoval(SS.getRange());
5996       SS.clear();
5997     } else {
5998       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5999     }
6000     return false;
6001   }
6002 
6003   // Check whether the qualifying scope encloses the scope of the original
6004   // declaration. For a template-id, we perform the checks in
6005   // CheckTemplateSpecializationScope.
6006   if (!Cur->Encloses(DC) && !IsTemplateId) {
6007     if (Cur->isRecord())
6008       Diag(Loc, diag::err_member_qualification)
6009         << Name << SS.getRange();
6010     else if (isa<TranslationUnitDecl>(DC))
6011       Diag(Loc, diag::err_invalid_declarator_global_scope)
6012         << Name << SS.getRange();
6013     else if (isa<FunctionDecl>(Cur))
6014       Diag(Loc, diag::err_invalid_declarator_in_function)
6015         << Name << SS.getRange();
6016     else if (isa<BlockDecl>(Cur))
6017       Diag(Loc, diag::err_invalid_declarator_in_block)
6018         << Name << SS.getRange();
6019     else if (isa<ExportDecl>(Cur)) {
6020       if (!isa<NamespaceDecl>(DC))
6021         Diag(Loc, diag::err_export_non_namespace_scope_name)
6022             << Name << SS.getRange();
6023       else
6024         // The cases that DC is not NamespaceDecl should be handled in
6025         // CheckRedeclarationExported.
6026         return false;
6027     } else
6028       Diag(Loc, diag::err_invalid_declarator_scope)
6029       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6030 
6031     return true;
6032   }
6033 
6034   if (Cur->isRecord()) {
6035     // Cannot qualify members within a class.
6036     Diag(Loc, diag::err_member_qualification)
6037       << Name << SS.getRange();
6038     SS.clear();
6039 
6040     // C++ constructors and destructors with incorrect scopes can break
6041     // our AST invariants by having the wrong underlying types. If
6042     // that's the case, then drop this declaration entirely.
6043     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6044          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6045         !Context.hasSameType(Name.getCXXNameType(),
6046                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6047       return true;
6048 
6049     return false;
6050   }
6051 
6052   // C++11 [dcl.meaning]p1:
6053   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6054   //   not begin with a decltype-specifer"
6055   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6056   while (SpecLoc.getPrefix())
6057     SpecLoc = SpecLoc.getPrefix();
6058   if (isa_and_nonnull<DecltypeType>(
6059           SpecLoc.getNestedNameSpecifier()->getAsType()))
6060     Diag(Loc, diag::err_decltype_in_declarator)
6061       << SpecLoc.getTypeLoc().getSourceRange();
6062 
6063   return false;
6064 }
6065 
6066 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6067                                   MultiTemplateParamsArg TemplateParamLists) {
6068   // TODO: consider using NameInfo for diagnostic.
6069   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6070   DeclarationName Name = NameInfo.getName();
6071 
6072   // All of these full declarators require an identifier.  If it doesn't have
6073   // one, the ParsedFreeStandingDeclSpec action should be used.
6074   if (D.isDecompositionDeclarator()) {
6075     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6076   } else if (!Name) {
6077     if (!D.isInvalidType())  // Reject this if we think it is valid.
6078       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6079           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6080     return nullptr;
6081   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6082     return nullptr;
6083 
6084   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6085   // we find one that is.
6086   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6087          (S->getFlags() & Scope::TemplateParamScope) != 0)
6088     S = S->getParent();
6089 
6090   DeclContext *DC = CurContext;
6091   if (D.getCXXScopeSpec().isInvalid())
6092     D.setInvalidType();
6093   else if (D.getCXXScopeSpec().isSet()) {
6094     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6095                                         UPPC_DeclarationQualifier))
6096       return nullptr;
6097 
6098     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6099     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6100     if (!DC || isa<EnumDecl>(DC)) {
6101       // If we could not compute the declaration context, it's because the
6102       // declaration context is dependent but does not refer to a class,
6103       // class template, or class template partial specialization. Complain
6104       // and return early, to avoid the coming semantic disaster.
6105       Diag(D.getIdentifierLoc(),
6106            diag::err_template_qualified_declarator_no_match)
6107         << D.getCXXScopeSpec().getScopeRep()
6108         << D.getCXXScopeSpec().getRange();
6109       return nullptr;
6110     }
6111     bool IsDependentContext = DC->isDependentContext();
6112 
6113     if (!IsDependentContext &&
6114         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6115       return nullptr;
6116 
6117     // If a class is incomplete, do not parse entities inside it.
6118     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6119       Diag(D.getIdentifierLoc(),
6120            diag::err_member_def_undefined_record)
6121         << Name << DC << D.getCXXScopeSpec().getRange();
6122       return nullptr;
6123     }
6124     if (!D.getDeclSpec().isFriendSpecified()) {
6125       if (diagnoseQualifiedDeclaration(
6126               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6127               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6128         if (DC->isRecord())
6129           return nullptr;
6130 
6131         D.setInvalidType();
6132       }
6133     }
6134 
6135     // Check whether we need to rebuild the type of the given
6136     // declaration in the current instantiation.
6137     if (EnteringContext && IsDependentContext &&
6138         TemplateParamLists.size() != 0) {
6139       ContextRAII SavedContext(*this, DC);
6140       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6141         D.setInvalidType();
6142     }
6143   }
6144 
6145   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6146   QualType R = TInfo->getType();
6147 
6148   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6149                                       UPPC_DeclarationType))
6150     D.setInvalidType();
6151 
6152   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6153                         forRedeclarationInCurContext());
6154 
6155   // See if this is a redefinition of a variable in the same scope.
6156   if (!D.getCXXScopeSpec().isSet()) {
6157     bool IsLinkageLookup = false;
6158     bool CreateBuiltins = false;
6159 
6160     // If the declaration we're planning to build will be a function
6161     // or object with linkage, then look for another declaration with
6162     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6163     //
6164     // If the declaration we're planning to build will be declared with
6165     // external linkage in the translation unit, create any builtin with
6166     // the same name.
6167     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6168       /* Do nothing*/;
6169     else if (CurContext->isFunctionOrMethod() &&
6170              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6171               R->isFunctionType())) {
6172       IsLinkageLookup = true;
6173       CreateBuiltins =
6174           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6175     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6176                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6177       CreateBuiltins = true;
6178 
6179     if (IsLinkageLookup) {
6180       Previous.clear(LookupRedeclarationWithLinkage);
6181       Previous.setRedeclarationKind(ForExternalRedeclaration);
6182     }
6183 
6184     LookupName(Previous, S, CreateBuiltins);
6185   } else { // Something like "int foo::x;"
6186     LookupQualifiedName(Previous, DC);
6187 
6188     // C++ [dcl.meaning]p1:
6189     //   When the declarator-id is qualified, the declaration shall refer to a
6190     //  previously declared member of the class or namespace to which the
6191     //  qualifier refers (or, in the case of a namespace, of an element of the
6192     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6193     //  thereof; [...]
6194     //
6195     // Note that we already checked the context above, and that we do not have
6196     // enough information to make sure that Previous contains the declaration
6197     // we want to match. For example, given:
6198     //
6199     //   class X {
6200     //     void f();
6201     //     void f(float);
6202     //   };
6203     //
6204     //   void X::f(int) { } // ill-formed
6205     //
6206     // In this case, Previous will point to the overload set
6207     // containing the two f's declared in X, but neither of them
6208     // matches.
6209 
6210     // C++ [dcl.meaning]p1:
6211     //   [...] the member shall not merely have been introduced by a
6212     //   using-declaration in the scope of the class or namespace nominated by
6213     //   the nested-name-specifier of the declarator-id.
6214     RemoveUsingDecls(Previous);
6215   }
6216 
6217   if (Previous.isSingleResult() &&
6218       Previous.getFoundDecl()->isTemplateParameter()) {
6219     // Maybe we will complain about the shadowed template parameter.
6220     if (!D.isInvalidType())
6221       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6222                                       Previous.getFoundDecl());
6223 
6224     // Just pretend that we didn't see the previous declaration.
6225     Previous.clear();
6226   }
6227 
6228   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6229     // Forget that the previous declaration is the injected-class-name.
6230     Previous.clear();
6231 
6232   // In C++, the previous declaration we find might be a tag type
6233   // (class or enum). In this case, the new declaration will hide the
6234   // tag type. Note that this applies to functions, function templates, and
6235   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6236   if (Previous.isSingleTagDecl() &&
6237       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6238       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6239     Previous.clear();
6240 
6241   // Check that there are no default arguments other than in the parameters
6242   // of a function declaration (C++ only).
6243   if (getLangOpts().CPlusPlus)
6244     CheckExtraCXXDefaultArguments(D);
6245 
6246   NamedDecl *New;
6247 
6248   bool AddToScope = true;
6249   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6250     if (TemplateParamLists.size()) {
6251       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6252       return nullptr;
6253     }
6254 
6255     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6256   } else if (R->isFunctionType()) {
6257     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6258                                   TemplateParamLists,
6259                                   AddToScope);
6260   } else {
6261     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6262                                   AddToScope);
6263   }
6264 
6265   if (!New)
6266     return nullptr;
6267 
6268   // If this has an identifier and is not a function template specialization,
6269   // add it to the scope stack.
6270   if (New->getDeclName() && AddToScope)
6271     PushOnScopeChains(New, S);
6272 
6273   if (isInOpenMPDeclareTargetContext())
6274     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6275 
6276   return New;
6277 }
6278 
6279 /// Helper method to turn variable array types into constant array
6280 /// types in certain situations which would otherwise be errors (for
6281 /// GCC compatibility).
6282 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6283                                                     ASTContext &Context,
6284                                                     bool &SizeIsNegative,
6285                                                     llvm::APSInt &Oversized) {
6286   // This method tries to turn a variable array into a constant
6287   // array even when the size isn't an ICE.  This is necessary
6288   // for compatibility with code that depends on gcc's buggy
6289   // constant expression folding, like struct {char x[(int)(char*)2];}
6290   SizeIsNegative = false;
6291   Oversized = 0;
6292 
6293   if (T->isDependentType())
6294     return QualType();
6295 
6296   QualifierCollector Qs;
6297   const Type *Ty = Qs.strip(T);
6298 
6299   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6300     QualType Pointee = PTy->getPointeeType();
6301     QualType FixedType =
6302         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6303                                             Oversized);
6304     if (FixedType.isNull()) return FixedType;
6305     FixedType = Context.getPointerType(FixedType);
6306     return Qs.apply(Context, FixedType);
6307   }
6308   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6309     QualType Inner = PTy->getInnerType();
6310     QualType FixedType =
6311         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6312                                             Oversized);
6313     if (FixedType.isNull()) return FixedType;
6314     FixedType = Context.getParenType(FixedType);
6315     return Qs.apply(Context, FixedType);
6316   }
6317 
6318   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6319   if (!VLATy)
6320     return QualType();
6321 
6322   QualType ElemTy = VLATy->getElementType();
6323   if (ElemTy->isVariablyModifiedType()) {
6324     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6325                                                  SizeIsNegative, Oversized);
6326     if (ElemTy.isNull())
6327       return QualType();
6328   }
6329 
6330   Expr::EvalResult Result;
6331   if (!VLATy->getSizeExpr() ||
6332       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6333     return QualType();
6334 
6335   llvm::APSInt Res = Result.Val.getInt();
6336 
6337   // Check whether the array size is negative.
6338   if (Res.isSigned() && Res.isNegative()) {
6339     SizeIsNegative = true;
6340     return QualType();
6341   }
6342 
6343   // Check whether the array is too large to be addressed.
6344   unsigned ActiveSizeBits =
6345       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6346        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6347           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6348           : Res.getActiveBits();
6349   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6350     Oversized = Res;
6351     return QualType();
6352   }
6353 
6354   QualType FoldedArrayType = Context.getConstantArrayType(
6355       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6356   return Qs.apply(Context, FoldedArrayType);
6357 }
6358 
6359 static void
6360 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6361   SrcTL = SrcTL.getUnqualifiedLoc();
6362   DstTL = DstTL.getUnqualifiedLoc();
6363   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6364     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6365     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6366                                       DstPTL.getPointeeLoc());
6367     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6368     return;
6369   }
6370   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6371     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6372     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6373                                       DstPTL.getInnerLoc());
6374     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6375     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6376     return;
6377   }
6378   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6379   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6380   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6381   TypeLoc DstElemTL = DstATL.getElementLoc();
6382   if (VariableArrayTypeLoc SrcElemATL =
6383           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6384     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6385     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6386   } else {
6387     DstElemTL.initializeFullCopy(SrcElemTL);
6388   }
6389   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6390   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6391   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6392 }
6393 
6394 /// Helper method to turn variable array types into constant array
6395 /// types in certain situations which would otherwise be errors (for
6396 /// GCC compatibility).
6397 static TypeSourceInfo*
6398 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6399                                               ASTContext &Context,
6400                                               bool &SizeIsNegative,
6401                                               llvm::APSInt &Oversized) {
6402   QualType FixedTy
6403     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6404                                           SizeIsNegative, Oversized);
6405   if (FixedTy.isNull())
6406     return nullptr;
6407   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6408   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6409                                     FixedTInfo->getTypeLoc());
6410   return FixedTInfo;
6411 }
6412 
6413 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6414 /// true if we were successful.
6415 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6416                                            QualType &T, SourceLocation Loc,
6417                                            unsigned FailedFoldDiagID) {
6418   bool SizeIsNegative;
6419   llvm::APSInt Oversized;
6420   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6421       TInfo, Context, SizeIsNegative, Oversized);
6422   if (FixedTInfo) {
6423     Diag(Loc, diag::ext_vla_folded_to_constant);
6424     TInfo = FixedTInfo;
6425     T = FixedTInfo->getType();
6426     return true;
6427   }
6428 
6429   if (SizeIsNegative)
6430     Diag(Loc, diag::err_typecheck_negative_array_size);
6431   else if (Oversized.getBoolValue())
6432     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6433   else if (FailedFoldDiagID)
6434     Diag(Loc, FailedFoldDiagID);
6435   return false;
6436 }
6437 
6438 /// Register the given locally-scoped extern "C" declaration so
6439 /// that it can be found later for redeclarations. We include any extern "C"
6440 /// declaration that is not visible in the translation unit here, not just
6441 /// function-scope declarations.
6442 void
6443 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6444   if (!getLangOpts().CPlusPlus &&
6445       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6446     // Don't need to track declarations in the TU in C.
6447     return;
6448 
6449   // Note that we have a locally-scoped external with this name.
6450   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6451 }
6452 
6453 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6454   // FIXME: We can have multiple results via __attribute__((overloadable)).
6455   auto Result = Context.getExternCContextDecl()->lookup(Name);
6456   return Result.empty() ? nullptr : *Result.begin();
6457 }
6458 
6459 /// Diagnose function specifiers on a declaration of an identifier that
6460 /// does not identify a function.
6461 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6462   // FIXME: We should probably indicate the identifier in question to avoid
6463   // confusion for constructs like "virtual int a(), b;"
6464   if (DS.isVirtualSpecified())
6465     Diag(DS.getVirtualSpecLoc(),
6466          diag::err_virtual_non_function);
6467 
6468   if (DS.hasExplicitSpecifier())
6469     Diag(DS.getExplicitSpecLoc(),
6470          diag::err_explicit_non_function);
6471 
6472   if (DS.isNoreturnSpecified())
6473     Diag(DS.getNoreturnSpecLoc(),
6474          diag::err_noreturn_non_function);
6475 }
6476 
6477 NamedDecl*
6478 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6479                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6480   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6481   if (D.getCXXScopeSpec().isSet()) {
6482     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6483       << D.getCXXScopeSpec().getRange();
6484     D.setInvalidType();
6485     // Pretend we didn't see the scope specifier.
6486     DC = CurContext;
6487     Previous.clear();
6488   }
6489 
6490   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6491 
6492   if (D.getDeclSpec().isInlineSpecified())
6493     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6494         << getLangOpts().CPlusPlus17;
6495   if (D.getDeclSpec().hasConstexprSpecifier())
6496     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6497         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6498 
6499   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6500     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6501       Diag(D.getName().StartLocation,
6502            diag::err_deduction_guide_invalid_specifier)
6503           << "typedef";
6504     else
6505       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6506           << D.getName().getSourceRange();
6507     return nullptr;
6508   }
6509 
6510   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6511   if (!NewTD) return nullptr;
6512 
6513   // Handle attributes prior to checking for duplicates in MergeVarDecl
6514   ProcessDeclAttributes(S, NewTD, D);
6515 
6516   CheckTypedefForVariablyModifiedType(S, NewTD);
6517 
6518   bool Redeclaration = D.isRedeclaration();
6519   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6520   D.setRedeclaration(Redeclaration);
6521   return ND;
6522 }
6523 
6524 void
6525 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6526   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6527   // then it shall have block scope.
6528   // Note that variably modified types must be fixed before merging the decl so
6529   // that redeclarations will match.
6530   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6531   QualType T = TInfo->getType();
6532   if (T->isVariablyModifiedType()) {
6533     setFunctionHasBranchProtectedScope();
6534 
6535     if (S->getFnParent() == nullptr) {
6536       bool SizeIsNegative;
6537       llvm::APSInt Oversized;
6538       TypeSourceInfo *FixedTInfo =
6539         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6540                                                       SizeIsNegative,
6541                                                       Oversized);
6542       if (FixedTInfo) {
6543         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6544         NewTD->setTypeSourceInfo(FixedTInfo);
6545       } else {
6546         if (SizeIsNegative)
6547           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6548         else if (T->isVariableArrayType())
6549           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6550         else if (Oversized.getBoolValue())
6551           Diag(NewTD->getLocation(), diag::err_array_too_large)
6552             << toString(Oversized, 10);
6553         else
6554           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6555         NewTD->setInvalidDecl();
6556       }
6557     }
6558   }
6559 }
6560 
6561 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6562 /// declares a typedef-name, either using the 'typedef' type specifier or via
6563 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6564 NamedDecl*
6565 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6566                            LookupResult &Previous, bool &Redeclaration) {
6567 
6568   // Find the shadowed declaration before filtering for scope.
6569   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6570 
6571   // Merge the decl with the existing one if appropriate. If the decl is
6572   // in an outer scope, it isn't the same thing.
6573   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6574                        /*AllowInlineNamespace*/false);
6575   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6576   if (!Previous.empty()) {
6577     Redeclaration = true;
6578     MergeTypedefNameDecl(S, NewTD, Previous);
6579   } else {
6580     inferGslPointerAttribute(NewTD);
6581   }
6582 
6583   if (ShadowedDecl && !Redeclaration)
6584     CheckShadow(NewTD, ShadowedDecl, Previous);
6585 
6586   // If this is the C FILE type, notify the AST context.
6587   if (IdentifierInfo *II = NewTD->getIdentifier())
6588     if (!NewTD->isInvalidDecl() &&
6589         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6590       if (II->isStr("FILE"))
6591         Context.setFILEDecl(NewTD);
6592       else if (II->isStr("jmp_buf"))
6593         Context.setjmp_bufDecl(NewTD);
6594       else if (II->isStr("sigjmp_buf"))
6595         Context.setsigjmp_bufDecl(NewTD);
6596       else if (II->isStr("ucontext_t"))
6597         Context.setucontext_tDecl(NewTD);
6598     }
6599 
6600   return NewTD;
6601 }
6602 
6603 /// Determines whether the given declaration is an out-of-scope
6604 /// previous declaration.
6605 ///
6606 /// This routine should be invoked when name lookup has found a
6607 /// previous declaration (PrevDecl) that is not in the scope where a
6608 /// new declaration by the same name is being introduced. If the new
6609 /// declaration occurs in a local scope, previous declarations with
6610 /// linkage may still be considered previous declarations (C99
6611 /// 6.2.2p4-5, C++ [basic.link]p6).
6612 ///
6613 /// \param PrevDecl the previous declaration found by name
6614 /// lookup
6615 ///
6616 /// \param DC the context in which the new declaration is being
6617 /// declared.
6618 ///
6619 /// \returns true if PrevDecl is an out-of-scope previous declaration
6620 /// for a new delcaration with the same name.
6621 static bool
6622 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6623                                 ASTContext &Context) {
6624   if (!PrevDecl)
6625     return false;
6626 
6627   if (!PrevDecl->hasLinkage())
6628     return false;
6629 
6630   if (Context.getLangOpts().CPlusPlus) {
6631     // C++ [basic.link]p6:
6632     //   If there is a visible declaration of an entity with linkage
6633     //   having the same name and type, ignoring entities declared
6634     //   outside the innermost enclosing namespace scope, the block
6635     //   scope declaration declares that same entity and receives the
6636     //   linkage of the previous declaration.
6637     DeclContext *OuterContext = DC->getRedeclContext();
6638     if (!OuterContext->isFunctionOrMethod())
6639       // This rule only applies to block-scope declarations.
6640       return false;
6641 
6642     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6643     if (PrevOuterContext->isRecord())
6644       // We found a member function: ignore it.
6645       return false;
6646 
6647     // Find the innermost enclosing namespace for the new and
6648     // previous declarations.
6649     OuterContext = OuterContext->getEnclosingNamespaceContext();
6650     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6651 
6652     // The previous declaration is in a different namespace, so it
6653     // isn't the same function.
6654     if (!OuterContext->Equals(PrevOuterContext))
6655       return false;
6656   }
6657 
6658   return true;
6659 }
6660 
6661 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6662   CXXScopeSpec &SS = D.getCXXScopeSpec();
6663   if (!SS.isSet()) return;
6664   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6665 }
6666 
6667 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6668   QualType type = decl->getType();
6669   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6670   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6671     // Various kinds of declaration aren't allowed to be __autoreleasing.
6672     unsigned kind = -1U;
6673     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6674       if (var->hasAttr<BlocksAttr>())
6675         kind = 0; // __block
6676       else if (!var->hasLocalStorage())
6677         kind = 1; // global
6678     } else if (isa<ObjCIvarDecl>(decl)) {
6679       kind = 3; // ivar
6680     } else if (isa<FieldDecl>(decl)) {
6681       kind = 2; // field
6682     }
6683 
6684     if (kind != -1U) {
6685       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6686         << kind;
6687     }
6688   } else if (lifetime == Qualifiers::OCL_None) {
6689     // Try to infer lifetime.
6690     if (!type->isObjCLifetimeType())
6691       return false;
6692 
6693     lifetime = type->getObjCARCImplicitLifetime();
6694     type = Context.getLifetimeQualifiedType(type, lifetime);
6695     decl->setType(type);
6696   }
6697 
6698   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6699     // Thread-local variables cannot have lifetime.
6700     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6701         var->getTLSKind()) {
6702       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6703         << var->getType();
6704       return true;
6705     }
6706   }
6707 
6708   return false;
6709 }
6710 
6711 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6712   if (Decl->getType().hasAddressSpace())
6713     return;
6714   if (Decl->getType()->isDependentType())
6715     return;
6716   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6717     QualType Type = Var->getType();
6718     if (Type->isSamplerT() || Type->isVoidType())
6719       return;
6720     LangAS ImplAS = LangAS::opencl_private;
6721     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6722     // __opencl_c_program_scope_global_variables feature, the address space
6723     // for a variable at program scope or a static or extern variable inside
6724     // a function are inferred to be __global.
6725     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6726         Var->hasGlobalStorage())
6727       ImplAS = LangAS::opencl_global;
6728     // If the original type from a decayed type is an array type and that array
6729     // type has no address space yet, deduce it now.
6730     if (auto DT = dyn_cast<DecayedType>(Type)) {
6731       auto OrigTy = DT->getOriginalType();
6732       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6733         // Add the address space to the original array type and then propagate
6734         // that to the element type through `getAsArrayType`.
6735         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6736         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6737         // Re-generate the decayed type.
6738         Type = Context.getDecayedType(OrigTy);
6739       }
6740     }
6741     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6742     // Apply any qualifiers (including address space) from the array type to
6743     // the element type. This implements C99 6.7.3p8: "If the specification of
6744     // an array type includes any type qualifiers, the element type is so
6745     // qualified, not the array type."
6746     if (Type->isArrayType())
6747       Type = QualType(Context.getAsArrayType(Type), 0);
6748     Decl->setType(Type);
6749   }
6750 }
6751 
6752 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6753   // Ensure that an auto decl is deduced otherwise the checks below might cache
6754   // the wrong linkage.
6755   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6756 
6757   // 'weak' only applies to declarations with external linkage.
6758   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6759     if (!ND.isExternallyVisible()) {
6760       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6761       ND.dropAttr<WeakAttr>();
6762     }
6763   }
6764   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6765     if (ND.isExternallyVisible()) {
6766       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6767       ND.dropAttr<WeakRefAttr>();
6768       ND.dropAttr<AliasAttr>();
6769     }
6770   }
6771 
6772   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6773     if (VD->hasInit()) {
6774       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6775         assert(VD->isThisDeclarationADefinition() &&
6776                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6777         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6778         VD->dropAttr<AliasAttr>();
6779       }
6780     }
6781   }
6782 
6783   // 'selectany' only applies to externally visible variable declarations.
6784   // It does not apply to functions.
6785   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6786     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6787       S.Diag(Attr->getLocation(),
6788              diag::err_attribute_selectany_non_extern_data);
6789       ND.dropAttr<SelectAnyAttr>();
6790     }
6791   }
6792 
6793   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6794     auto *VD = dyn_cast<VarDecl>(&ND);
6795     bool IsAnonymousNS = false;
6796     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6797     if (VD) {
6798       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6799       while (NS && !IsAnonymousNS) {
6800         IsAnonymousNS = NS->isAnonymousNamespace();
6801         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6802       }
6803     }
6804     // dll attributes require external linkage. Static locals may have external
6805     // linkage but still cannot be explicitly imported or exported.
6806     // In Microsoft mode, a variable defined in anonymous namespace must have
6807     // external linkage in order to be exported.
6808     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6809     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6810         (!AnonNSInMicrosoftMode &&
6811          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6812       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6813         << &ND << Attr;
6814       ND.setInvalidDecl();
6815     }
6816   }
6817 
6818   // Check the attributes on the function type, if any.
6819   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6820     // Don't declare this variable in the second operand of the for-statement;
6821     // GCC miscompiles that by ending its lifetime before evaluating the
6822     // third operand. See gcc.gnu.org/PR86769.
6823     AttributedTypeLoc ATL;
6824     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6825          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6826          TL = ATL.getModifiedLoc()) {
6827       // The [[lifetimebound]] attribute can be applied to the implicit object
6828       // parameter of a non-static member function (other than a ctor or dtor)
6829       // by applying it to the function type.
6830       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6831         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6832         if (!MD || MD->isStatic()) {
6833           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6834               << !MD << A->getRange();
6835         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6836           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6837               << isa<CXXDestructorDecl>(MD) << A->getRange();
6838         }
6839       }
6840     }
6841   }
6842 }
6843 
6844 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6845                                            NamedDecl *NewDecl,
6846                                            bool IsSpecialization,
6847                                            bool IsDefinition) {
6848   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6849     return;
6850 
6851   bool IsTemplate = false;
6852   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6853     OldDecl = OldTD->getTemplatedDecl();
6854     IsTemplate = true;
6855     if (!IsSpecialization)
6856       IsDefinition = false;
6857   }
6858   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6859     NewDecl = NewTD->getTemplatedDecl();
6860     IsTemplate = true;
6861   }
6862 
6863   if (!OldDecl || !NewDecl)
6864     return;
6865 
6866   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6867   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6868   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6869   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6870 
6871   // dllimport and dllexport are inheritable attributes so we have to exclude
6872   // inherited attribute instances.
6873   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6874                     (NewExportAttr && !NewExportAttr->isInherited());
6875 
6876   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6877   // the only exception being explicit specializations.
6878   // Implicitly generated declarations are also excluded for now because there
6879   // is no other way to switch these to use dllimport or dllexport.
6880   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6881 
6882   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6883     // Allow with a warning for free functions and global variables.
6884     bool JustWarn = false;
6885     if (!OldDecl->isCXXClassMember()) {
6886       auto *VD = dyn_cast<VarDecl>(OldDecl);
6887       if (VD && !VD->getDescribedVarTemplate())
6888         JustWarn = true;
6889       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6890       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6891         JustWarn = true;
6892     }
6893 
6894     // We cannot change a declaration that's been used because IR has already
6895     // been emitted. Dllimported functions will still work though (modulo
6896     // address equality) as they can use the thunk.
6897     if (OldDecl->isUsed())
6898       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6899         JustWarn = false;
6900 
6901     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6902                                : diag::err_attribute_dll_redeclaration;
6903     S.Diag(NewDecl->getLocation(), DiagID)
6904         << NewDecl
6905         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6906     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6907     if (!JustWarn) {
6908       NewDecl->setInvalidDecl();
6909       return;
6910     }
6911   }
6912 
6913   // A redeclaration is not allowed to drop a dllimport attribute, the only
6914   // exceptions being inline function definitions (except for function
6915   // templates), local extern declarations, qualified friend declarations or
6916   // special MSVC extension: in the last case, the declaration is treated as if
6917   // it were marked dllexport.
6918   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6919   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6920   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6921     // Ignore static data because out-of-line definitions are diagnosed
6922     // separately.
6923     IsStaticDataMember = VD->isStaticDataMember();
6924     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6925                    VarDecl::DeclarationOnly;
6926   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6927     IsInline = FD->isInlined();
6928     IsQualifiedFriend = FD->getQualifier() &&
6929                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6930   }
6931 
6932   if (OldImportAttr && !HasNewAttr &&
6933       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6934       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6935     if (IsMicrosoftABI && IsDefinition) {
6936       S.Diag(NewDecl->getLocation(),
6937              diag::warn_redeclaration_without_import_attribute)
6938           << NewDecl;
6939       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6940       NewDecl->dropAttr<DLLImportAttr>();
6941       NewDecl->addAttr(
6942           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6943     } else {
6944       S.Diag(NewDecl->getLocation(),
6945              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6946           << NewDecl << OldImportAttr;
6947       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6948       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6949       OldDecl->dropAttr<DLLImportAttr>();
6950       NewDecl->dropAttr<DLLImportAttr>();
6951     }
6952   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6953     // In MinGW, seeing a function declared inline drops the dllimport
6954     // attribute.
6955     OldDecl->dropAttr<DLLImportAttr>();
6956     NewDecl->dropAttr<DLLImportAttr>();
6957     S.Diag(NewDecl->getLocation(),
6958            diag::warn_dllimport_dropped_from_inline_function)
6959         << NewDecl << OldImportAttr;
6960   }
6961 
6962   // A specialization of a class template member function is processed here
6963   // since it's a redeclaration. If the parent class is dllexport, the
6964   // specialization inherits that attribute. This doesn't happen automatically
6965   // since the parent class isn't instantiated until later.
6966   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6967     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6968         !NewImportAttr && !NewExportAttr) {
6969       if (const DLLExportAttr *ParentExportAttr =
6970               MD->getParent()->getAttr<DLLExportAttr>()) {
6971         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6972         NewAttr->setInherited(true);
6973         NewDecl->addAttr(NewAttr);
6974       }
6975     }
6976   }
6977 }
6978 
6979 /// Given that we are within the definition of the given function,
6980 /// will that definition behave like C99's 'inline', where the
6981 /// definition is discarded except for optimization purposes?
6982 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6983   // Try to avoid calling GetGVALinkageForFunction.
6984 
6985   // All cases of this require the 'inline' keyword.
6986   if (!FD->isInlined()) return false;
6987 
6988   // This is only possible in C++ with the gnu_inline attribute.
6989   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6990     return false;
6991 
6992   // Okay, go ahead and call the relatively-more-expensive function.
6993   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6994 }
6995 
6996 /// Determine whether a variable is extern "C" prior to attaching
6997 /// an initializer. We can't just call isExternC() here, because that
6998 /// will also compute and cache whether the declaration is externally
6999 /// visible, which might change when we attach the initializer.
7000 ///
7001 /// This can only be used if the declaration is known to not be a
7002 /// redeclaration of an internal linkage declaration.
7003 ///
7004 /// For instance:
7005 ///
7006 ///   auto x = []{};
7007 ///
7008 /// Attaching the initializer here makes this declaration not externally
7009 /// visible, because its type has internal linkage.
7010 ///
7011 /// FIXME: This is a hack.
7012 template<typename T>
7013 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7014   if (S.getLangOpts().CPlusPlus) {
7015     // In C++, the overloadable attribute negates the effects of extern "C".
7016     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7017       return false;
7018 
7019     // So do CUDA's host/device attributes.
7020     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7021                                  D->template hasAttr<CUDAHostAttr>()))
7022       return false;
7023   }
7024   return D->isExternC();
7025 }
7026 
7027 static bool shouldConsiderLinkage(const VarDecl *VD) {
7028   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7029   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7030       isa<OMPDeclareMapperDecl>(DC))
7031     return VD->hasExternalStorage();
7032   if (DC->isFileContext())
7033     return true;
7034   if (DC->isRecord())
7035     return false;
7036   if (isa<RequiresExprBodyDecl>(DC))
7037     return false;
7038   llvm_unreachable("Unexpected context");
7039 }
7040 
7041 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7042   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7043   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7044       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7045     return true;
7046   if (DC->isRecord())
7047     return false;
7048   llvm_unreachable("Unexpected context");
7049 }
7050 
7051 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7052                           ParsedAttr::Kind Kind) {
7053   // Check decl attributes on the DeclSpec.
7054   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7055     return true;
7056 
7057   // Walk the declarator structure, checking decl attributes that were in a type
7058   // position to the decl itself.
7059   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7060     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7061       return true;
7062   }
7063 
7064   // Finally, check attributes on the decl itself.
7065   return PD.getAttributes().hasAttribute(Kind) ||
7066          PD.getDeclarationAttributes().hasAttribute(Kind);
7067 }
7068 
7069 /// Adjust the \c DeclContext for a function or variable that might be a
7070 /// function-local external declaration.
7071 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7072   if (!DC->isFunctionOrMethod())
7073     return false;
7074 
7075   // If this is a local extern function or variable declared within a function
7076   // template, don't add it into the enclosing namespace scope until it is
7077   // instantiated; it might have a dependent type right now.
7078   if (DC->isDependentContext())
7079     return true;
7080 
7081   // C++11 [basic.link]p7:
7082   //   When a block scope declaration of an entity with linkage is not found to
7083   //   refer to some other declaration, then that entity is a member of the
7084   //   innermost enclosing namespace.
7085   //
7086   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7087   // semantically-enclosing namespace, not a lexically-enclosing one.
7088   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7089     DC = DC->getParent();
7090   return true;
7091 }
7092 
7093 /// Returns true if given declaration has external C language linkage.
7094 static bool isDeclExternC(const Decl *D) {
7095   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7096     return FD->isExternC();
7097   if (const auto *VD = dyn_cast<VarDecl>(D))
7098     return VD->isExternC();
7099 
7100   llvm_unreachable("Unknown type of decl!");
7101 }
7102 
7103 /// Returns true if there hasn't been any invalid type diagnosed.
7104 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7105   DeclContext *DC = NewVD->getDeclContext();
7106   QualType R = NewVD->getType();
7107 
7108   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7109   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7110   // argument.
7111   if (R->isImageType() || R->isPipeType()) {
7112     Se.Diag(NewVD->getLocation(),
7113             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7114         << R;
7115     NewVD->setInvalidDecl();
7116     return false;
7117   }
7118 
7119   // OpenCL v1.2 s6.9.r:
7120   // The event type cannot be used to declare a program scope variable.
7121   // OpenCL v2.0 s6.9.q:
7122   // The clk_event_t and reserve_id_t types cannot be declared in program
7123   // scope.
7124   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7125     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7126       Se.Diag(NewVD->getLocation(),
7127               diag::err_invalid_type_for_program_scope_var)
7128           << R;
7129       NewVD->setInvalidDecl();
7130       return false;
7131     }
7132   }
7133 
7134   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7135   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7136                                                Se.getLangOpts())) {
7137     QualType NR = R.getCanonicalType();
7138     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7139            NR->isReferenceType()) {
7140       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7141           NR->isFunctionReferenceType()) {
7142         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7143             << NR->isReferenceType();
7144         NewVD->setInvalidDecl();
7145         return false;
7146       }
7147       NR = NR->getPointeeType();
7148     }
7149   }
7150 
7151   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7152                                                Se.getLangOpts())) {
7153     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7154     // half array type (unless the cl_khr_fp16 extension is enabled).
7155     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7156       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7157       NewVD->setInvalidDecl();
7158       return false;
7159     }
7160   }
7161 
7162   // OpenCL v1.2 s6.9.r:
7163   // The event type cannot be used with the __local, __constant and __global
7164   // address space qualifiers.
7165   if (R->isEventT()) {
7166     if (R.getAddressSpace() != LangAS::opencl_private) {
7167       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7168       NewVD->setInvalidDecl();
7169       return false;
7170     }
7171   }
7172 
7173   if (R->isSamplerT()) {
7174     // OpenCL v1.2 s6.9.b p4:
7175     // The sampler type cannot be used with the __local and __global address
7176     // space qualifiers.
7177     if (R.getAddressSpace() == LangAS::opencl_local ||
7178         R.getAddressSpace() == LangAS::opencl_global) {
7179       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7180       NewVD->setInvalidDecl();
7181     }
7182 
7183     // OpenCL v1.2 s6.12.14.1:
7184     // A global sampler must be declared with either the constant address
7185     // space qualifier or with the const qualifier.
7186     if (DC->isTranslationUnit() &&
7187         !(R.getAddressSpace() == LangAS::opencl_constant ||
7188           R.isConstQualified())) {
7189       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7190       NewVD->setInvalidDecl();
7191     }
7192     if (NewVD->isInvalidDecl())
7193       return false;
7194   }
7195 
7196   return true;
7197 }
7198 
7199 template <typename AttrTy>
7200 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7201   const TypedefNameDecl *TND = TT->getDecl();
7202   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7203     AttrTy *Clone = Attribute->clone(S.Context);
7204     Clone->setInherited(true);
7205     D->addAttr(Clone);
7206   }
7207 }
7208 
7209 NamedDecl *Sema::ActOnVariableDeclarator(
7210     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7211     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7212     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7213   QualType R = TInfo->getType();
7214   DeclarationName Name = GetNameForDeclarator(D).getName();
7215 
7216   IdentifierInfo *II = Name.getAsIdentifierInfo();
7217 
7218   if (D.isDecompositionDeclarator()) {
7219     // Take the name of the first declarator as our name for diagnostic
7220     // purposes.
7221     auto &Decomp = D.getDecompositionDeclarator();
7222     if (!Decomp.bindings().empty()) {
7223       II = Decomp.bindings()[0].Name;
7224       Name = II;
7225     }
7226   } else if (!II) {
7227     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7228     return nullptr;
7229   }
7230 
7231 
7232   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7233   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7234 
7235   // dllimport globals without explicit storage class are treated as extern. We
7236   // have to change the storage class this early to get the right DeclContext.
7237   if (SC == SC_None && !DC->isRecord() &&
7238       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7239       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7240     SC = SC_Extern;
7241 
7242   DeclContext *OriginalDC = DC;
7243   bool IsLocalExternDecl = SC == SC_Extern &&
7244                            adjustContextForLocalExternDecl(DC);
7245 
7246   if (SCSpec == DeclSpec::SCS_mutable) {
7247     // mutable can only appear on non-static class members, so it's always
7248     // an error here
7249     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7250     D.setInvalidType();
7251     SC = SC_None;
7252   }
7253 
7254   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7255       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7256                               D.getDeclSpec().getStorageClassSpecLoc())) {
7257     // In C++11, the 'register' storage class specifier is deprecated.
7258     // Suppress the warning in system macros, it's used in macros in some
7259     // popular C system headers, such as in glibc's htonl() macro.
7260     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7261          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7262                                    : diag::warn_deprecated_register)
7263       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7264   }
7265 
7266   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7267 
7268   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7269     // C99 6.9p2: The storage-class specifiers auto and register shall not
7270     // appear in the declaration specifiers in an external declaration.
7271     // Global Register+Asm is a GNU extension we support.
7272     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7273       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7274       D.setInvalidType();
7275     }
7276   }
7277 
7278   // If this variable has a VLA type and an initializer, try to
7279   // fold to a constant-sized type. This is otherwise invalid.
7280   if (D.hasInitializer() && R->isVariableArrayType())
7281     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7282                                     /*DiagID=*/0);
7283 
7284   bool IsMemberSpecialization = false;
7285   bool IsVariableTemplateSpecialization = false;
7286   bool IsPartialSpecialization = false;
7287   bool IsVariableTemplate = false;
7288   VarDecl *NewVD = nullptr;
7289   VarTemplateDecl *NewTemplate = nullptr;
7290   TemplateParameterList *TemplateParams = nullptr;
7291   if (!getLangOpts().CPlusPlus) {
7292     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7293                             II, R, TInfo, SC);
7294 
7295     if (R->getContainedDeducedType())
7296       ParsingInitForAutoVars.insert(NewVD);
7297 
7298     if (D.isInvalidType())
7299       NewVD->setInvalidDecl();
7300 
7301     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7302         NewVD->hasLocalStorage())
7303       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7304                             NTCUC_AutoVar, NTCUK_Destruct);
7305   } else {
7306     bool Invalid = false;
7307 
7308     if (DC->isRecord() && !CurContext->isRecord()) {
7309       // This is an out-of-line definition of a static data member.
7310       switch (SC) {
7311       case SC_None:
7312         break;
7313       case SC_Static:
7314         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7315              diag::err_static_out_of_line)
7316           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7317         break;
7318       case SC_Auto:
7319       case SC_Register:
7320       case SC_Extern:
7321         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7322         // to names of variables declared in a block or to function parameters.
7323         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7324         // of class members
7325 
7326         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7327              diag::err_storage_class_for_static_member)
7328           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7329         break;
7330       case SC_PrivateExtern:
7331         llvm_unreachable("C storage class in c++!");
7332       }
7333     }
7334 
7335     if (SC == SC_Static && CurContext->isRecord()) {
7336       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7337         // Walk up the enclosing DeclContexts to check for any that are
7338         // incompatible with static data members.
7339         const DeclContext *FunctionOrMethod = nullptr;
7340         const CXXRecordDecl *AnonStruct = nullptr;
7341         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7342           if (Ctxt->isFunctionOrMethod()) {
7343             FunctionOrMethod = Ctxt;
7344             break;
7345           }
7346           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7347           if (ParentDecl && !ParentDecl->getDeclName()) {
7348             AnonStruct = ParentDecl;
7349             break;
7350           }
7351         }
7352         if (FunctionOrMethod) {
7353           // C++ [class.static.data]p5: A local class shall not have static data
7354           // members.
7355           Diag(D.getIdentifierLoc(),
7356                diag::err_static_data_member_not_allowed_in_local_class)
7357             << Name << RD->getDeclName() << RD->getTagKind();
7358         } else if (AnonStruct) {
7359           // C++ [class.static.data]p4: Unnamed classes and classes contained
7360           // directly or indirectly within unnamed classes shall not contain
7361           // static data members.
7362           Diag(D.getIdentifierLoc(),
7363                diag::err_static_data_member_not_allowed_in_anon_struct)
7364             << Name << AnonStruct->getTagKind();
7365           Invalid = true;
7366         } else if (RD->isUnion()) {
7367           // C++98 [class.union]p1: If a union contains a static data member,
7368           // the program is ill-formed. C++11 drops this restriction.
7369           Diag(D.getIdentifierLoc(),
7370                getLangOpts().CPlusPlus11
7371                  ? diag::warn_cxx98_compat_static_data_member_in_union
7372                  : diag::ext_static_data_member_in_union) << Name;
7373         }
7374       }
7375     }
7376 
7377     // Match up the template parameter lists with the scope specifier, then
7378     // determine whether we have a template or a template specialization.
7379     bool InvalidScope = false;
7380     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7381         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7382         D.getCXXScopeSpec(),
7383         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7384             ? D.getName().TemplateId
7385             : nullptr,
7386         TemplateParamLists,
7387         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7388     Invalid |= InvalidScope;
7389 
7390     if (TemplateParams) {
7391       if (!TemplateParams->size() &&
7392           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7393         // There is an extraneous 'template<>' for this variable. Complain
7394         // about it, but allow the declaration of the variable.
7395         Diag(TemplateParams->getTemplateLoc(),
7396              diag::err_template_variable_noparams)
7397           << II
7398           << SourceRange(TemplateParams->getTemplateLoc(),
7399                          TemplateParams->getRAngleLoc());
7400         TemplateParams = nullptr;
7401       } else {
7402         // Check that we can declare a template here.
7403         if (CheckTemplateDeclScope(S, TemplateParams))
7404           return nullptr;
7405 
7406         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7407           // This is an explicit specialization or a partial specialization.
7408           IsVariableTemplateSpecialization = true;
7409           IsPartialSpecialization = TemplateParams->size() > 0;
7410         } else { // if (TemplateParams->size() > 0)
7411           // This is a template declaration.
7412           IsVariableTemplate = true;
7413 
7414           // Only C++1y supports variable templates (N3651).
7415           Diag(D.getIdentifierLoc(),
7416                getLangOpts().CPlusPlus14
7417                    ? diag::warn_cxx11_compat_variable_template
7418                    : diag::ext_variable_template);
7419         }
7420       }
7421     } else {
7422       // Check that we can declare a member specialization here.
7423       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7424           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7425         return nullptr;
7426       assert((Invalid ||
7427               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7428              "should have a 'template<>' for this decl");
7429     }
7430 
7431     if (IsVariableTemplateSpecialization) {
7432       SourceLocation TemplateKWLoc =
7433           TemplateParamLists.size() > 0
7434               ? TemplateParamLists[0]->getTemplateLoc()
7435               : SourceLocation();
7436       DeclResult Res = ActOnVarTemplateSpecialization(
7437           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7438           IsPartialSpecialization);
7439       if (Res.isInvalid())
7440         return nullptr;
7441       NewVD = cast<VarDecl>(Res.get());
7442       AddToScope = false;
7443     } else if (D.isDecompositionDeclarator()) {
7444       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7445                                         D.getIdentifierLoc(), R, TInfo, SC,
7446                                         Bindings);
7447     } else
7448       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7449                               D.getIdentifierLoc(), II, R, TInfo, SC);
7450 
7451     // If this is supposed to be a variable template, create it as such.
7452     if (IsVariableTemplate) {
7453       NewTemplate =
7454           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7455                                   TemplateParams, NewVD);
7456       NewVD->setDescribedVarTemplate(NewTemplate);
7457     }
7458 
7459     // If this decl has an auto type in need of deduction, make a note of the
7460     // Decl so we can diagnose uses of it in its own initializer.
7461     if (R->getContainedDeducedType())
7462       ParsingInitForAutoVars.insert(NewVD);
7463 
7464     if (D.isInvalidType() || Invalid) {
7465       NewVD->setInvalidDecl();
7466       if (NewTemplate)
7467         NewTemplate->setInvalidDecl();
7468     }
7469 
7470     SetNestedNameSpecifier(*this, NewVD, D);
7471 
7472     // If we have any template parameter lists that don't directly belong to
7473     // the variable (matching the scope specifier), store them.
7474     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7475     if (TemplateParamLists.size() > VDTemplateParamLists)
7476       NewVD->setTemplateParameterListsInfo(
7477           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7478   }
7479 
7480   if (D.getDeclSpec().isInlineSpecified()) {
7481     if (!getLangOpts().CPlusPlus) {
7482       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7483           << 0;
7484     } else if (CurContext->isFunctionOrMethod()) {
7485       // 'inline' is not allowed on block scope variable declaration.
7486       Diag(D.getDeclSpec().getInlineSpecLoc(),
7487            diag::err_inline_declaration_block_scope) << Name
7488         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7489     } else {
7490       Diag(D.getDeclSpec().getInlineSpecLoc(),
7491            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7492                                      : diag::ext_inline_variable);
7493       NewVD->setInlineSpecified();
7494     }
7495   }
7496 
7497   // Set the lexical context. If the declarator has a C++ scope specifier, the
7498   // lexical context will be different from the semantic context.
7499   NewVD->setLexicalDeclContext(CurContext);
7500   if (NewTemplate)
7501     NewTemplate->setLexicalDeclContext(CurContext);
7502 
7503   if (IsLocalExternDecl) {
7504     if (D.isDecompositionDeclarator())
7505       for (auto *B : Bindings)
7506         B->setLocalExternDecl();
7507     else
7508       NewVD->setLocalExternDecl();
7509   }
7510 
7511   bool EmitTLSUnsupportedError = false;
7512   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7513     // C++11 [dcl.stc]p4:
7514     //   When thread_local is applied to a variable of block scope the
7515     //   storage-class-specifier static is implied if it does not appear
7516     //   explicitly.
7517     // Core issue: 'static' is not implied if the variable is declared
7518     //   'extern'.
7519     if (NewVD->hasLocalStorage() &&
7520         (SCSpec != DeclSpec::SCS_unspecified ||
7521          TSCS != DeclSpec::TSCS_thread_local ||
7522          !DC->isFunctionOrMethod()))
7523       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7524            diag::err_thread_non_global)
7525         << DeclSpec::getSpecifierName(TSCS);
7526     else if (!Context.getTargetInfo().isTLSSupported()) {
7527       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7528           getLangOpts().SYCLIsDevice) {
7529         // Postpone error emission until we've collected attributes required to
7530         // figure out whether it's a host or device variable and whether the
7531         // error should be ignored.
7532         EmitTLSUnsupportedError = true;
7533         // We still need to mark the variable as TLS so it shows up in AST with
7534         // proper storage class for other tools to use even if we're not going
7535         // to emit any code for it.
7536         NewVD->setTSCSpec(TSCS);
7537       } else
7538         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7539              diag::err_thread_unsupported);
7540     } else
7541       NewVD->setTSCSpec(TSCS);
7542   }
7543 
7544   switch (D.getDeclSpec().getConstexprSpecifier()) {
7545   case ConstexprSpecKind::Unspecified:
7546     break;
7547 
7548   case ConstexprSpecKind::Consteval:
7549     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7550          diag::err_constexpr_wrong_decl_kind)
7551         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7552     LLVM_FALLTHROUGH;
7553 
7554   case ConstexprSpecKind::Constexpr:
7555     NewVD->setConstexpr(true);
7556     // C++1z [dcl.spec.constexpr]p1:
7557     //   A static data member declared with the constexpr specifier is
7558     //   implicitly an inline variable.
7559     if (NewVD->isStaticDataMember() &&
7560         (getLangOpts().CPlusPlus17 ||
7561          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7562       NewVD->setImplicitlyInline();
7563     break;
7564 
7565   case ConstexprSpecKind::Constinit:
7566     if (!NewVD->hasGlobalStorage())
7567       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7568            diag::err_constinit_local_variable);
7569     else
7570       NewVD->addAttr(ConstInitAttr::Create(
7571           Context, D.getDeclSpec().getConstexprSpecLoc(),
7572           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7573     break;
7574   }
7575 
7576   // C99 6.7.4p3
7577   //   An inline definition of a function with external linkage shall
7578   //   not contain a definition of a modifiable object with static or
7579   //   thread storage duration...
7580   // We only apply this when the function is required to be defined
7581   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7582   // that a local variable with thread storage duration still has to
7583   // be marked 'static'.  Also note that it's possible to get these
7584   // semantics in C++ using __attribute__((gnu_inline)).
7585   if (SC == SC_Static && S->getFnParent() != nullptr &&
7586       !NewVD->getType().isConstQualified()) {
7587     FunctionDecl *CurFD = getCurFunctionDecl();
7588     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7589       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7590            diag::warn_static_local_in_extern_inline);
7591       MaybeSuggestAddingStaticToDecl(CurFD);
7592     }
7593   }
7594 
7595   if (D.getDeclSpec().isModulePrivateSpecified()) {
7596     if (IsVariableTemplateSpecialization)
7597       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7598           << (IsPartialSpecialization ? 1 : 0)
7599           << FixItHint::CreateRemoval(
7600                  D.getDeclSpec().getModulePrivateSpecLoc());
7601     else if (IsMemberSpecialization)
7602       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7603         << 2
7604         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7605     else if (NewVD->hasLocalStorage())
7606       Diag(NewVD->getLocation(), diag::err_module_private_local)
7607           << 0 << NewVD
7608           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7609           << FixItHint::CreateRemoval(
7610                  D.getDeclSpec().getModulePrivateSpecLoc());
7611     else {
7612       NewVD->setModulePrivate();
7613       if (NewTemplate)
7614         NewTemplate->setModulePrivate();
7615       for (auto *B : Bindings)
7616         B->setModulePrivate();
7617     }
7618   }
7619 
7620   if (getLangOpts().OpenCL) {
7621     deduceOpenCLAddressSpace(NewVD);
7622 
7623     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7624     if (TSC != TSCS_unspecified) {
7625       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7626            diag::err_opencl_unknown_type_specifier)
7627           << getLangOpts().getOpenCLVersionString()
7628           << DeclSpec::getSpecifierName(TSC) << 1;
7629       NewVD->setInvalidDecl();
7630     }
7631   }
7632 
7633   // Handle attributes prior to checking for duplicates in MergeVarDecl
7634   ProcessDeclAttributes(S, NewVD, D);
7635 
7636   // FIXME: This is probably the wrong location to be doing this and we should
7637   // probably be doing this for more attributes (especially for function
7638   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7639   // the code to copy attributes would be generated by TableGen.
7640   if (R->isFunctionPointerType())
7641     if (const auto *TT = R->getAs<TypedefType>())
7642       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7643 
7644   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7645       getLangOpts().SYCLIsDevice) {
7646     if (EmitTLSUnsupportedError &&
7647         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7648          (getLangOpts().OpenMPIsDevice &&
7649           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7650       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7651            diag::err_thread_unsupported);
7652 
7653     if (EmitTLSUnsupportedError &&
7654         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7655       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7656     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7657     // storage [duration]."
7658     if (SC == SC_None && S->getFnParent() != nullptr &&
7659         (NewVD->hasAttr<CUDASharedAttr>() ||
7660          NewVD->hasAttr<CUDAConstantAttr>())) {
7661       NewVD->setStorageClass(SC_Static);
7662     }
7663   }
7664 
7665   // Ensure that dllimport globals without explicit storage class are treated as
7666   // extern. The storage class is set above using parsed attributes. Now we can
7667   // check the VarDecl itself.
7668   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7669          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7670          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7671 
7672   // In auto-retain/release, infer strong retension for variables of
7673   // retainable type.
7674   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7675     NewVD->setInvalidDecl();
7676 
7677   // Handle GNU asm-label extension (encoded as an attribute).
7678   if (Expr *E = (Expr*)D.getAsmLabel()) {
7679     // The parser guarantees this is a string.
7680     StringLiteral *SE = cast<StringLiteral>(E);
7681     StringRef Label = SE->getString();
7682     if (S->getFnParent() != nullptr) {
7683       switch (SC) {
7684       case SC_None:
7685       case SC_Auto:
7686         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7687         break;
7688       case SC_Register:
7689         // Local Named register
7690         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7691             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7692           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7693         break;
7694       case SC_Static:
7695       case SC_Extern:
7696       case SC_PrivateExtern:
7697         break;
7698       }
7699     } else if (SC == SC_Register) {
7700       // Global Named register
7701       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7702         const auto &TI = Context.getTargetInfo();
7703         bool HasSizeMismatch;
7704 
7705         if (!TI.isValidGCCRegisterName(Label))
7706           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7707         else if (!TI.validateGlobalRegisterVariable(Label,
7708                                                     Context.getTypeSize(R),
7709                                                     HasSizeMismatch))
7710           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7711         else if (HasSizeMismatch)
7712           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7713       }
7714 
7715       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7716         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7717         NewVD->setInvalidDecl(true);
7718       }
7719     }
7720 
7721     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7722                                         /*IsLiteralLabel=*/true,
7723                                         SE->getStrTokenLoc(0)));
7724   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7725     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7726       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7727     if (I != ExtnameUndeclaredIdentifiers.end()) {
7728       if (isDeclExternC(NewVD)) {
7729         NewVD->addAttr(I->second);
7730         ExtnameUndeclaredIdentifiers.erase(I);
7731       } else
7732         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7733             << /*Variable*/1 << NewVD;
7734     }
7735   }
7736 
7737   // Find the shadowed declaration before filtering for scope.
7738   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7739                                 ? getShadowedDeclaration(NewVD, Previous)
7740                                 : nullptr;
7741 
7742   // Don't consider existing declarations that are in a different
7743   // scope and are out-of-semantic-context declarations (if the new
7744   // declaration has linkage).
7745   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7746                        D.getCXXScopeSpec().isNotEmpty() ||
7747                        IsMemberSpecialization ||
7748                        IsVariableTemplateSpecialization);
7749 
7750   // Check whether the previous declaration is in the same block scope. This
7751   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7752   if (getLangOpts().CPlusPlus &&
7753       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7754     NewVD->setPreviousDeclInSameBlockScope(
7755         Previous.isSingleResult() && !Previous.isShadowed() &&
7756         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7757 
7758   if (!getLangOpts().CPlusPlus) {
7759     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7760   } else {
7761     // If this is an explicit specialization of a static data member, check it.
7762     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7763         CheckMemberSpecialization(NewVD, Previous))
7764       NewVD->setInvalidDecl();
7765 
7766     // Merge the decl with the existing one if appropriate.
7767     if (!Previous.empty()) {
7768       if (Previous.isSingleResult() &&
7769           isa<FieldDecl>(Previous.getFoundDecl()) &&
7770           D.getCXXScopeSpec().isSet()) {
7771         // The user tried to define a non-static data member
7772         // out-of-line (C++ [dcl.meaning]p1).
7773         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7774           << D.getCXXScopeSpec().getRange();
7775         Previous.clear();
7776         NewVD->setInvalidDecl();
7777       }
7778     } else if (D.getCXXScopeSpec().isSet()) {
7779       // No previous declaration in the qualifying scope.
7780       Diag(D.getIdentifierLoc(), diag::err_no_member)
7781         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7782         << D.getCXXScopeSpec().getRange();
7783       NewVD->setInvalidDecl();
7784     }
7785 
7786     if (!IsVariableTemplateSpecialization)
7787       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7788 
7789     if (NewTemplate) {
7790       VarTemplateDecl *PrevVarTemplate =
7791           NewVD->getPreviousDecl()
7792               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7793               : nullptr;
7794 
7795       // Check the template parameter list of this declaration, possibly
7796       // merging in the template parameter list from the previous variable
7797       // template declaration.
7798       if (CheckTemplateParameterList(
7799               TemplateParams,
7800               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7801                               : nullptr,
7802               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7803                DC->isDependentContext())
7804                   ? TPC_ClassTemplateMember
7805                   : TPC_VarTemplate))
7806         NewVD->setInvalidDecl();
7807 
7808       // If we are providing an explicit specialization of a static variable
7809       // template, make a note of that.
7810       if (PrevVarTemplate &&
7811           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7812         PrevVarTemplate->setMemberSpecialization();
7813     }
7814   }
7815 
7816   // Diagnose shadowed variables iff this isn't a redeclaration.
7817   if (ShadowedDecl && !D.isRedeclaration())
7818     CheckShadow(NewVD, ShadowedDecl, Previous);
7819 
7820   ProcessPragmaWeak(S, NewVD);
7821 
7822   // If this is the first declaration of an extern C variable, update
7823   // the map of such variables.
7824   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7825       isIncompleteDeclExternC(*this, NewVD))
7826     RegisterLocallyScopedExternCDecl(NewVD, S);
7827 
7828   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7829     MangleNumberingContext *MCtx;
7830     Decl *ManglingContextDecl;
7831     std::tie(MCtx, ManglingContextDecl) =
7832         getCurrentMangleNumberContext(NewVD->getDeclContext());
7833     if (MCtx) {
7834       Context.setManglingNumber(
7835           NewVD, MCtx->getManglingNumber(
7836                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7837       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7838     }
7839   }
7840 
7841   // Special handling of variable named 'main'.
7842   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7843       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7844       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7845 
7846     // C++ [basic.start.main]p3
7847     // A program that declares a variable main at global scope is ill-formed.
7848     if (getLangOpts().CPlusPlus)
7849       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7850 
7851     // In C, and external-linkage variable named main results in undefined
7852     // behavior.
7853     else if (NewVD->hasExternalFormalLinkage())
7854       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7855   }
7856 
7857   if (D.isRedeclaration() && !Previous.empty()) {
7858     NamedDecl *Prev = Previous.getRepresentativeDecl();
7859     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7860                                    D.isFunctionDefinition());
7861   }
7862 
7863   if (NewTemplate) {
7864     if (NewVD->isInvalidDecl())
7865       NewTemplate->setInvalidDecl();
7866     ActOnDocumentableDecl(NewTemplate);
7867     return NewTemplate;
7868   }
7869 
7870   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7871     CompleteMemberSpecialization(NewVD, Previous);
7872 
7873   return NewVD;
7874 }
7875 
7876 /// Enum describing the %select options in diag::warn_decl_shadow.
7877 enum ShadowedDeclKind {
7878   SDK_Local,
7879   SDK_Global,
7880   SDK_StaticMember,
7881   SDK_Field,
7882   SDK_Typedef,
7883   SDK_Using,
7884   SDK_StructuredBinding
7885 };
7886 
7887 /// Determine what kind of declaration we're shadowing.
7888 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7889                                                 const DeclContext *OldDC) {
7890   if (isa<TypeAliasDecl>(ShadowedDecl))
7891     return SDK_Using;
7892   else if (isa<TypedefDecl>(ShadowedDecl))
7893     return SDK_Typedef;
7894   else if (isa<BindingDecl>(ShadowedDecl))
7895     return SDK_StructuredBinding;
7896   else if (isa<RecordDecl>(OldDC))
7897     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7898 
7899   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7900 }
7901 
7902 /// Return the location of the capture if the given lambda captures the given
7903 /// variable \p VD, or an invalid source location otherwise.
7904 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7905                                          const VarDecl *VD) {
7906   for (const Capture &Capture : LSI->Captures) {
7907     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7908       return Capture.getLocation();
7909   }
7910   return SourceLocation();
7911 }
7912 
7913 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7914                                      const LookupResult &R) {
7915   // Only diagnose if we're shadowing an unambiguous field or variable.
7916   if (R.getResultKind() != LookupResult::Found)
7917     return false;
7918 
7919   // Return false if warning is ignored.
7920   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7921 }
7922 
7923 /// Return the declaration shadowed by the given variable \p D, or null
7924 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7925 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7926                                         const LookupResult &R) {
7927   if (!shouldWarnIfShadowedDecl(Diags, R))
7928     return nullptr;
7929 
7930   // Don't diagnose declarations at file scope.
7931   if (D->hasGlobalStorage())
7932     return nullptr;
7933 
7934   NamedDecl *ShadowedDecl = R.getFoundDecl();
7935   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7936                                                             : nullptr;
7937 }
7938 
7939 /// Return the declaration shadowed by the given typedef \p D, or null
7940 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7941 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7942                                         const LookupResult &R) {
7943   // Don't warn if typedef declaration is part of a class
7944   if (D->getDeclContext()->isRecord())
7945     return nullptr;
7946 
7947   if (!shouldWarnIfShadowedDecl(Diags, R))
7948     return nullptr;
7949 
7950   NamedDecl *ShadowedDecl = R.getFoundDecl();
7951   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7952 }
7953 
7954 /// Return the declaration shadowed by the given variable \p D, or null
7955 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7956 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7957                                         const LookupResult &R) {
7958   if (!shouldWarnIfShadowedDecl(Diags, R))
7959     return nullptr;
7960 
7961   NamedDecl *ShadowedDecl = R.getFoundDecl();
7962   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7963                                                             : nullptr;
7964 }
7965 
7966 /// Diagnose variable or built-in function shadowing.  Implements
7967 /// -Wshadow.
7968 ///
7969 /// This method is called whenever a VarDecl is added to a "useful"
7970 /// scope.
7971 ///
7972 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7973 /// \param R the lookup of the name
7974 ///
7975 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7976                        const LookupResult &R) {
7977   DeclContext *NewDC = D->getDeclContext();
7978 
7979   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7980     // Fields are not shadowed by variables in C++ static methods.
7981     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7982       if (MD->isStatic())
7983         return;
7984 
7985     // Fields shadowed by constructor parameters are a special case. Usually
7986     // the constructor initializes the field with the parameter.
7987     if (isa<CXXConstructorDecl>(NewDC))
7988       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7989         // Remember that this was shadowed so we can either warn about its
7990         // modification or its existence depending on warning settings.
7991         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7992         return;
7993       }
7994   }
7995 
7996   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7997     if (shadowedVar->isExternC()) {
7998       // For shadowing external vars, make sure that we point to the global
7999       // declaration, not a locally scoped extern declaration.
8000       for (auto I : shadowedVar->redecls())
8001         if (I->isFileVarDecl()) {
8002           ShadowedDecl = I;
8003           break;
8004         }
8005     }
8006 
8007   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8008 
8009   unsigned WarningDiag = diag::warn_decl_shadow;
8010   SourceLocation CaptureLoc;
8011   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8012       isa<CXXMethodDecl>(NewDC)) {
8013     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8014       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8015         if (RD->getLambdaCaptureDefault() == LCD_None) {
8016           // Try to avoid warnings for lambdas with an explicit capture list.
8017           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8018           // Warn only when the lambda captures the shadowed decl explicitly.
8019           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8020           if (CaptureLoc.isInvalid())
8021             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8022         } else {
8023           // Remember that this was shadowed so we can avoid the warning if the
8024           // shadowed decl isn't captured and the warning settings allow it.
8025           cast<LambdaScopeInfo>(getCurFunction())
8026               ->ShadowingDecls.push_back(
8027                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8028           return;
8029         }
8030       }
8031 
8032       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8033         // A variable can't shadow a local variable in an enclosing scope, if
8034         // they are separated by a non-capturing declaration context.
8035         for (DeclContext *ParentDC = NewDC;
8036              ParentDC && !ParentDC->Equals(OldDC);
8037              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8038           // Only block literals, captured statements, and lambda expressions
8039           // can capture; other scopes don't.
8040           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8041               !isLambdaCallOperator(ParentDC)) {
8042             return;
8043           }
8044         }
8045       }
8046     }
8047   }
8048 
8049   // Only warn about certain kinds of shadowing for class members.
8050   if (NewDC && NewDC->isRecord()) {
8051     // In particular, don't warn about shadowing non-class members.
8052     if (!OldDC->isRecord())
8053       return;
8054 
8055     // TODO: should we warn about static data members shadowing
8056     // static data members from base classes?
8057 
8058     // TODO: don't diagnose for inaccessible shadowed members.
8059     // This is hard to do perfectly because we might friend the
8060     // shadowing context, but that's just a false negative.
8061   }
8062 
8063 
8064   DeclarationName Name = R.getLookupName();
8065 
8066   // Emit warning and note.
8067   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8068   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8069   if (!CaptureLoc.isInvalid())
8070     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8071         << Name << /*explicitly*/ 1;
8072   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8073 }
8074 
8075 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8076 /// when these variables are captured by the lambda.
8077 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8078   for (const auto &Shadow : LSI->ShadowingDecls) {
8079     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8080     // Try to avoid the warning when the shadowed decl isn't captured.
8081     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8082     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8083     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8084                                        ? diag::warn_decl_shadow_uncaptured_local
8085                                        : diag::warn_decl_shadow)
8086         << Shadow.VD->getDeclName()
8087         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8088     if (!CaptureLoc.isInvalid())
8089       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8090           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8091     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8092   }
8093 }
8094 
8095 /// Check -Wshadow without the advantage of a previous lookup.
8096 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8097   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8098     return;
8099 
8100   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8101                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8102   LookupName(R, S);
8103   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8104     CheckShadow(D, ShadowedDecl, R);
8105 }
8106 
8107 /// Check if 'E', which is an expression that is about to be modified, refers
8108 /// to a constructor parameter that shadows a field.
8109 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8110   // Quickly ignore expressions that can't be shadowing ctor parameters.
8111   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8112     return;
8113   E = E->IgnoreParenImpCasts();
8114   auto *DRE = dyn_cast<DeclRefExpr>(E);
8115   if (!DRE)
8116     return;
8117   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8118   auto I = ShadowingDecls.find(D);
8119   if (I == ShadowingDecls.end())
8120     return;
8121   const NamedDecl *ShadowedDecl = I->second;
8122   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8123   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8124   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8125   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8126 
8127   // Avoid issuing multiple warnings about the same decl.
8128   ShadowingDecls.erase(I);
8129 }
8130 
8131 /// Check for conflict between this global or extern "C" declaration and
8132 /// previous global or extern "C" declarations. This is only used in C++.
8133 template<typename T>
8134 static bool checkGlobalOrExternCConflict(
8135     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8136   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8137   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8138 
8139   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8140     // The common case: this global doesn't conflict with any extern "C"
8141     // declaration.
8142     return false;
8143   }
8144 
8145   if (Prev) {
8146     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8147       // Both the old and new declarations have C language linkage. This is a
8148       // redeclaration.
8149       Previous.clear();
8150       Previous.addDecl(Prev);
8151       return true;
8152     }
8153 
8154     // This is a global, non-extern "C" declaration, and there is a previous
8155     // non-global extern "C" declaration. Diagnose if this is a variable
8156     // declaration.
8157     if (!isa<VarDecl>(ND))
8158       return false;
8159   } else {
8160     // The declaration is extern "C". Check for any declaration in the
8161     // translation unit which might conflict.
8162     if (IsGlobal) {
8163       // We have already performed the lookup into the translation unit.
8164       IsGlobal = false;
8165       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8166            I != E; ++I) {
8167         if (isa<VarDecl>(*I)) {
8168           Prev = *I;
8169           break;
8170         }
8171       }
8172     } else {
8173       DeclContext::lookup_result R =
8174           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8175       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8176            I != E; ++I) {
8177         if (isa<VarDecl>(*I)) {
8178           Prev = *I;
8179           break;
8180         }
8181         // FIXME: If we have any other entity with this name in global scope,
8182         // the declaration is ill-formed, but that is a defect: it breaks the
8183         // 'stat' hack, for instance. Only variables can have mangled name
8184         // clashes with extern "C" declarations, so only they deserve a
8185         // diagnostic.
8186       }
8187     }
8188 
8189     if (!Prev)
8190       return false;
8191   }
8192 
8193   // Use the first declaration's location to ensure we point at something which
8194   // is lexically inside an extern "C" linkage-spec.
8195   assert(Prev && "should have found a previous declaration to diagnose");
8196   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8197     Prev = FD->getFirstDecl();
8198   else
8199     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8200 
8201   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8202     << IsGlobal << ND;
8203   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8204     << IsGlobal;
8205   return false;
8206 }
8207 
8208 /// Apply special rules for handling extern "C" declarations. Returns \c true
8209 /// if we have found that this is a redeclaration of some prior entity.
8210 ///
8211 /// Per C++ [dcl.link]p6:
8212 ///   Two declarations [for a function or variable] with C language linkage
8213 ///   with the same name that appear in different scopes refer to the same
8214 ///   [entity]. An entity with C language linkage shall not be declared with
8215 ///   the same name as an entity in global scope.
8216 template<typename T>
8217 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8218                                                   LookupResult &Previous) {
8219   if (!S.getLangOpts().CPlusPlus) {
8220     // In C, when declaring a global variable, look for a corresponding 'extern'
8221     // variable declared in function scope. We don't need this in C++, because
8222     // we find local extern decls in the surrounding file-scope DeclContext.
8223     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8224       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8225         Previous.clear();
8226         Previous.addDecl(Prev);
8227         return true;
8228       }
8229     }
8230     return false;
8231   }
8232 
8233   // A declaration in the translation unit can conflict with an extern "C"
8234   // declaration.
8235   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8236     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8237 
8238   // An extern "C" declaration can conflict with a declaration in the
8239   // translation unit or can be a redeclaration of an extern "C" declaration
8240   // in another scope.
8241   if (isIncompleteDeclExternC(S,ND))
8242     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8243 
8244   // Neither global nor extern "C": nothing to do.
8245   return false;
8246 }
8247 
8248 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8249   // If the decl is already known invalid, don't check it.
8250   if (NewVD->isInvalidDecl())
8251     return;
8252 
8253   QualType T = NewVD->getType();
8254 
8255   // Defer checking an 'auto' type until its initializer is attached.
8256   if (T->isUndeducedType())
8257     return;
8258 
8259   if (NewVD->hasAttrs())
8260     CheckAlignasUnderalignment(NewVD);
8261 
8262   if (T->isObjCObjectType()) {
8263     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8264       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8265     T = Context.getObjCObjectPointerType(T);
8266     NewVD->setType(T);
8267   }
8268 
8269   // Emit an error if an address space was applied to decl with local storage.
8270   // This includes arrays of objects with address space qualifiers, but not
8271   // automatic variables that point to other address spaces.
8272   // ISO/IEC TR 18037 S5.1.2
8273   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8274       T.getAddressSpace() != LangAS::Default) {
8275     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8276     NewVD->setInvalidDecl();
8277     return;
8278   }
8279 
8280   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8281   // scope.
8282   if (getLangOpts().OpenCLVersion == 120 &&
8283       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8284                                             getLangOpts()) &&
8285       NewVD->isStaticLocal()) {
8286     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8287     NewVD->setInvalidDecl();
8288     return;
8289   }
8290 
8291   if (getLangOpts().OpenCL) {
8292     if (!diagnoseOpenCLTypes(*this, NewVD))
8293       return;
8294 
8295     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8296     if (NewVD->hasAttr<BlocksAttr>()) {
8297       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8298       return;
8299     }
8300 
8301     if (T->isBlockPointerType()) {
8302       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8303       // can't use 'extern' storage class.
8304       if (!T.isConstQualified()) {
8305         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8306             << 0 /*const*/;
8307         NewVD->setInvalidDecl();
8308         return;
8309       }
8310       if (NewVD->hasExternalStorage()) {
8311         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8312         NewVD->setInvalidDecl();
8313         return;
8314       }
8315     }
8316 
8317     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8318     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8319         NewVD->hasExternalStorage()) {
8320       if (!T->isSamplerT() && !T->isDependentType() &&
8321           !(T.getAddressSpace() == LangAS::opencl_constant ||
8322             (T.getAddressSpace() == LangAS::opencl_global &&
8323              getOpenCLOptions().areProgramScopeVariablesSupported(
8324                  getLangOpts())))) {
8325         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8326         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8327           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8328               << Scope << "global or constant";
8329         else
8330           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8331               << Scope << "constant";
8332         NewVD->setInvalidDecl();
8333         return;
8334       }
8335     } else {
8336       if (T.getAddressSpace() == LangAS::opencl_global) {
8337         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8338             << 1 /*is any function*/ << "global";
8339         NewVD->setInvalidDecl();
8340         return;
8341       }
8342       if (T.getAddressSpace() == LangAS::opencl_constant ||
8343           T.getAddressSpace() == LangAS::opencl_local) {
8344         FunctionDecl *FD = getCurFunctionDecl();
8345         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8346         // in functions.
8347         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8348           if (T.getAddressSpace() == LangAS::opencl_constant)
8349             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8350                 << 0 /*non-kernel only*/ << "constant";
8351           else
8352             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8353                 << 0 /*non-kernel only*/ << "local";
8354           NewVD->setInvalidDecl();
8355           return;
8356         }
8357         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8358         // in the outermost scope of a kernel function.
8359         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8360           if (!getCurScope()->isFunctionScope()) {
8361             if (T.getAddressSpace() == LangAS::opencl_constant)
8362               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8363                   << "constant";
8364             else
8365               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8366                   << "local";
8367             NewVD->setInvalidDecl();
8368             return;
8369           }
8370         }
8371       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8372                  // If we are parsing a template we didn't deduce an addr
8373                  // space yet.
8374                  T.getAddressSpace() != LangAS::Default) {
8375         // Do not allow other address spaces on automatic variable.
8376         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8377         NewVD->setInvalidDecl();
8378         return;
8379       }
8380     }
8381   }
8382 
8383   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8384       && !NewVD->hasAttr<BlocksAttr>()) {
8385     if (getLangOpts().getGC() != LangOptions::NonGC)
8386       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8387     else {
8388       assert(!getLangOpts().ObjCAutoRefCount);
8389       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8390     }
8391   }
8392 
8393   bool isVM = T->isVariablyModifiedType();
8394   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8395       NewVD->hasAttr<BlocksAttr>())
8396     setFunctionHasBranchProtectedScope();
8397 
8398   if ((isVM && NewVD->hasLinkage()) ||
8399       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8400     bool SizeIsNegative;
8401     llvm::APSInt Oversized;
8402     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8403         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8404     QualType FixedT;
8405     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8406       FixedT = FixedTInfo->getType();
8407     else if (FixedTInfo) {
8408       // Type and type-as-written are canonically different. We need to fix up
8409       // both types separately.
8410       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8411                                                    Oversized);
8412     }
8413     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8414       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8415       // FIXME: This won't give the correct result for
8416       // int a[10][n];
8417       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8418 
8419       if (NewVD->isFileVarDecl())
8420         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8421         << SizeRange;
8422       else if (NewVD->isStaticLocal())
8423         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8424         << SizeRange;
8425       else
8426         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8427         << SizeRange;
8428       NewVD->setInvalidDecl();
8429       return;
8430     }
8431 
8432     if (!FixedTInfo) {
8433       if (NewVD->isFileVarDecl())
8434         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8435       else
8436         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8437       NewVD->setInvalidDecl();
8438       return;
8439     }
8440 
8441     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8442     NewVD->setType(FixedT);
8443     NewVD->setTypeSourceInfo(FixedTInfo);
8444   }
8445 
8446   if (T->isVoidType()) {
8447     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8448     //                    of objects and functions.
8449     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8450       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8451         << T;
8452       NewVD->setInvalidDecl();
8453       return;
8454     }
8455   }
8456 
8457   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8458     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8459     NewVD->setInvalidDecl();
8460     return;
8461   }
8462 
8463   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8464     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8465     NewVD->setInvalidDecl();
8466     return;
8467   }
8468 
8469   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8470     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8471     NewVD->setInvalidDecl();
8472     return;
8473   }
8474 
8475   if (NewVD->isConstexpr() && !T->isDependentType() &&
8476       RequireLiteralType(NewVD->getLocation(), T,
8477                          diag::err_constexpr_var_non_literal)) {
8478     NewVD->setInvalidDecl();
8479     return;
8480   }
8481 
8482   // PPC MMA non-pointer types are not allowed as non-local variable types.
8483   if (Context.getTargetInfo().getTriple().isPPC64() &&
8484       !NewVD->isLocalVarDecl() &&
8485       CheckPPCMMAType(T, NewVD->getLocation())) {
8486     NewVD->setInvalidDecl();
8487     return;
8488   }
8489 }
8490 
8491 /// Perform semantic checking on a newly-created variable
8492 /// declaration.
8493 ///
8494 /// This routine performs all of the type-checking required for a
8495 /// variable declaration once it has been built. It is used both to
8496 /// check variables after they have been parsed and their declarators
8497 /// have been translated into a declaration, and to check variables
8498 /// that have been instantiated from a template.
8499 ///
8500 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8501 ///
8502 /// Returns true if the variable declaration is a redeclaration.
8503 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8504   CheckVariableDeclarationType(NewVD);
8505 
8506   // If the decl is already known invalid, don't check it.
8507   if (NewVD->isInvalidDecl())
8508     return false;
8509 
8510   // If we did not find anything by this name, look for a non-visible
8511   // extern "C" declaration with the same name.
8512   if (Previous.empty() &&
8513       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8514     Previous.setShadowed();
8515 
8516   if (!Previous.empty()) {
8517     MergeVarDecl(NewVD, Previous);
8518     return true;
8519   }
8520   return false;
8521 }
8522 
8523 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8524 /// and if so, check that it's a valid override and remember it.
8525 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8526   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8527 
8528   // Look for methods in base classes that this method might override.
8529   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8530                      /*DetectVirtual=*/false);
8531   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8532     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8533     DeclarationName Name = MD->getDeclName();
8534 
8535     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8536       // We really want to find the base class destructor here.
8537       QualType T = Context.getTypeDeclType(BaseRecord);
8538       CanQualType CT = Context.getCanonicalType(T);
8539       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8540     }
8541 
8542     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8543       CXXMethodDecl *BaseMD =
8544           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8545       if (!BaseMD || !BaseMD->isVirtual() ||
8546           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8547                      /*ConsiderCudaAttrs=*/true,
8548                      // C++2a [class.virtual]p2 does not consider requires
8549                      // clauses when overriding.
8550                      /*ConsiderRequiresClauses=*/false))
8551         continue;
8552 
8553       if (Overridden.insert(BaseMD).second) {
8554         MD->addOverriddenMethod(BaseMD);
8555         CheckOverridingFunctionReturnType(MD, BaseMD);
8556         CheckOverridingFunctionAttributes(MD, BaseMD);
8557         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8558         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8559       }
8560 
8561       // A method can only override one function from each base class. We
8562       // don't track indirectly overridden methods from bases of bases.
8563       return true;
8564     }
8565 
8566     return false;
8567   };
8568 
8569   DC->lookupInBases(VisitBase, Paths);
8570   return !Overridden.empty();
8571 }
8572 
8573 namespace {
8574   // Struct for holding all of the extra arguments needed by
8575   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8576   struct ActOnFDArgs {
8577     Scope *S;
8578     Declarator &D;
8579     MultiTemplateParamsArg TemplateParamLists;
8580     bool AddToScope;
8581   };
8582 } // end anonymous namespace
8583 
8584 namespace {
8585 
8586 // Callback to only accept typo corrections that have a non-zero edit distance.
8587 // Also only accept corrections that have the same parent decl.
8588 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8589  public:
8590   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8591                             CXXRecordDecl *Parent)
8592       : Context(Context), OriginalFD(TypoFD),
8593         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8594 
8595   bool ValidateCandidate(const TypoCorrection &candidate) override {
8596     if (candidate.getEditDistance() == 0)
8597       return false;
8598 
8599     SmallVector<unsigned, 1> MismatchedParams;
8600     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8601                                           CDeclEnd = candidate.end();
8602          CDecl != CDeclEnd; ++CDecl) {
8603       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8604 
8605       if (FD && !FD->hasBody() &&
8606           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8607         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8608           CXXRecordDecl *Parent = MD->getParent();
8609           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8610             return true;
8611         } else if (!ExpectedParent) {
8612           return true;
8613         }
8614       }
8615     }
8616 
8617     return false;
8618   }
8619 
8620   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8621     return std::make_unique<DifferentNameValidatorCCC>(*this);
8622   }
8623 
8624  private:
8625   ASTContext &Context;
8626   FunctionDecl *OriginalFD;
8627   CXXRecordDecl *ExpectedParent;
8628 };
8629 
8630 } // end anonymous namespace
8631 
8632 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8633   TypoCorrectedFunctionDefinitions.insert(F);
8634 }
8635 
8636 /// Generate diagnostics for an invalid function redeclaration.
8637 ///
8638 /// This routine handles generating the diagnostic messages for an invalid
8639 /// function redeclaration, including finding possible similar declarations
8640 /// or performing typo correction if there are no previous declarations with
8641 /// the same name.
8642 ///
8643 /// Returns a NamedDecl iff typo correction was performed and substituting in
8644 /// the new declaration name does not cause new errors.
8645 static NamedDecl *DiagnoseInvalidRedeclaration(
8646     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8647     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8648   DeclarationName Name = NewFD->getDeclName();
8649   DeclContext *NewDC = NewFD->getDeclContext();
8650   SmallVector<unsigned, 1> MismatchedParams;
8651   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8652   TypoCorrection Correction;
8653   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8654   unsigned DiagMsg =
8655     IsLocalFriend ? diag::err_no_matching_local_friend :
8656     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8657     diag::err_member_decl_does_not_match;
8658   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8659                     IsLocalFriend ? Sema::LookupLocalFriendName
8660                                   : Sema::LookupOrdinaryName,
8661                     Sema::ForVisibleRedeclaration);
8662 
8663   NewFD->setInvalidDecl();
8664   if (IsLocalFriend)
8665     SemaRef.LookupName(Prev, S);
8666   else
8667     SemaRef.LookupQualifiedName(Prev, NewDC);
8668   assert(!Prev.isAmbiguous() &&
8669          "Cannot have an ambiguity in previous-declaration lookup");
8670   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8671   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8672                                 MD ? MD->getParent() : nullptr);
8673   if (!Prev.empty()) {
8674     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8675          Func != FuncEnd; ++Func) {
8676       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8677       if (FD &&
8678           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8679         // Add 1 to the index so that 0 can mean the mismatch didn't
8680         // involve a parameter
8681         unsigned ParamNum =
8682             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8683         NearMatches.push_back(std::make_pair(FD, ParamNum));
8684       }
8685     }
8686   // If the qualified name lookup yielded nothing, try typo correction
8687   } else if ((Correction = SemaRef.CorrectTypo(
8688                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8689                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8690                   IsLocalFriend ? nullptr : NewDC))) {
8691     // Set up everything for the call to ActOnFunctionDeclarator
8692     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8693                               ExtraArgs.D.getIdentifierLoc());
8694     Previous.clear();
8695     Previous.setLookupName(Correction.getCorrection());
8696     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8697                                     CDeclEnd = Correction.end();
8698          CDecl != CDeclEnd; ++CDecl) {
8699       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8700       if (FD && !FD->hasBody() &&
8701           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8702         Previous.addDecl(FD);
8703       }
8704     }
8705     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8706 
8707     NamedDecl *Result;
8708     // Retry building the function declaration with the new previous
8709     // declarations, and with errors suppressed.
8710     {
8711       // Trap errors.
8712       Sema::SFINAETrap Trap(SemaRef);
8713 
8714       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8715       // pieces need to verify the typo-corrected C++ declaration and hopefully
8716       // eliminate the need for the parameter pack ExtraArgs.
8717       Result = SemaRef.ActOnFunctionDeclarator(
8718           ExtraArgs.S, ExtraArgs.D,
8719           Correction.getCorrectionDecl()->getDeclContext(),
8720           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8721           ExtraArgs.AddToScope);
8722 
8723       if (Trap.hasErrorOccurred())
8724         Result = nullptr;
8725     }
8726 
8727     if (Result) {
8728       // Determine which correction we picked.
8729       Decl *Canonical = Result->getCanonicalDecl();
8730       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8731            I != E; ++I)
8732         if ((*I)->getCanonicalDecl() == Canonical)
8733           Correction.setCorrectionDecl(*I);
8734 
8735       // Let Sema know about the correction.
8736       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8737       SemaRef.diagnoseTypo(
8738           Correction,
8739           SemaRef.PDiag(IsLocalFriend
8740                           ? diag::err_no_matching_local_friend_suggest
8741                           : diag::err_member_decl_does_not_match_suggest)
8742             << Name << NewDC << IsDefinition);
8743       return Result;
8744     }
8745 
8746     // Pretend the typo correction never occurred
8747     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8748                               ExtraArgs.D.getIdentifierLoc());
8749     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8750     Previous.clear();
8751     Previous.setLookupName(Name);
8752   }
8753 
8754   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8755       << Name << NewDC << IsDefinition << NewFD->getLocation();
8756 
8757   bool NewFDisConst = false;
8758   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8759     NewFDisConst = NewMD->isConst();
8760 
8761   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8762        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8763        NearMatch != NearMatchEnd; ++NearMatch) {
8764     FunctionDecl *FD = NearMatch->first;
8765     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8766     bool FDisConst = MD && MD->isConst();
8767     bool IsMember = MD || !IsLocalFriend;
8768 
8769     // FIXME: These notes are poorly worded for the local friend case.
8770     if (unsigned Idx = NearMatch->second) {
8771       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8772       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8773       if (Loc.isInvalid()) Loc = FD->getLocation();
8774       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8775                                  : diag::note_local_decl_close_param_match)
8776         << Idx << FDParam->getType()
8777         << NewFD->getParamDecl(Idx - 1)->getType();
8778     } else if (FDisConst != NewFDisConst) {
8779       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8780           << NewFDisConst << FD->getSourceRange().getEnd()
8781           << (NewFDisConst
8782                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8783                                                  .getConstQualifierLoc())
8784                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8785                                                    .getRParenLoc()
8786                                                    .getLocWithOffset(1),
8787                                                " const"));
8788     } else
8789       SemaRef.Diag(FD->getLocation(),
8790                    IsMember ? diag::note_member_def_close_match
8791                             : diag::note_local_decl_close_match);
8792   }
8793   return nullptr;
8794 }
8795 
8796 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8797   switch (D.getDeclSpec().getStorageClassSpec()) {
8798   default: llvm_unreachable("Unknown storage class!");
8799   case DeclSpec::SCS_auto:
8800   case DeclSpec::SCS_register:
8801   case DeclSpec::SCS_mutable:
8802     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8803                  diag::err_typecheck_sclass_func);
8804     D.getMutableDeclSpec().ClearStorageClassSpecs();
8805     D.setInvalidType();
8806     break;
8807   case DeclSpec::SCS_unspecified: break;
8808   case DeclSpec::SCS_extern:
8809     if (D.getDeclSpec().isExternInLinkageSpec())
8810       return SC_None;
8811     return SC_Extern;
8812   case DeclSpec::SCS_static: {
8813     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8814       // C99 6.7.1p5:
8815       //   The declaration of an identifier for a function that has
8816       //   block scope shall have no explicit storage-class specifier
8817       //   other than extern
8818       // See also (C++ [dcl.stc]p4).
8819       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8820                    diag::err_static_block_func);
8821       break;
8822     } else
8823       return SC_Static;
8824   }
8825   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8826   }
8827 
8828   // No explicit storage class has already been returned
8829   return SC_None;
8830 }
8831 
8832 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8833                                            DeclContext *DC, QualType &R,
8834                                            TypeSourceInfo *TInfo,
8835                                            StorageClass SC,
8836                                            bool &IsVirtualOkay) {
8837   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8838   DeclarationName Name = NameInfo.getName();
8839 
8840   FunctionDecl *NewFD = nullptr;
8841   bool isInline = D.getDeclSpec().isInlineSpecified();
8842 
8843   if (!SemaRef.getLangOpts().CPlusPlus) {
8844     // Determine whether the function was written with a prototype. This is
8845     // true when:
8846     //   - there is a prototype in the declarator, or
8847     //   - the type R of the function is some kind of typedef or other non-
8848     //     attributed reference to a type name (which eventually refers to a
8849     //     function type). Note, we can't always look at the adjusted type to
8850     //     check this case because attributes may cause a non-function
8851     //     declarator to still have a function type. e.g.,
8852     //       typedef void func(int a);
8853     //       __attribute__((noreturn)) func other_func; // This has a prototype
8854     bool HasPrototype =
8855         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8856         (D.getDeclSpec().isTypeRep() &&
8857          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8858         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8859     assert(
8860         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8861         "Strict prototypes are required");
8862 
8863     NewFD = FunctionDecl::Create(
8864         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8865         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8866         ConstexprSpecKind::Unspecified,
8867         /*TrailingRequiresClause=*/nullptr);
8868     if (D.isInvalidType())
8869       NewFD->setInvalidDecl();
8870 
8871     return NewFD;
8872   }
8873 
8874   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8875 
8876   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8877   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8878     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8879                  diag::err_constexpr_wrong_decl_kind)
8880         << static_cast<int>(ConstexprKind);
8881     ConstexprKind = ConstexprSpecKind::Unspecified;
8882     D.getMutableDeclSpec().ClearConstexprSpec();
8883   }
8884   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8885 
8886   // Check that the return type is not an abstract class type.
8887   // For record types, this is done by the AbstractClassUsageDiagnoser once
8888   // the class has been completely parsed.
8889   if (!DC->isRecord() &&
8890       SemaRef.RequireNonAbstractType(
8891           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8892           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8893     D.setInvalidType();
8894 
8895   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8896     // This is a C++ constructor declaration.
8897     assert(DC->isRecord() &&
8898            "Constructors can only be declared in a member context");
8899 
8900     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8901     return CXXConstructorDecl::Create(
8902         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8903         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8904         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8905         InheritedConstructor(), TrailingRequiresClause);
8906 
8907   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8908     // This is a C++ destructor declaration.
8909     if (DC->isRecord()) {
8910       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8911       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8912       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8913           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8914           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8915           /*isImplicitlyDeclared=*/false, ConstexprKind,
8916           TrailingRequiresClause);
8917       // User defined destructors start as not selected if the class definition is still
8918       // not done.
8919       if (Record->isBeingDefined())
8920         NewDD->setIneligibleOrNotSelected(true);
8921 
8922       // If the destructor needs an implicit exception specification, set it
8923       // now. FIXME: It'd be nice to be able to create the right type to start
8924       // with, but the type needs to reference the destructor declaration.
8925       if (SemaRef.getLangOpts().CPlusPlus11)
8926         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8927 
8928       IsVirtualOkay = true;
8929       return NewDD;
8930 
8931     } else {
8932       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8933       D.setInvalidType();
8934 
8935       // Create a FunctionDecl to satisfy the function definition parsing
8936       // code path.
8937       return FunctionDecl::Create(
8938           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8939           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8940           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8941     }
8942 
8943   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8944     if (!DC->isRecord()) {
8945       SemaRef.Diag(D.getIdentifierLoc(),
8946            diag::err_conv_function_not_member);
8947       return nullptr;
8948     }
8949 
8950     SemaRef.CheckConversionDeclarator(D, R, SC);
8951     if (D.isInvalidType())
8952       return nullptr;
8953 
8954     IsVirtualOkay = true;
8955     return CXXConversionDecl::Create(
8956         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8957         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8958         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8959         TrailingRequiresClause);
8960 
8961   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8962     if (TrailingRequiresClause)
8963       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8964                    diag::err_trailing_requires_clause_on_deduction_guide)
8965           << TrailingRequiresClause->getSourceRange();
8966     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8967 
8968     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8969                                          ExplicitSpecifier, NameInfo, R, TInfo,
8970                                          D.getEndLoc());
8971   } else if (DC->isRecord()) {
8972     // If the name of the function is the same as the name of the record,
8973     // then this must be an invalid constructor that has a return type.
8974     // (The parser checks for a return type and makes the declarator a
8975     // constructor if it has no return type).
8976     if (Name.getAsIdentifierInfo() &&
8977         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8978       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8979         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8980         << SourceRange(D.getIdentifierLoc());
8981       return nullptr;
8982     }
8983 
8984     // This is a C++ method declaration.
8985     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8986         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8987         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8988         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8989     IsVirtualOkay = !Ret->isStatic();
8990     return Ret;
8991   } else {
8992     bool isFriend =
8993         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8994     if (!isFriend && SemaRef.CurContext->isRecord())
8995       return nullptr;
8996 
8997     // Determine whether the function was written with a
8998     // prototype. This true when:
8999     //   - we're in C++ (where every function has a prototype),
9000     return FunctionDecl::Create(
9001         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9002         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9003         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9004   }
9005 }
9006 
9007 enum OpenCLParamType {
9008   ValidKernelParam,
9009   PtrPtrKernelParam,
9010   PtrKernelParam,
9011   InvalidAddrSpacePtrKernelParam,
9012   InvalidKernelParam,
9013   RecordKernelParam
9014 };
9015 
9016 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9017   // Size dependent types are just typedefs to normal integer types
9018   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9019   // integers other than by their names.
9020   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9021 
9022   // Remove typedefs one by one until we reach a typedef
9023   // for a size dependent type.
9024   QualType DesugaredTy = Ty;
9025   do {
9026     ArrayRef<StringRef> Names(SizeTypeNames);
9027     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9028     if (Names.end() != Match)
9029       return true;
9030 
9031     Ty = DesugaredTy;
9032     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9033   } while (DesugaredTy != Ty);
9034 
9035   return false;
9036 }
9037 
9038 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9039   if (PT->isDependentType())
9040     return InvalidKernelParam;
9041 
9042   if (PT->isPointerType() || PT->isReferenceType()) {
9043     QualType PointeeType = PT->getPointeeType();
9044     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9045         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9046         PointeeType.getAddressSpace() == LangAS::Default)
9047       return InvalidAddrSpacePtrKernelParam;
9048 
9049     if (PointeeType->isPointerType()) {
9050       // This is a pointer to pointer parameter.
9051       // Recursively check inner type.
9052       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9053       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9054           ParamKind == InvalidKernelParam)
9055         return ParamKind;
9056 
9057       return PtrPtrKernelParam;
9058     }
9059 
9060     // C++ for OpenCL v1.0 s2.4:
9061     // Moreover the types used in parameters of the kernel functions must be:
9062     // Standard layout types for pointer parameters. The same applies to
9063     // reference if an implementation supports them in kernel parameters.
9064     if (S.getLangOpts().OpenCLCPlusPlus &&
9065         !S.getOpenCLOptions().isAvailableOption(
9066             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9067         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9068         !PointeeType->isStandardLayoutType())
9069       return InvalidKernelParam;
9070 
9071     return PtrKernelParam;
9072   }
9073 
9074   // OpenCL v1.2 s6.9.k:
9075   // Arguments to kernel functions in a program cannot be declared with the
9076   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9077   // uintptr_t or a struct and/or union that contain fields declared to be one
9078   // of these built-in scalar types.
9079   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9080     return InvalidKernelParam;
9081 
9082   if (PT->isImageType())
9083     return PtrKernelParam;
9084 
9085   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9086     return InvalidKernelParam;
9087 
9088   // OpenCL extension spec v1.2 s9.5:
9089   // This extension adds support for half scalar and vector types as built-in
9090   // types that can be used for arithmetic operations, conversions etc.
9091   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9092       PT->isHalfType())
9093     return InvalidKernelParam;
9094 
9095   // Look into an array argument to check if it has a forbidden type.
9096   if (PT->isArrayType()) {
9097     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9098     // Call ourself to check an underlying type of an array. Since the
9099     // getPointeeOrArrayElementType returns an innermost type which is not an
9100     // array, this recursive call only happens once.
9101     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9102   }
9103 
9104   // C++ for OpenCL v1.0 s2.4:
9105   // Moreover the types used in parameters of the kernel functions must be:
9106   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9107   // types) for parameters passed by value;
9108   if (S.getLangOpts().OpenCLCPlusPlus &&
9109       !S.getOpenCLOptions().isAvailableOption(
9110           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9111       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9112     return InvalidKernelParam;
9113 
9114   if (PT->isRecordType())
9115     return RecordKernelParam;
9116 
9117   return ValidKernelParam;
9118 }
9119 
9120 static void checkIsValidOpenCLKernelParameter(
9121   Sema &S,
9122   Declarator &D,
9123   ParmVarDecl *Param,
9124   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9125   QualType PT = Param->getType();
9126 
9127   // Cache the valid types we encounter to avoid rechecking structs that are
9128   // used again
9129   if (ValidTypes.count(PT.getTypePtr()))
9130     return;
9131 
9132   switch (getOpenCLKernelParameterType(S, PT)) {
9133   case PtrPtrKernelParam:
9134     // OpenCL v3.0 s6.11.a:
9135     // A kernel function argument cannot be declared as a pointer to a pointer
9136     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9137     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9138       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9139       D.setInvalidType();
9140       return;
9141     }
9142 
9143     ValidTypes.insert(PT.getTypePtr());
9144     return;
9145 
9146   case InvalidAddrSpacePtrKernelParam:
9147     // OpenCL v1.0 s6.5:
9148     // __kernel function arguments declared to be a pointer of a type can point
9149     // to one of the following address spaces only : __global, __local or
9150     // __constant.
9151     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9152     D.setInvalidType();
9153     return;
9154 
9155     // OpenCL v1.2 s6.9.k:
9156     // Arguments to kernel functions in a program cannot be declared with the
9157     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9158     // uintptr_t or a struct and/or union that contain fields declared to be
9159     // one of these built-in scalar types.
9160 
9161   case InvalidKernelParam:
9162     // OpenCL v1.2 s6.8 n:
9163     // A kernel function argument cannot be declared
9164     // of event_t type.
9165     // Do not diagnose half type since it is diagnosed as invalid argument
9166     // type for any function elsewhere.
9167     if (!PT->isHalfType()) {
9168       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9169 
9170       // Explain what typedefs are involved.
9171       const TypedefType *Typedef = nullptr;
9172       while ((Typedef = PT->getAs<TypedefType>())) {
9173         SourceLocation Loc = Typedef->getDecl()->getLocation();
9174         // SourceLocation may be invalid for a built-in type.
9175         if (Loc.isValid())
9176           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9177         PT = Typedef->desugar();
9178       }
9179     }
9180 
9181     D.setInvalidType();
9182     return;
9183 
9184   case PtrKernelParam:
9185   case ValidKernelParam:
9186     ValidTypes.insert(PT.getTypePtr());
9187     return;
9188 
9189   case RecordKernelParam:
9190     break;
9191   }
9192 
9193   // Track nested structs we will inspect
9194   SmallVector<const Decl *, 4> VisitStack;
9195 
9196   // Track where we are in the nested structs. Items will migrate from
9197   // VisitStack to HistoryStack as we do the DFS for bad field.
9198   SmallVector<const FieldDecl *, 4> HistoryStack;
9199   HistoryStack.push_back(nullptr);
9200 
9201   // At this point we already handled everything except of a RecordType or
9202   // an ArrayType of a RecordType.
9203   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9204   const RecordType *RecTy =
9205       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9206   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9207 
9208   VisitStack.push_back(RecTy->getDecl());
9209   assert(VisitStack.back() && "First decl null?");
9210 
9211   do {
9212     const Decl *Next = VisitStack.pop_back_val();
9213     if (!Next) {
9214       assert(!HistoryStack.empty());
9215       // Found a marker, we have gone up a level
9216       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9217         ValidTypes.insert(Hist->getType().getTypePtr());
9218 
9219       continue;
9220     }
9221 
9222     // Adds everything except the original parameter declaration (which is not a
9223     // field itself) to the history stack.
9224     const RecordDecl *RD;
9225     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9226       HistoryStack.push_back(Field);
9227 
9228       QualType FieldTy = Field->getType();
9229       // Other field types (known to be valid or invalid) are handled while we
9230       // walk around RecordDecl::fields().
9231       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9232              "Unexpected type.");
9233       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9234 
9235       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9236     } else {
9237       RD = cast<RecordDecl>(Next);
9238     }
9239 
9240     // Add a null marker so we know when we've gone back up a level
9241     VisitStack.push_back(nullptr);
9242 
9243     for (const auto *FD : RD->fields()) {
9244       QualType QT = FD->getType();
9245 
9246       if (ValidTypes.count(QT.getTypePtr()))
9247         continue;
9248 
9249       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9250       if (ParamType == ValidKernelParam)
9251         continue;
9252 
9253       if (ParamType == RecordKernelParam) {
9254         VisitStack.push_back(FD);
9255         continue;
9256       }
9257 
9258       // OpenCL v1.2 s6.9.p:
9259       // Arguments to kernel functions that are declared to be a struct or union
9260       // do not allow OpenCL objects to be passed as elements of the struct or
9261       // union.
9262       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9263           ParamType == InvalidAddrSpacePtrKernelParam) {
9264         S.Diag(Param->getLocation(),
9265                diag::err_record_with_pointers_kernel_param)
9266           << PT->isUnionType()
9267           << PT;
9268       } else {
9269         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9270       }
9271 
9272       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9273           << OrigRecDecl->getDeclName();
9274 
9275       // We have an error, now let's go back up through history and show where
9276       // the offending field came from
9277       for (ArrayRef<const FieldDecl *>::const_iterator
9278                I = HistoryStack.begin() + 1,
9279                E = HistoryStack.end();
9280            I != E; ++I) {
9281         const FieldDecl *OuterField = *I;
9282         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9283           << OuterField->getType();
9284       }
9285 
9286       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9287         << QT->isPointerType()
9288         << QT;
9289       D.setInvalidType();
9290       return;
9291     }
9292   } while (!VisitStack.empty());
9293 }
9294 
9295 /// Find the DeclContext in which a tag is implicitly declared if we see an
9296 /// elaborated type specifier in the specified context, and lookup finds
9297 /// nothing.
9298 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9299   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9300     DC = DC->getParent();
9301   return DC;
9302 }
9303 
9304 /// Find the Scope in which a tag is implicitly declared if we see an
9305 /// elaborated type specifier in the specified context, and lookup finds
9306 /// nothing.
9307 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9308   while (S->isClassScope() ||
9309          (LangOpts.CPlusPlus &&
9310           S->isFunctionPrototypeScope()) ||
9311          ((S->getFlags() & Scope::DeclScope) == 0) ||
9312          (S->getEntity() && S->getEntity()->isTransparentContext()))
9313     S = S->getParent();
9314   return S;
9315 }
9316 
9317 /// Determine whether a declaration matches a known function in namespace std.
9318 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9319                          unsigned BuiltinID) {
9320   switch (BuiltinID) {
9321   case Builtin::BI__GetExceptionInfo:
9322     // No type checking whatsoever.
9323     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9324 
9325   case Builtin::BIaddressof:
9326   case Builtin::BI__addressof:
9327   case Builtin::BIforward:
9328   case Builtin::BImove:
9329   case Builtin::BImove_if_noexcept:
9330   case Builtin::BIas_const: {
9331     // Ensure that we don't treat the algorithm
9332     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9333     // as the builtin std::move.
9334     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9335     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9336   }
9337 
9338   default:
9339     return false;
9340   }
9341 }
9342 
9343 NamedDecl*
9344 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9345                               TypeSourceInfo *TInfo, LookupResult &Previous,
9346                               MultiTemplateParamsArg TemplateParamListsRef,
9347                               bool &AddToScope) {
9348   QualType R = TInfo->getType();
9349 
9350   assert(R->isFunctionType());
9351   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9352     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9353 
9354   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9355   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9356   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9357     if (!TemplateParamLists.empty() &&
9358         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9359       TemplateParamLists.back() = Invented;
9360     else
9361       TemplateParamLists.push_back(Invented);
9362   }
9363 
9364   // TODO: consider using NameInfo for diagnostic.
9365   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9366   DeclarationName Name = NameInfo.getName();
9367   StorageClass SC = getFunctionStorageClass(*this, D);
9368 
9369   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9370     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9371          diag::err_invalid_thread)
9372       << DeclSpec::getSpecifierName(TSCS);
9373 
9374   if (D.isFirstDeclarationOfMember())
9375     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9376                            D.getIdentifierLoc());
9377 
9378   bool isFriend = false;
9379   FunctionTemplateDecl *FunctionTemplate = nullptr;
9380   bool isMemberSpecialization = false;
9381   bool isFunctionTemplateSpecialization = false;
9382 
9383   bool isDependentClassScopeExplicitSpecialization = false;
9384   bool HasExplicitTemplateArgs = false;
9385   TemplateArgumentListInfo TemplateArgs;
9386 
9387   bool isVirtualOkay = false;
9388 
9389   DeclContext *OriginalDC = DC;
9390   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9391 
9392   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9393                                               isVirtualOkay);
9394   if (!NewFD) return nullptr;
9395 
9396   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9397     NewFD->setTopLevelDeclInObjCContainer();
9398 
9399   // Set the lexical context. If this is a function-scope declaration, or has a
9400   // C++ scope specifier, or is the object of a friend declaration, the lexical
9401   // context will be different from the semantic context.
9402   NewFD->setLexicalDeclContext(CurContext);
9403 
9404   if (IsLocalExternDecl)
9405     NewFD->setLocalExternDecl();
9406 
9407   if (getLangOpts().CPlusPlus) {
9408     // The rules for implicit inlines changed in C++20 for methods and friends
9409     // with an in-class definition (when such a definition is not attached to
9410     // the global module).  User-specified 'inline' overrides this (set when
9411     // the function decl is created above).
9412     bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlus20 ||
9413                                !NewFD->getOwningModule() ||
9414                                NewFD->getOwningModule()->isGlobalModule();
9415     bool isInline = D.getDeclSpec().isInlineSpecified();
9416     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9417     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9418     isFriend = D.getDeclSpec().isFriendSpecified();
9419     if (isFriend && !isInline && D.isFunctionDefinition()) {
9420       // Pre-C++20 [class.friend]p5
9421       //   A function can be defined in a friend declaration of a
9422       //   class . . . . Such a function is implicitly inline.
9423       // Post C++20 [class.friend]p7
9424       //   Such a function is implicitly an inline function if it is attached
9425       //   to the global module.
9426       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9427     }
9428 
9429     // If this is a method defined in an __interface, and is not a constructor
9430     // or an overloaded operator, then set the pure flag (isVirtual will already
9431     // return true).
9432     if (const CXXRecordDecl *Parent =
9433           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9434       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9435         NewFD->setPure(true);
9436 
9437       // C++ [class.union]p2
9438       //   A union can have member functions, but not virtual functions.
9439       if (isVirtual && Parent->isUnion()) {
9440         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9441         NewFD->setInvalidDecl();
9442       }
9443       if ((Parent->isClass() || Parent->isStruct()) &&
9444           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9445           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9446           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9447         if (auto *Def = Parent->getDefinition())
9448           Def->setInitMethod(true);
9449       }
9450     }
9451 
9452     SetNestedNameSpecifier(*this, NewFD, D);
9453     isMemberSpecialization = false;
9454     isFunctionTemplateSpecialization = false;
9455     if (D.isInvalidType())
9456       NewFD->setInvalidDecl();
9457 
9458     // Match up the template parameter lists with the scope specifier, then
9459     // determine whether we have a template or a template specialization.
9460     bool Invalid = false;
9461     TemplateParameterList *TemplateParams =
9462         MatchTemplateParametersToScopeSpecifier(
9463             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9464             D.getCXXScopeSpec(),
9465             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9466                 ? D.getName().TemplateId
9467                 : nullptr,
9468             TemplateParamLists, isFriend, isMemberSpecialization,
9469             Invalid);
9470     if (TemplateParams) {
9471       // Check that we can declare a template here.
9472       if (CheckTemplateDeclScope(S, TemplateParams))
9473         NewFD->setInvalidDecl();
9474 
9475       if (TemplateParams->size() > 0) {
9476         // This is a function template
9477 
9478         // A destructor cannot be a template.
9479         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9480           Diag(NewFD->getLocation(), diag::err_destructor_template);
9481           NewFD->setInvalidDecl();
9482         }
9483 
9484         // If we're adding a template to a dependent context, we may need to
9485         // rebuilding some of the types used within the template parameter list,
9486         // now that we know what the current instantiation is.
9487         if (DC->isDependentContext()) {
9488           ContextRAII SavedContext(*this, DC);
9489           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9490             Invalid = true;
9491         }
9492 
9493         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9494                                                         NewFD->getLocation(),
9495                                                         Name, TemplateParams,
9496                                                         NewFD);
9497         FunctionTemplate->setLexicalDeclContext(CurContext);
9498         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9499 
9500         // For source fidelity, store the other template param lists.
9501         if (TemplateParamLists.size() > 1) {
9502           NewFD->setTemplateParameterListsInfo(Context,
9503               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9504                   .drop_back(1));
9505         }
9506       } else {
9507         // This is a function template specialization.
9508         isFunctionTemplateSpecialization = true;
9509         // For source fidelity, store all the template param lists.
9510         if (TemplateParamLists.size() > 0)
9511           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9512 
9513         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9514         if (isFriend) {
9515           // We want to remove the "template<>", found here.
9516           SourceRange RemoveRange = TemplateParams->getSourceRange();
9517 
9518           // If we remove the template<> and the name is not a
9519           // template-id, we're actually silently creating a problem:
9520           // the friend declaration will refer to an untemplated decl,
9521           // and clearly the user wants a template specialization.  So
9522           // we need to insert '<>' after the name.
9523           SourceLocation InsertLoc;
9524           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9525             InsertLoc = D.getName().getSourceRange().getEnd();
9526             InsertLoc = getLocForEndOfToken(InsertLoc);
9527           }
9528 
9529           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9530             << Name << RemoveRange
9531             << FixItHint::CreateRemoval(RemoveRange)
9532             << FixItHint::CreateInsertion(InsertLoc, "<>");
9533           Invalid = true;
9534         }
9535       }
9536     } else {
9537       // Check that we can declare a template here.
9538       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9539           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9540         NewFD->setInvalidDecl();
9541 
9542       // All template param lists were matched against the scope specifier:
9543       // this is NOT (an explicit specialization of) a template.
9544       if (TemplateParamLists.size() > 0)
9545         // For source fidelity, store all the template param lists.
9546         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9547     }
9548 
9549     if (Invalid) {
9550       NewFD->setInvalidDecl();
9551       if (FunctionTemplate)
9552         FunctionTemplate->setInvalidDecl();
9553     }
9554 
9555     // C++ [dcl.fct.spec]p5:
9556     //   The virtual specifier shall only be used in declarations of
9557     //   nonstatic class member functions that appear within a
9558     //   member-specification of a class declaration; see 10.3.
9559     //
9560     if (isVirtual && !NewFD->isInvalidDecl()) {
9561       if (!isVirtualOkay) {
9562         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9563              diag::err_virtual_non_function);
9564       } else if (!CurContext->isRecord()) {
9565         // 'virtual' was specified outside of the class.
9566         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9567              diag::err_virtual_out_of_class)
9568           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9569       } else if (NewFD->getDescribedFunctionTemplate()) {
9570         // C++ [temp.mem]p3:
9571         //  A member function template shall not be virtual.
9572         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9573              diag::err_virtual_member_function_template)
9574           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9575       } else {
9576         // Okay: Add virtual to the method.
9577         NewFD->setVirtualAsWritten(true);
9578       }
9579 
9580       if (getLangOpts().CPlusPlus14 &&
9581           NewFD->getReturnType()->isUndeducedType())
9582         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9583     }
9584 
9585     if (getLangOpts().CPlusPlus14 &&
9586         (NewFD->isDependentContext() ||
9587          (isFriend && CurContext->isDependentContext())) &&
9588         NewFD->getReturnType()->isUndeducedType()) {
9589       // If the function template is referenced directly (for instance, as a
9590       // member of the current instantiation), pretend it has a dependent type.
9591       // This is not really justified by the standard, but is the only sane
9592       // thing to do.
9593       // FIXME: For a friend function, we have not marked the function as being
9594       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9595       const FunctionProtoType *FPT =
9596           NewFD->getType()->castAs<FunctionProtoType>();
9597       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9598       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9599                                              FPT->getExtProtoInfo()));
9600     }
9601 
9602     // C++ [dcl.fct.spec]p3:
9603     //  The inline specifier shall not appear on a block scope function
9604     //  declaration.
9605     if (isInline && !NewFD->isInvalidDecl()) {
9606       if (CurContext->isFunctionOrMethod()) {
9607         // 'inline' is not allowed on block scope function declaration.
9608         Diag(D.getDeclSpec().getInlineSpecLoc(),
9609              diag::err_inline_declaration_block_scope) << Name
9610           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9611       }
9612     }
9613 
9614     // C++ [dcl.fct.spec]p6:
9615     //  The explicit specifier shall be used only in the declaration of a
9616     //  constructor or conversion function within its class definition;
9617     //  see 12.3.1 and 12.3.2.
9618     if (hasExplicit && !NewFD->isInvalidDecl() &&
9619         !isa<CXXDeductionGuideDecl>(NewFD)) {
9620       if (!CurContext->isRecord()) {
9621         // 'explicit' was specified outside of the class.
9622         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9623              diag::err_explicit_out_of_class)
9624             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9625       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9626                  !isa<CXXConversionDecl>(NewFD)) {
9627         // 'explicit' was specified on a function that wasn't a constructor
9628         // or conversion function.
9629         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9630              diag::err_explicit_non_ctor_or_conv_function)
9631             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9632       }
9633     }
9634 
9635     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9636     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9637       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9638       // are implicitly inline.
9639       NewFD->setImplicitlyInline();
9640 
9641       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9642       // be either constructors or to return a literal type. Therefore,
9643       // destructors cannot be declared constexpr.
9644       if (isa<CXXDestructorDecl>(NewFD) &&
9645           (!getLangOpts().CPlusPlus20 ||
9646            ConstexprKind == ConstexprSpecKind::Consteval)) {
9647         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9648             << static_cast<int>(ConstexprKind);
9649         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9650                                     ? ConstexprSpecKind::Unspecified
9651                                     : ConstexprSpecKind::Constexpr);
9652       }
9653       // C++20 [dcl.constexpr]p2: An allocation function, or a
9654       // deallocation function shall not be declared with the consteval
9655       // specifier.
9656       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9657           (NewFD->getOverloadedOperator() == OO_New ||
9658            NewFD->getOverloadedOperator() == OO_Array_New ||
9659            NewFD->getOverloadedOperator() == OO_Delete ||
9660            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9661         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9662              diag::err_invalid_consteval_decl_kind)
9663             << NewFD;
9664         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9665       }
9666     }
9667 
9668     // If __module_private__ was specified, mark the function accordingly.
9669     if (D.getDeclSpec().isModulePrivateSpecified()) {
9670       if (isFunctionTemplateSpecialization) {
9671         SourceLocation ModulePrivateLoc
9672           = D.getDeclSpec().getModulePrivateSpecLoc();
9673         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9674           << 0
9675           << FixItHint::CreateRemoval(ModulePrivateLoc);
9676       } else {
9677         NewFD->setModulePrivate();
9678         if (FunctionTemplate)
9679           FunctionTemplate->setModulePrivate();
9680       }
9681     }
9682 
9683     if (isFriend) {
9684       if (FunctionTemplate) {
9685         FunctionTemplate->setObjectOfFriendDecl();
9686         FunctionTemplate->setAccess(AS_public);
9687       }
9688       NewFD->setObjectOfFriendDecl();
9689       NewFD->setAccess(AS_public);
9690     }
9691 
9692     // If a function is defined as defaulted or deleted, mark it as such now.
9693     // We'll do the relevant checks on defaulted / deleted functions later.
9694     switch (D.getFunctionDefinitionKind()) {
9695     case FunctionDefinitionKind::Declaration:
9696     case FunctionDefinitionKind::Definition:
9697       break;
9698 
9699     case FunctionDefinitionKind::Defaulted:
9700       NewFD->setDefaulted();
9701       break;
9702 
9703     case FunctionDefinitionKind::Deleted:
9704       NewFD->setDeletedAsWritten();
9705       break;
9706     }
9707 
9708     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9709         D.isFunctionDefinition() && !isInline) {
9710       // Pre C++20 [class.mfct]p2:
9711       //   A member function may be defined (8.4) in its class definition, in
9712       //   which case it is an inline member function (7.1.2)
9713       // Post C++20 [class.mfct]p1:
9714       //   If a member function is attached to the global module and is defined
9715       //   in its class definition, it is inline.
9716       NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9717     }
9718 
9719     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9720         !CurContext->isRecord()) {
9721       // C++ [class.static]p1:
9722       //   A data or function member of a class may be declared static
9723       //   in a class definition, in which case it is a static member of
9724       //   the class.
9725 
9726       // Complain about the 'static' specifier if it's on an out-of-line
9727       // member function definition.
9728 
9729       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9730       // member function template declaration and class member template
9731       // declaration (MSVC versions before 2015), warn about this.
9732       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9733            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9734              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9735            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9736            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9737         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9738     }
9739 
9740     // C++11 [except.spec]p15:
9741     //   A deallocation function with no exception-specification is treated
9742     //   as if it were specified with noexcept(true).
9743     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9744     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9745          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9746         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9747       NewFD->setType(Context.getFunctionType(
9748           FPT->getReturnType(), FPT->getParamTypes(),
9749           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9750   }
9751 
9752   // Filter out previous declarations that don't match the scope.
9753   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9754                        D.getCXXScopeSpec().isNotEmpty() ||
9755                        isMemberSpecialization ||
9756                        isFunctionTemplateSpecialization);
9757 
9758   // Handle GNU asm-label extension (encoded as an attribute).
9759   if (Expr *E = (Expr*) D.getAsmLabel()) {
9760     // The parser guarantees this is a string.
9761     StringLiteral *SE = cast<StringLiteral>(E);
9762     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9763                                         /*IsLiteralLabel=*/true,
9764                                         SE->getStrTokenLoc(0)));
9765   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9766     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9767       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9768     if (I != ExtnameUndeclaredIdentifiers.end()) {
9769       if (isDeclExternC(NewFD)) {
9770         NewFD->addAttr(I->second);
9771         ExtnameUndeclaredIdentifiers.erase(I);
9772       } else
9773         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9774             << /*Variable*/0 << NewFD;
9775     }
9776   }
9777 
9778   // Copy the parameter declarations from the declarator D to the function
9779   // declaration NewFD, if they are available.  First scavenge them into Params.
9780   SmallVector<ParmVarDecl*, 16> Params;
9781   unsigned FTIIdx;
9782   if (D.isFunctionDeclarator(FTIIdx)) {
9783     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9784 
9785     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9786     // function that takes no arguments, not a function that takes a
9787     // single void argument.
9788     // We let through "const void" here because Sema::GetTypeForDeclarator
9789     // already checks for that case.
9790     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9791       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9792         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9793         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9794         Param->setDeclContext(NewFD);
9795         Params.push_back(Param);
9796 
9797         if (Param->isInvalidDecl())
9798           NewFD->setInvalidDecl();
9799       }
9800     }
9801 
9802     if (!getLangOpts().CPlusPlus) {
9803       // In C, find all the tag declarations from the prototype and move them
9804       // into the function DeclContext. Remove them from the surrounding tag
9805       // injection context of the function, which is typically but not always
9806       // the TU.
9807       DeclContext *PrototypeTagContext =
9808           getTagInjectionContext(NewFD->getLexicalDeclContext());
9809       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9810         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9811 
9812         // We don't want to reparent enumerators. Look at their parent enum
9813         // instead.
9814         if (!TD) {
9815           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9816             TD = cast<EnumDecl>(ECD->getDeclContext());
9817         }
9818         if (!TD)
9819           continue;
9820         DeclContext *TagDC = TD->getLexicalDeclContext();
9821         if (!TagDC->containsDecl(TD))
9822           continue;
9823         TagDC->removeDecl(TD);
9824         TD->setDeclContext(NewFD);
9825         NewFD->addDecl(TD);
9826 
9827         // Preserve the lexical DeclContext if it is not the surrounding tag
9828         // injection context of the FD. In this example, the semantic context of
9829         // E will be f and the lexical context will be S, while both the
9830         // semantic and lexical contexts of S will be f:
9831         //   void f(struct S { enum E { a } f; } s);
9832         if (TagDC != PrototypeTagContext)
9833           TD->setLexicalDeclContext(TagDC);
9834       }
9835     }
9836   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9837     // When we're declaring a function with a typedef, typeof, etc as in the
9838     // following example, we'll need to synthesize (unnamed)
9839     // parameters for use in the declaration.
9840     //
9841     // @code
9842     // typedef void fn(int);
9843     // fn f;
9844     // @endcode
9845 
9846     // Synthesize a parameter for each argument type.
9847     for (const auto &AI : FT->param_types()) {
9848       ParmVarDecl *Param =
9849           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9850       Param->setScopeInfo(0, Params.size());
9851       Params.push_back(Param);
9852     }
9853   } else {
9854     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9855            "Should not need args for typedef of non-prototype fn");
9856   }
9857 
9858   // Finally, we know we have the right number of parameters, install them.
9859   NewFD->setParams(Params);
9860 
9861   if (D.getDeclSpec().isNoreturnSpecified())
9862     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9863                                            D.getDeclSpec().getNoreturnSpecLoc(),
9864                                            AttributeCommonInfo::AS_Keyword));
9865 
9866   // Functions returning a variably modified type violate C99 6.7.5.2p2
9867   // because all functions have linkage.
9868   if (!NewFD->isInvalidDecl() &&
9869       NewFD->getReturnType()->isVariablyModifiedType()) {
9870     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9871     NewFD->setInvalidDecl();
9872   }
9873 
9874   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9875   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9876       !NewFD->hasAttr<SectionAttr>())
9877     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9878         Context, PragmaClangTextSection.SectionName,
9879         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9880 
9881   // Apply an implicit SectionAttr if #pragma code_seg is active.
9882   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9883       !NewFD->hasAttr<SectionAttr>()) {
9884     NewFD->addAttr(SectionAttr::CreateImplicit(
9885         Context, CodeSegStack.CurrentValue->getString(),
9886         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9887         SectionAttr::Declspec_allocate));
9888     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9889                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9890                          ASTContext::PSF_Read,
9891                      NewFD))
9892       NewFD->dropAttr<SectionAttr>();
9893   }
9894 
9895   // Apply an implicit CodeSegAttr from class declspec or
9896   // apply an implicit SectionAttr from #pragma code_seg if active.
9897   if (!NewFD->hasAttr<CodeSegAttr>()) {
9898     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9899                                                                  D.isFunctionDefinition())) {
9900       NewFD->addAttr(SAttr);
9901     }
9902   }
9903 
9904   // Handle attributes.
9905   ProcessDeclAttributes(S, NewFD, D);
9906 
9907   if (getLangOpts().OpenCL) {
9908     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9909     // type declaration will generate a compilation error.
9910     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9911     if (AddressSpace != LangAS::Default) {
9912       Diag(NewFD->getLocation(),
9913            diag::err_opencl_return_value_with_address_space);
9914       NewFD->setInvalidDecl();
9915     }
9916   }
9917 
9918   if (!getLangOpts().CPlusPlus) {
9919     // Perform semantic checking on the function declaration.
9920     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9921       CheckMain(NewFD, D.getDeclSpec());
9922 
9923     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9924       CheckMSVCRTEntryPoint(NewFD);
9925 
9926     if (!NewFD->isInvalidDecl())
9927       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9928                                                   isMemberSpecialization,
9929                                                   D.isFunctionDefinition()));
9930     else if (!Previous.empty())
9931       // Recover gracefully from an invalid redeclaration.
9932       D.setRedeclaration(true);
9933     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9934             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9935            "previous declaration set still overloaded");
9936 
9937     // Diagnose no-prototype function declarations with calling conventions that
9938     // don't support variadic calls. Only do this in C and do it after merging
9939     // possibly prototyped redeclarations.
9940     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9941     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9942       CallingConv CC = FT->getExtInfo().getCC();
9943       if (!supportsVariadicCall(CC)) {
9944         // Windows system headers sometimes accidentally use stdcall without
9945         // (void) parameters, so we relax this to a warning.
9946         int DiagID =
9947             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9948         Diag(NewFD->getLocation(), DiagID)
9949             << FunctionType::getNameForCallConv(CC);
9950       }
9951     }
9952 
9953    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9954        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9955      checkNonTrivialCUnion(NewFD->getReturnType(),
9956                            NewFD->getReturnTypeSourceRange().getBegin(),
9957                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9958   } else {
9959     // C++11 [replacement.functions]p3:
9960     //  The program's definitions shall not be specified as inline.
9961     //
9962     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9963     //
9964     // Suppress the diagnostic if the function is __attribute__((used)), since
9965     // that forces an external definition to be emitted.
9966     if (D.getDeclSpec().isInlineSpecified() &&
9967         NewFD->isReplaceableGlobalAllocationFunction() &&
9968         !NewFD->hasAttr<UsedAttr>())
9969       Diag(D.getDeclSpec().getInlineSpecLoc(),
9970            diag::ext_operator_new_delete_declared_inline)
9971         << NewFD->getDeclName();
9972 
9973     // If the declarator is a template-id, translate the parser's template
9974     // argument list into our AST format.
9975     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9976       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9977       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9978       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9979       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9980                                          TemplateId->NumArgs);
9981       translateTemplateArguments(TemplateArgsPtr,
9982                                  TemplateArgs);
9983 
9984       HasExplicitTemplateArgs = true;
9985 
9986       if (NewFD->isInvalidDecl()) {
9987         HasExplicitTemplateArgs = false;
9988       } else if (FunctionTemplate) {
9989         // Function template with explicit template arguments.
9990         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9991           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9992 
9993         HasExplicitTemplateArgs = false;
9994       } else {
9995         assert((isFunctionTemplateSpecialization ||
9996                 D.getDeclSpec().isFriendSpecified()) &&
9997                "should have a 'template<>' for this decl");
9998         // "friend void foo<>(int);" is an implicit specialization decl.
9999         isFunctionTemplateSpecialization = true;
10000       }
10001     } else if (isFriend && isFunctionTemplateSpecialization) {
10002       // This combination is only possible in a recovery case;  the user
10003       // wrote something like:
10004       //   template <> friend void foo(int);
10005       // which we're recovering from as if the user had written:
10006       //   friend void foo<>(int);
10007       // Go ahead and fake up a template id.
10008       HasExplicitTemplateArgs = true;
10009       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10010       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10011     }
10012 
10013     // We do not add HD attributes to specializations here because
10014     // they may have different constexpr-ness compared to their
10015     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10016     // may end up with different effective targets. Instead, a
10017     // specialization inherits its target attributes from its template
10018     // in the CheckFunctionTemplateSpecialization() call below.
10019     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10020       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10021 
10022     // If it's a friend (and only if it's a friend), it's possible
10023     // that either the specialized function type or the specialized
10024     // template is dependent, and therefore matching will fail.  In
10025     // this case, don't check the specialization yet.
10026     if (isFunctionTemplateSpecialization && isFriend &&
10027         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10028          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10029              TemplateArgs.arguments()))) {
10030       assert(HasExplicitTemplateArgs &&
10031              "friend function specialization without template args");
10032       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10033                                                        Previous))
10034         NewFD->setInvalidDecl();
10035     } else if (isFunctionTemplateSpecialization) {
10036       if (CurContext->isDependentContext() && CurContext->isRecord()
10037           && !isFriend) {
10038         isDependentClassScopeExplicitSpecialization = true;
10039       } else if (!NewFD->isInvalidDecl() &&
10040                  CheckFunctionTemplateSpecialization(
10041                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10042                      Previous))
10043         NewFD->setInvalidDecl();
10044 
10045       // C++ [dcl.stc]p1:
10046       //   A storage-class-specifier shall not be specified in an explicit
10047       //   specialization (14.7.3)
10048       FunctionTemplateSpecializationInfo *Info =
10049           NewFD->getTemplateSpecializationInfo();
10050       if (Info && SC != SC_None) {
10051         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10052           Diag(NewFD->getLocation(),
10053                diag::err_explicit_specialization_inconsistent_storage_class)
10054             << SC
10055             << FixItHint::CreateRemoval(
10056                                       D.getDeclSpec().getStorageClassSpecLoc());
10057 
10058         else
10059           Diag(NewFD->getLocation(),
10060                diag::ext_explicit_specialization_storage_class)
10061             << FixItHint::CreateRemoval(
10062                                       D.getDeclSpec().getStorageClassSpecLoc());
10063       }
10064     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10065       if (CheckMemberSpecialization(NewFD, Previous))
10066           NewFD->setInvalidDecl();
10067     }
10068 
10069     // Perform semantic checking on the function declaration.
10070     if (!isDependentClassScopeExplicitSpecialization) {
10071       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10072         CheckMain(NewFD, D.getDeclSpec());
10073 
10074       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10075         CheckMSVCRTEntryPoint(NewFD);
10076 
10077       if (!NewFD->isInvalidDecl())
10078         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10079                                                     isMemberSpecialization,
10080                                                     D.isFunctionDefinition()));
10081       else if (!Previous.empty())
10082         // Recover gracefully from an invalid redeclaration.
10083         D.setRedeclaration(true);
10084     }
10085 
10086     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10087             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10088            "previous declaration set still overloaded");
10089 
10090     NamedDecl *PrincipalDecl = (FunctionTemplate
10091                                 ? cast<NamedDecl>(FunctionTemplate)
10092                                 : NewFD);
10093 
10094     if (isFriend && NewFD->getPreviousDecl()) {
10095       AccessSpecifier Access = AS_public;
10096       if (!NewFD->isInvalidDecl())
10097         Access = NewFD->getPreviousDecl()->getAccess();
10098 
10099       NewFD->setAccess(Access);
10100       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10101     }
10102 
10103     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10104         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10105       PrincipalDecl->setNonMemberOperator();
10106 
10107     // If we have a function template, check the template parameter
10108     // list. This will check and merge default template arguments.
10109     if (FunctionTemplate) {
10110       FunctionTemplateDecl *PrevTemplate =
10111                                      FunctionTemplate->getPreviousDecl();
10112       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10113                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10114                                     : nullptr,
10115                             D.getDeclSpec().isFriendSpecified()
10116                               ? (D.isFunctionDefinition()
10117                                    ? TPC_FriendFunctionTemplateDefinition
10118                                    : TPC_FriendFunctionTemplate)
10119                               : (D.getCXXScopeSpec().isSet() &&
10120                                  DC && DC->isRecord() &&
10121                                  DC->isDependentContext())
10122                                   ? TPC_ClassTemplateMember
10123                                   : TPC_FunctionTemplate);
10124     }
10125 
10126     if (NewFD->isInvalidDecl()) {
10127       // Ignore all the rest of this.
10128     } else if (!D.isRedeclaration()) {
10129       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10130                                        AddToScope };
10131       // Fake up an access specifier if it's supposed to be a class member.
10132       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10133         NewFD->setAccess(AS_public);
10134 
10135       // Qualified decls generally require a previous declaration.
10136       if (D.getCXXScopeSpec().isSet()) {
10137         // ...with the major exception of templated-scope or
10138         // dependent-scope friend declarations.
10139 
10140         // TODO: we currently also suppress this check in dependent
10141         // contexts because (1) the parameter depth will be off when
10142         // matching friend templates and (2) we might actually be
10143         // selecting a friend based on a dependent factor.  But there
10144         // are situations where these conditions don't apply and we
10145         // can actually do this check immediately.
10146         //
10147         // Unless the scope is dependent, it's always an error if qualified
10148         // redeclaration lookup found nothing at all. Diagnose that now;
10149         // nothing will diagnose that error later.
10150         if (isFriend &&
10151             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10152              (!Previous.empty() && CurContext->isDependentContext()))) {
10153           // ignore these
10154         } else if (NewFD->isCPUDispatchMultiVersion() ||
10155                    NewFD->isCPUSpecificMultiVersion()) {
10156           // ignore this, we allow the redeclaration behavior here to create new
10157           // versions of the function.
10158         } else {
10159           // The user tried to provide an out-of-line definition for a
10160           // function that is a member of a class or namespace, but there
10161           // was no such member function declared (C++ [class.mfct]p2,
10162           // C++ [namespace.memdef]p2). For example:
10163           //
10164           // class X {
10165           //   void f() const;
10166           // };
10167           //
10168           // void X::f() { } // ill-formed
10169           //
10170           // Complain about this problem, and attempt to suggest close
10171           // matches (e.g., those that differ only in cv-qualifiers and
10172           // whether the parameter types are references).
10173 
10174           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10175                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10176             AddToScope = ExtraArgs.AddToScope;
10177             return Result;
10178           }
10179         }
10180 
10181         // Unqualified local friend declarations are required to resolve
10182         // to something.
10183       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10184         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10185                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10186           AddToScope = ExtraArgs.AddToScope;
10187           return Result;
10188         }
10189       }
10190     } else if (!D.isFunctionDefinition() &&
10191                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10192                !isFriend && !isFunctionTemplateSpecialization &&
10193                !isMemberSpecialization) {
10194       // An out-of-line member function declaration must also be a
10195       // definition (C++ [class.mfct]p2).
10196       // Note that this is not the case for explicit specializations of
10197       // function templates or member functions of class templates, per
10198       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10199       // extension for compatibility with old SWIG code which likes to
10200       // generate them.
10201       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10202         << D.getCXXScopeSpec().getRange();
10203     }
10204   }
10205 
10206   // If this is the first declaration of a library builtin function, add
10207   // attributes as appropriate.
10208   if (!D.isRedeclaration()) {
10209     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10210       if (unsigned BuiltinID = II->getBuiltinID()) {
10211         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10212         if (!InStdNamespace &&
10213             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10214           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10215             // Validate the type matches unless this builtin is specified as
10216             // matching regardless of its declared type.
10217             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10218               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10219             } else {
10220               ASTContext::GetBuiltinTypeError Error;
10221               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10222               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10223 
10224               if (!Error && !BuiltinType.isNull() &&
10225                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10226                       NewFD->getType(), BuiltinType))
10227                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10228             }
10229           }
10230         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10231                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10232           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10233         }
10234       }
10235     }
10236   }
10237 
10238   ProcessPragmaWeak(S, NewFD);
10239   checkAttributesAfterMerging(*this, *NewFD);
10240 
10241   AddKnownFunctionAttributes(NewFD);
10242 
10243   if (NewFD->hasAttr<OverloadableAttr>() &&
10244       !NewFD->getType()->getAs<FunctionProtoType>()) {
10245     Diag(NewFD->getLocation(),
10246          diag::err_attribute_overloadable_no_prototype)
10247       << NewFD;
10248 
10249     // Turn this into a variadic function with no parameters.
10250     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10251     FunctionProtoType::ExtProtoInfo EPI(
10252         Context.getDefaultCallingConvention(true, false));
10253     EPI.Variadic = true;
10254     EPI.ExtInfo = FT->getExtInfo();
10255 
10256     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10257     NewFD->setType(R);
10258   }
10259 
10260   // If there's a #pragma GCC visibility in scope, and this isn't a class
10261   // member, set the visibility of this function.
10262   if (!DC->isRecord() && NewFD->isExternallyVisible())
10263     AddPushedVisibilityAttribute(NewFD);
10264 
10265   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10266   // marking the function.
10267   AddCFAuditedAttribute(NewFD);
10268 
10269   // If this is a function definition, check if we have to apply any
10270   // attributes (i.e. optnone and no_builtin) due to a pragma.
10271   if (D.isFunctionDefinition()) {
10272     AddRangeBasedOptnone(NewFD);
10273     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10274     AddSectionMSAllocText(NewFD);
10275     ModifyFnAttributesMSPragmaOptimize(NewFD);
10276   }
10277 
10278   // If this is the first declaration of an extern C variable, update
10279   // the map of such variables.
10280   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10281       isIncompleteDeclExternC(*this, NewFD))
10282     RegisterLocallyScopedExternCDecl(NewFD, S);
10283 
10284   // Set this FunctionDecl's range up to the right paren.
10285   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10286 
10287   if (D.isRedeclaration() && !Previous.empty()) {
10288     NamedDecl *Prev = Previous.getRepresentativeDecl();
10289     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10290                                    isMemberSpecialization ||
10291                                        isFunctionTemplateSpecialization,
10292                                    D.isFunctionDefinition());
10293   }
10294 
10295   if (getLangOpts().CUDA) {
10296     IdentifierInfo *II = NewFD->getIdentifier();
10297     if (II && II->isStr(getCudaConfigureFuncName()) &&
10298         !NewFD->isInvalidDecl() &&
10299         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10300       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10301         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10302             << getCudaConfigureFuncName();
10303       Context.setcudaConfigureCallDecl(NewFD);
10304     }
10305 
10306     // Variadic functions, other than a *declaration* of printf, are not allowed
10307     // in device-side CUDA code, unless someone passed
10308     // -fcuda-allow-variadic-functions.
10309     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10310         (NewFD->hasAttr<CUDADeviceAttr>() ||
10311          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10312         !(II && II->isStr("printf") && NewFD->isExternC() &&
10313           !D.isFunctionDefinition())) {
10314       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10315     }
10316   }
10317 
10318   MarkUnusedFileScopedDecl(NewFD);
10319 
10320 
10321 
10322   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10323     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10324     if (SC == SC_Static) {
10325       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10326       D.setInvalidType();
10327     }
10328 
10329     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10330     if (!NewFD->getReturnType()->isVoidType()) {
10331       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10332       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10333           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10334                                 : FixItHint());
10335       D.setInvalidType();
10336     }
10337 
10338     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10339     for (auto Param : NewFD->parameters())
10340       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10341 
10342     if (getLangOpts().OpenCLCPlusPlus) {
10343       if (DC->isRecord()) {
10344         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10345         D.setInvalidType();
10346       }
10347       if (FunctionTemplate) {
10348         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10349         D.setInvalidType();
10350       }
10351     }
10352   }
10353 
10354   if (getLangOpts().CPlusPlus) {
10355     if (FunctionTemplate) {
10356       if (NewFD->isInvalidDecl())
10357         FunctionTemplate->setInvalidDecl();
10358       return FunctionTemplate;
10359     }
10360 
10361     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10362       CompleteMemberSpecialization(NewFD, Previous);
10363   }
10364 
10365   for (const ParmVarDecl *Param : NewFD->parameters()) {
10366     QualType PT = Param->getType();
10367 
10368     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10369     // types.
10370     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10371       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10372         QualType ElemTy = PipeTy->getElementType();
10373           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10374             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10375             D.setInvalidType();
10376           }
10377       }
10378     }
10379   }
10380 
10381   // Here we have an function template explicit specialization at class scope.
10382   // The actual specialization will be postponed to template instatiation
10383   // time via the ClassScopeFunctionSpecializationDecl node.
10384   if (isDependentClassScopeExplicitSpecialization) {
10385     ClassScopeFunctionSpecializationDecl *NewSpec =
10386                          ClassScopeFunctionSpecializationDecl::Create(
10387                                 Context, CurContext, NewFD->getLocation(),
10388                                 cast<CXXMethodDecl>(NewFD),
10389                                 HasExplicitTemplateArgs, TemplateArgs);
10390     CurContext->addDecl(NewSpec);
10391     AddToScope = false;
10392   }
10393 
10394   // Diagnose availability attributes. Availability cannot be used on functions
10395   // that are run during load/unload.
10396   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10397     if (NewFD->hasAttr<ConstructorAttr>()) {
10398       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10399           << 1;
10400       NewFD->dropAttr<AvailabilityAttr>();
10401     }
10402     if (NewFD->hasAttr<DestructorAttr>()) {
10403       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10404           << 2;
10405       NewFD->dropAttr<AvailabilityAttr>();
10406     }
10407   }
10408 
10409   // Diagnose no_builtin attribute on function declaration that are not a
10410   // definition.
10411   // FIXME: We should really be doing this in
10412   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10413   // the FunctionDecl and at this point of the code
10414   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10415   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10416   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10417     switch (D.getFunctionDefinitionKind()) {
10418     case FunctionDefinitionKind::Defaulted:
10419     case FunctionDefinitionKind::Deleted:
10420       Diag(NBA->getLocation(),
10421            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10422           << NBA->getSpelling();
10423       break;
10424     case FunctionDefinitionKind::Declaration:
10425       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10426           << NBA->getSpelling();
10427       break;
10428     case FunctionDefinitionKind::Definition:
10429       break;
10430     }
10431 
10432   return NewFD;
10433 }
10434 
10435 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10436 /// when __declspec(code_seg) "is applied to a class, all member functions of
10437 /// the class and nested classes -- this includes compiler-generated special
10438 /// member functions -- are put in the specified segment."
10439 /// The actual behavior is a little more complicated. The Microsoft compiler
10440 /// won't check outer classes if there is an active value from #pragma code_seg.
10441 /// The CodeSeg is always applied from the direct parent but only from outer
10442 /// classes when the #pragma code_seg stack is empty. See:
10443 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10444 /// available since MS has removed the page.
10445 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10446   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10447   if (!Method)
10448     return nullptr;
10449   const CXXRecordDecl *Parent = Method->getParent();
10450   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10451     Attr *NewAttr = SAttr->clone(S.getASTContext());
10452     NewAttr->setImplicit(true);
10453     return NewAttr;
10454   }
10455 
10456   // The Microsoft compiler won't check outer classes for the CodeSeg
10457   // when the #pragma code_seg stack is active.
10458   if (S.CodeSegStack.CurrentValue)
10459    return nullptr;
10460 
10461   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10462     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10463       Attr *NewAttr = SAttr->clone(S.getASTContext());
10464       NewAttr->setImplicit(true);
10465       return NewAttr;
10466     }
10467   }
10468   return nullptr;
10469 }
10470 
10471 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10472 /// containing class. Otherwise it will return implicit SectionAttr if the
10473 /// function is a definition and there is an active value on CodeSegStack
10474 /// (from the current #pragma code-seg value).
10475 ///
10476 /// \param FD Function being declared.
10477 /// \param IsDefinition Whether it is a definition or just a declarartion.
10478 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10479 ///          nullptr if no attribute should be added.
10480 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10481                                                        bool IsDefinition) {
10482   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10483     return A;
10484   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10485       CodeSegStack.CurrentValue)
10486     return SectionAttr::CreateImplicit(
10487         getASTContext(), CodeSegStack.CurrentValue->getString(),
10488         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10489         SectionAttr::Declspec_allocate);
10490   return nullptr;
10491 }
10492 
10493 /// Determines if we can perform a correct type check for \p D as a
10494 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10495 /// best-effort check.
10496 ///
10497 /// \param NewD The new declaration.
10498 /// \param OldD The old declaration.
10499 /// \param NewT The portion of the type of the new declaration to check.
10500 /// \param OldT The portion of the type of the old declaration to check.
10501 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10502                                           QualType NewT, QualType OldT) {
10503   if (!NewD->getLexicalDeclContext()->isDependentContext())
10504     return true;
10505 
10506   // For dependently-typed local extern declarations and friends, we can't
10507   // perform a correct type check in general until instantiation:
10508   //
10509   //   int f();
10510   //   template<typename T> void g() { T f(); }
10511   //
10512   // (valid if g() is only instantiated with T = int).
10513   if (NewT->isDependentType() &&
10514       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10515     return false;
10516 
10517   // Similarly, if the previous declaration was a dependent local extern
10518   // declaration, we don't really know its type yet.
10519   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10520     return false;
10521 
10522   return true;
10523 }
10524 
10525 /// Checks if the new declaration declared in dependent context must be
10526 /// put in the same redeclaration chain as the specified declaration.
10527 ///
10528 /// \param D Declaration that is checked.
10529 /// \param PrevDecl Previous declaration found with proper lookup method for the
10530 ///                 same declaration name.
10531 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10532 ///          belongs to.
10533 ///
10534 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10535   if (!D->getLexicalDeclContext()->isDependentContext())
10536     return true;
10537 
10538   // Don't chain dependent friend function definitions until instantiation, to
10539   // permit cases like
10540   //
10541   //   void func();
10542   //   template<typename T> class C1 { friend void func() {} };
10543   //   template<typename T> class C2 { friend void func() {} };
10544   //
10545   // ... which is valid if only one of C1 and C2 is ever instantiated.
10546   //
10547   // FIXME: This need only apply to function definitions. For now, we proxy
10548   // this by checking for a file-scope function. We do not want this to apply
10549   // to friend declarations nominating member functions, because that gets in
10550   // the way of access checks.
10551   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10552     return false;
10553 
10554   auto *VD = dyn_cast<ValueDecl>(D);
10555   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10556   return !VD || !PrevVD ||
10557          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10558                                         PrevVD->getType());
10559 }
10560 
10561 /// Check the target attribute of the function for MultiVersion
10562 /// validity.
10563 ///
10564 /// Returns true if there was an error, false otherwise.
10565 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10566   const auto *TA = FD->getAttr<TargetAttr>();
10567   assert(TA && "MultiVersion Candidate requires a target attribute");
10568   ParsedTargetAttr ParseInfo = TA->parse();
10569   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10570   enum ErrType { Feature = 0, Architecture = 1 };
10571 
10572   if (!ParseInfo.Architecture.empty() &&
10573       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10574     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10575         << Architecture << ParseInfo.Architecture;
10576     return true;
10577   }
10578 
10579   for (const auto &Feat : ParseInfo.Features) {
10580     auto BareFeat = StringRef{Feat}.substr(1);
10581     if (Feat[0] == '-') {
10582       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10583           << Feature << ("no-" + BareFeat).str();
10584       return true;
10585     }
10586 
10587     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10588         !TargetInfo.isValidFeatureName(BareFeat)) {
10589       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10590           << Feature << BareFeat;
10591       return true;
10592     }
10593   }
10594   return false;
10595 }
10596 
10597 // Provide a white-list of attributes that are allowed to be combined with
10598 // multiversion functions.
10599 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10600                                            MultiVersionKind MVKind) {
10601   // Note: this list/diagnosis must match the list in
10602   // checkMultiversionAttributesAllSame.
10603   switch (Kind) {
10604   default:
10605     return false;
10606   case attr::Used:
10607     return MVKind == MultiVersionKind::Target;
10608   case attr::NonNull:
10609   case attr::NoThrow:
10610     return true;
10611   }
10612 }
10613 
10614 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10615                                                  const FunctionDecl *FD,
10616                                                  const FunctionDecl *CausedFD,
10617                                                  MultiVersionKind MVKind) {
10618   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10619     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10620         << static_cast<unsigned>(MVKind) << A;
10621     if (CausedFD)
10622       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10623     return true;
10624   };
10625 
10626   for (const Attr *A : FD->attrs()) {
10627     switch (A->getKind()) {
10628     case attr::CPUDispatch:
10629     case attr::CPUSpecific:
10630       if (MVKind != MultiVersionKind::CPUDispatch &&
10631           MVKind != MultiVersionKind::CPUSpecific)
10632         return Diagnose(S, A);
10633       break;
10634     case attr::Target:
10635       if (MVKind != MultiVersionKind::Target)
10636         return Diagnose(S, A);
10637       break;
10638     case attr::TargetClones:
10639       if (MVKind != MultiVersionKind::TargetClones)
10640         return Diagnose(S, A);
10641       break;
10642     default:
10643       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10644         return Diagnose(S, A);
10645       break;
10646     }
10647   }
10648   return false;
10649 }
10650 
10651 bool Sema::areMultiversionVariantFunctionsCompatible(
10652     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10653     const PartialDiagnostic &NoProtoDiagID,
10654     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10655     const PartialDiagnosticAt &NoSupportDiagIDAt,
10656     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10657     bool ConstexprSupported, bool CLinkageMayDiffer) {
10658   enum DoesntSupport {
10659     FuncTemplates = 0,
10660     VirtFuncs = 1,
10661     DeducedReturn = 2,
10662     Constructors = 3,
10663     Destructors = 4,
10664     DeletedFuncs = 5,
10665     DefaultedFuncs = 6,
10666     ConstexprFuncs = 7,
10667     ConstevalFuncs = 8,
10668     Lambda = 9,
10669   };
10670   enum Different {
10671     CallingConv = 0,
10672     ReturnType = 1,
10673     ConstexprSpec = 2,
10674     InlineSpec = 3,
10675     Linkage = 4,
10676     LanguageLinkage = 5,
10677   };
10678 
10679   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10680       !OldFD->getType()->getAs<FunctionProtoType>()) {
10681     Diag(OldFD->getLocation(), NoProtoDiagID);
10682     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10683     return true;
10684   }
10685 
10686   if (NoProtoDiagID.getDiagID() != 0 &&
10687       !NewFD->getType()->getAs<FunctionProtoType>())
10688     return Diag(NewFD->getLocation(), NoProtoDiagID);
10689 
10690   if (!TemplatesSupported &&
10691       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10692     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10693            << FuncTemplates;
10694 
10695   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10696     if (NewCXXFD->isVirtual())
10697       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10698              << VirtFuncs;
10699 
10700     if (isa<CXXConstructorDecl>(NewCXXFD))
10701       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10702              << Constructors;
10703 
10704     if (isa<CXXDestructorDecl>(NewCXXFD))
10705       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10706              << Destructors;
10707   }
10708 
10709   if (NewFD->isDeleted())
10710     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10711            << DeletedFuncs;
10712 
10713   if (NewFD->isDefaulted())
10714     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10715            << DefaultedFuncs;
10716 
10717   if (!ConstexprSupported && NewFD->isConstexpr())
10718     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10719            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10720 
10721   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10722   const auto *NewType = cast<FunctionType>(NewQType);
10723   QualType NewReturnType = NewType->getReturnType();
10724 
10725   if (NewReturnType->isUndeducedType())
10726     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10727            << DeducedReturn;
10728 
10729   // Ensure the return type is identical.
10730   if (OldFD) {
10731     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10732     const auto *OldType = cast<FunctionType>(OldQType);
10733     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10734     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10735 
10736     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10737       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10738 
10739     QualType OldReturnType = OldType->getReturnType();
10740 
10741     if (OldReturnType != NewReturnType)
10742       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10743 
10744     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10745       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10746 
10747     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10748       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10749 
10750     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10751       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10752 
10753     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10754       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10755 
10756     if (CheckEquivalentExceptionSpec(
10757             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10758             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10759       return true;
10760   }
10761   return false;
10762 }
10763 
10764 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10765                                              const FunctionDecl *NewFD,
10766                                              bool CausesMV,
10767                                              MultiVersionKind MVKind) {
10768   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10769     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10770     if (OldFD)
10771       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10772     return true;
10773   }
10774 
10775   bool IsCPUSpecificCPUDispatchMVKind =
10776       MVKind == MultiVersionKind::CPUDispatch ||
10777       MVKind == MultiVersionKind::CPUSpecific;
10778 
10779   if (CausesMV && OldFD &&
10780       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10781     return true;
10782 
10783   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10784     return true;
10785 
10786   // Only allow transition to MultiVersion if it hasn't been used.
10787   if (OldFD && CausesMV && OldFD->isUsed(false))
10788     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10789 
10790   return S.areMultiversionVariantFunctionsCompatible(
10791       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10792       PartialDiagnosticAt(NewFD->getLocation(),
10793                           S.PDiag(diag::note_multiversioning_caused_here)),
10794       PartialDiagnosticAt(NewFD->getLocation(),
10795                           S.PDiag(diag::err_multiversion_doesnt_support)
10796                               << static_cast<unsigned>(MVKind)),
10797       PartialDiagnosticAt(NewFD->getLocation(),
10798                           S.PDiag(diag::err_multiversion_diff)),
10799       /*TemplatesSupported=*/false,
10800       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10801       /*CLinkageMayDiffer=*/false);
10802 }
10803 
10804 /// Check the validity of a multiversion function declaration that is the
10805 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10806 ///
10807 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10808 ///
10809 /// Returns true if there was an error, false otherwise.
10810 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10811                                            MultiVersionKind MVKind,
10812                                            const TargetAttr *TA) {
10813   assert(MVKind != MultiVersionKind::None &&
10814          "Function lacks multiversion attribute");
10815 
10816   // Target only causes MV if it is default, otherwise this is a normal
10817   // function.
10818   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10819     return false;
10820 
10821   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10822     FD->setInvalidDecl();
10823     return true;
10824   }
10825 
10826   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10827     FD->setInvalidDecl();
10828     return true;
10829   }
10830 
10831   FD->setIsMultiVersion();
10832   return false;
10833 }
10834 
10835 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10836   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10837     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10838       return true;
10839   }
10840 
10841   return false;
10842 }
10843 
10844 static bool CheckTargetCausesMultiVersioning(
10845     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10846     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10847   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10848   ParsedTargetAttr NewParsed = NewTA->parse();
10849   // Sort order doesn't matter, it just needs to be consistent.
10850   llvm::sort(NewParsed.Features);
10851 
10852   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10853   // to change, this is a simple redeclaration.
10854   if (!NewTA->isDefaultVersion() &&
10855       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10856     return false;
10857 
10858   // Otherwise, this decl causes MultiVersioning.
10859   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10860                                        MultiVersionKind::Target)) {
10861     NewFD->setInvalidDecl();
10862     return true;
10863   }
10864 
10865   if (CheckMultiVersionValue(S, NewFD)) {
10866     NewFD->setInvalidDecl();
10867     return true;
10868   }
10869 
10870   // If this is 'default', permit the forward declaration.
10871   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10872     Redeclaration = true;
10873     OldDecl = OldFD;
10874     OldFD->setIsMultiVersion();
10875     NewFD->setIsMultiVersion();
10876     return false;
10877   }
10878 
10879   if (CheckMultiVersionValue(S, OldFD)) {
10880     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10881     NewFD->setInvalidDecl();
10882     return true;
10883   }
10884 
10885   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10886 
10887   if (OldParsed == NewParsed) {
10888     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10889     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10890     NewFD->setInvalidDecl();
10891     return true;
10892   }
10893 
10894   for (const auto *FD : OldFD->redecls()) {
10895     const auto *CurTA = FD->getAttr<TargetAttr>();
10896     // We allow forward declarations before ANY multiversioning attributes, but
10897     // nothing after the fact.
10898     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10899         (!CurTA || CurTA->isInherited())) {
10900       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10901           << 0;
10902       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10903       NewFD->setInvalidDecl();
10904       return true;
10905     }
10906   }
10907 
10908   OldFD->setIsMultiVersion();
10909   NewFD->setIsMultiVersion();
10910   Redeclaration = false;
10911   OldDecl = nullptr;
10912   Previous.clear();
10913   return false;
10914 }
10915 
10916 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10917                                         MultiVersionKind New) {
10918   if (Old == New || Old == MultiVersionKind::None ||
10919       New == MultiVersionKind::None)
10920     return true;
10921 
10922   return (Old == MultiVersionKind::CPUDispatch &&
10923           New == MultiVersionKind::CPUSpecific) ||
10924          (Old == MultiVersionKind::CPUSpecific &&
10925           New == MultiVersionKind::CPUDispatch);
10926 }
10927 
10928 /// Check the validity of a new function declaration being added to an existing
10929 /// multiversioned declaration collection.
10930 static bool CheckMultiVersionAdditionalDecl(
10931     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10932     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10933     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10934     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10935     LookupResult &Previous) {
10936 
10937   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10938   // Disallow mixing of multiversioning types.
10939   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10940     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10941     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10942     NewFD->setInvalidDecl();
10943     return true;
10944   }
10945 
10946   ParsedTargetAttr NewParsed;
10947   if (NewTA) {
10948     NewParsed = NewTA->parse();
10949     llvm::sort(NewParsed.Features);
10950   }
10951 
10952   bool UseMemberUsingDeclRules =
10953       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10954 
10955   bool MayNeedOverloadableChecks =
10956       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10957 
10958   // Next, check ALL non-overloads to see if this is a redeclaration of a
10959   // previous member of the MultiVersion set.
10960   for (NamedDecl *ND : Previous) {
10961     FunctionDecl *CurFD = ND->getAsFunction();
10962     if (!CurFD)
10963       continue;
10964     if (MayNeedOverloadableChecks &&
10965         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10966       continue;
10967 
10968     switch (NewMVKind) {
10969     case MultiVersionKind::None:
10970       assert(OldMVKind == MultiVersionKind::TargetClones &&
10971              "Only target_clones can be omitted in subsequent declarations");
10972       break;
10973     case MultiVersionKind::Target: {
10974       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10975       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10976         NewFD->setIsMultiVersion();
10977         Redeclaration = true;
10978         OldDecl = ND;
10979         return false;
10980       }
10981 
10982       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10983       if (CurParsed == NewParsed) {
10984         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10985         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10986         NewFD->setInvalidDecl();
10987         return true;
10988       }
10989       break;
10990     }
10991     case MultiVersionKind::TargetClones: {
10992       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10993       Redeclaration = true;
10994       OldDecl = CurFD;
10995       NewFD->setIsMultiVersion();
10996 
10997       if (CurClones && NewClones &&
10998           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10999            !std::equal(CurClones->featuresStrs_begin(),
11000                        CurClones->featuresStrs_end(),
11001                        NewClones->featuresStrs_begin()))) {
11002         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11003         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11004         NewFD->setInvalidDecl();
11005         return true;
11006       }
11007 
11008       return false;
11009     }
11010     case MultiVersionKind::CPUSpecific:
11011     case MultiVersionKind::CPUDispatch: {
11012       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11013       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11014       // Handle CPUDispatch/CPUSpecific versions.
11015       // Only 1 CPUDispatch function is allowed, this will make it go through
11016       // the redeclaration errors.
11017       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11018           CurFD->hasAttr<CPUDispatchAttr>()) {
11019         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11020             std::equal(
11021                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11022                 NewCPUDisp->cpus_begin(),
11023                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11024                   return Cur->getName() == New->getName();
11025                 })) {
11026           NewFD->setIsMultiVersion();
11027           Redeclaration = true;
11028           OldDecl = ND;
11029           return false;
11030         }
11031 
11032         // If the declarations don't match, this is an error condition.
11033         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11034         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11035         NewFD->setInvalidDecl();
11036         return true;
11037       }
11038       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11039         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11040             std::equal(
11041                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11042                 NewCPUSpec->cpus_begin(),
11043                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11044                   return Cur->getName() == New->getName();
11045                 })) {
11046           NewFD->setIsMultiVersion();
11047           Redeclaration = true;
11048           OldDecl = ND;
11049           return false;
11050         }
11051 
11052         // Only 1 version of CPUSpecific is allowed for each CPU.
11053         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11054           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11055             if (CurII == NewII) {
11056               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11057                   << NewII;
11058               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11059               NewFD->setInvalidDecl();
11060               return true;
11061             }
11062           }
11063         }
11064       }
11065       break;
11066     }
11067     }
11068   }
11069 
11070   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11071   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11072   // handled in the attribute adding step.
11073   if (NewMVKind == MultiVersionKind::Target &&
11074       CheckMultiVersionValue(S, NewFD)) {
11075     NewFD->setInvalidDecl();
11076     return true;
11077   }
11078 
11079   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11080                                        !OldFD->isMultiVersion(), NewMVKind)) {
11081     NewFD->setInvalidDecl();
11082     return true;
11083   }
11084 
11085   // Permit forward declarations in the case where these two are compatible.
11086   if (!OldFD->isMultiVersion()) {
11087     OldFD->setIsMultiVersion();
11088     NewFD->setIsMultiVersion();
11089     Redeclaration = true;
11090     OldDecl = OldFD;
11091     return false;
11092   }
11093 
11094   NewFD->setIsMultiVersion();
11095   Redeclaration = false;
11096   OldDecl = nullptr;
11097   Previous.clear();
11098   return false;
11099 }
11100 
11101 /// Check the validity of a mulitversion function declaration.
11102 /// Also sets the multiversion'ness' of the function itself.
11103 ///
11104 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11105 ///
11106 /// Returns true if there was an error, false otherwise.
11107 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11108                                       bool &Redeclaration, NamedDecl *&OldDecl,
11109                                       LookupResult &Previous) {
11110   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11111   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11112   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11113   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11114   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11115 
11116   // Main isn't allowed to become a multiversion function, however it IS
11117   // permitted to have 'main' be marked with the 'target' optimization hint.
11118   if (NewFD->isMain()) {
11119     if (MVKind != MultiVersionKind::None &&
11120         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11121       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11122       NewFD->setInvalidDecl();
11123       return true;
11124     }
11125     return false;
11126   }
11127 
11128   if (!OldDecl || !OldDecl->getAsFunction() ||
11129       OldDecl->getDeclContext()->getRedeclContext() !=
11130           NewFD->getDeclContext()->getRedeclContext()) {
11131     // If there's no previous declaration, AND this isn't attempting to cause
11132     // multiversioning, this isn't an error condition.
11133     if (MVKind == MultiVersionKind::None)
11134       return false;
11135     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11136   }
11137 
11138   FunctionDecl *OldFD = OldDecl->getAsFunction();
11139 
11140   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11141     return false;
11142 
11143   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11144   // for target_clones.
11145   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11146       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11147     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11148         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11149     NewFD->setInvalidDecl();
11150     return true;
11151   }
11152 
11153   if (!OldFD->isMultiVersion()) {
11154     switch (MVKind) {
11155     case MultiVersionKind::Target:
11156       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11157                                               Redeclaration, OldDecl, Previous);
11158     case MultiVersionKind::TargetClones:
11159       if (OldFD->isUsed(false)) {
11160         NewFD->setInvalidDecl();
11161         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11162       }
11163       OldFD->setIsMultiVersion();
11164       break;
11165     case MultiVersionKind::CPUDispatch:
11166     case MultiVersionKind::CPUSpecific:
11167     case MultiVersionKind::None:
11168       break;
11169     }
11170   }
11171 
11172   // At this point, we have a multiversion function decl (in OldFD) AND an
11173   // appropriate attribute in the current function decl.  Resolve that these are
11174   // still compatible with previous declarations.
11175   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11176                                          NewCPUDisp, NewCPUSpec, NewClones,
11177                                          Redeclaration, OldDecl, Previous);
11178 }
11179 
11180 /// Perform semantic checking of a new function declaration.
11181 ///
11182 /// Performs semantic analysis of the new function declaration
11183 /// NewFD. This routine performs all semantic checking that does not
11184 /// require the actual declarator involved in the declaration, and is
11185 /// used both for the declaration of functions as they are parsed
11186 /// (called via ActOnDeclarator) and for the declaration of functions
11187 /// that have been instantiated via C++ template instantiation (called
11188 /// via InstantiateDecl).
11189 ///
11190 /// \param IsMemberSpecialization whether this new function declaration is
11191 /// a member specialization (that replaces any definition provided by the
11192 /// previous declaration).
11193 ///
11194 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11195 ///
11196 /// \returns true if the function declaration is a redeclaration.
11197 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11198                                     LookupResult &Previous,
11199                                     bool IsMemberSpecialization,
11200                                     bool DeclIsDefn) {
11201   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11202          "Variably modified return types are not handled here");
11203 
11204   // Determine whether the type of this function should be merged with
11205   // a previous visible declaration. This never happens for functions in C++,
11206   // and always happens in C if the previous declaration was visible.
11207   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11208                                !Previous.isShadowed();
11209 
11210   bool Redeclaration = false;
11211   NamedDecl *OldDecl = nullptr;
11212   bool MayNeedOverloadableChecks = false;
11213 
11214   // Merge or overload the declaration with an existing declaration of
11215   // the same name, if appropriate.
11216   if (!Previous.empty()) {
11217     // Determine whether NewFD is an overload of PrevDecl or
11218     // a declaration that requires merging. If it's an overload,
11219     // there's no more work to do here; we'll just add the new
11220     // function to the scope.
11221     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11222       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11223       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11224         Redeclaration = true;
11225         OldDecl = Candidate;
11226       }
11227     } else {
11228       MayNeedOverloadableChecks = true;
11229       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11230                             /*NewIsUsingDecl*/ false)) {
11231       case Ovl_Match:
11232         Redeclaration = true;
11233         break;
11234 
11235       case Ovl_NonFunction:
11236         Redeclaration = true;
11237         break;
11238 
11239       case Ovl_Overload:
11240         Redeclaration = false;
11241         break;
11242       }
11243     }
11244   }
11245 
11246   // Check for a previous extern "C" declaration with this name.
11247   if (!Redeclaration &&
11248       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11249     if (!Previous.empty()) {
11250       // This is an extern "C" declaration with the same name as a previous
11251       // declaration, and thus redeclares that entity...
11252       Redeclaration = true;
11253       OldDecl = Previous.getFoundDecl();
11254       MergeTypeWithPrevious = false;
11255 
11256       // ... except in the presence of __attribute__((overloadable)).
11257       if (OldDecl->hasAttr<OverloadableAttr>() ||
11258           NewFD->hasAttr<OverloadableAttr>()) {
11259         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11260           MayNeedOverloadableChecks = true;
11261           Redeclaration = false;
11262           OldDecl = nullptr;
11263         }
11264       }
11265     }
11266   }
11267 
11268   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11269     return Redeclaration;
11270 
11271   // PPC MMA non-pointer types are not allowed as function return types.
11272   if (Context.getTargetInfo().getTriple().isPPC64() &&
11273       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11274     NewFD->setInvalidDecl();
11275   }
11276 
11277   // C++11 [dcl.constexpr]p8:
11278   //   A constexpr specifier for a non-static member function that is not
11279   //   a constructor declares that member function to be const.
11280   //
11281   // This needs to be delayed until we know whether this is an out-of-line
11282   // definition of a static member function.
11283   //
11284   // This rule is not present in C++1y, so we produce a backwards
11285   // compatibility warning whenever it happens in C++11.
11286   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11287   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11288       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11289       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11290     CXXMethodDecl *OldMD = nullptr;
11291     if (OldDecl)
11292       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11293     if (!OldMD || !OldMD->isStatic()) {
11294       const FunctionProtoType *FPT =
11295         MD->getType()->castAs<FunctionProtoType>();
11296       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11297       EPI.TypeQuals.addConst();
11298       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11299                                           FPT->getParamTypes(), EPI));
11300 
11301       // Warn that we did this, if we're not performing template instantiation.
11302       // In that case, we'll have warned already when the template was defined.
11303       if (!inTemplateInstantiation()) {
11304         SourceLocation AddConstLoc;
11305         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11306                 .IgnoreParens().getAs<FunctionTypeLoc>())
11307           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11308 
11309         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11310           << FixItHint::CreateInsertion(AddConstLoc, " const");
11311       }
11312     }
11313   }
11314 
11315   if (Redeclaration) {
11316     // NewFD and OldDecl represent declarations that need to be
11317     // merged.
11318     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11319                           DeclIsDefn)) {
11320       NewFD->setInvalidDecl();
11321       return Redeclaration;
11322     }
11323 
11324     Previous.clear();
11325     Previous.addDecl(OldDecl);
11326 
11327     if (FunctionTemplateDecl *OldTemplateDecl =
11328             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11329       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11330       FunctionTemplateDecl *NewTemplateDecl
11331         = NewFD->getDescribedFunctionTemplate();
11332       assert(NewTemplateDecl && "Template/non-template mismatch");
11333 
11334       // The call to MergeFunctionDecl above may have created some state in
11335       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11336       // can add it as a redeclaration.
11337       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11338 
11339       NewFD->setPreviousDeclaration(OldFD);
11340       if (NewFD->isCXXClassMember()) {
11341         NewFD->setAccess(OldTemplateDecl->getAccess());
11342         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11343       }
11344 
11345       // If this is an explicit specialization of a member that is a function
11346       // template, mark it as a member specialization.
11347       if (IsMemberSpecialization &&
11348           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11349         NewTemplateDecl->setMemberSpecialization();
11350         assert(OldTemplateDecl->isMemberSpecialization());
11351         // Explicit specializations of a member template do not inherit deleted
11352         // status from the parent member template that they are specializing.
11353         if (OldFD->isDeleted()) {
11354           // FIXME: This assert will not hold in the presence of modules.
11355           assert(OldFD->getCanonicalDecl() == OldFD);
11356           // FIXME: We need an update record for this AST mutation.
11357           OldFD->setDeletedAsWritten(false);
11358         }
11359       }
11360 
11361     } else {
11362       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11363         auto *OldFD = cast<FunctionDecl>(OldDecl);
11364         // This needs to happen first so that 'inline' propagates.
11365         NewFD->setPreviousDeclaration(OldFD);
11366         if (NewFD->isCXXClassMember())
11367           NewFD->setAccess(OldFD->getAccess());
11368       }
11369     }
11370   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11371              !NewFD->getAttr<OverloadableAttr>()) {
11372     assert((Previous.empty() ||
11373             llvm::any_of(Previous,
11374                          [](const NamedDecl *ND) {
11375                            return ND->hasAttr<OverloadableAttr>();
11376                          })) &&
11377            "Non-redecls shouldn't happen without overloadable present");
11378 
11379     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11380       const auto *FD = dyn_cast<FunctionDecl>(ND);
11381       return FD && !FD->hasAttr<OverloadableAttr>();
11382     });
11383 
11384     if (OtherUnmarkedIter != Previous.end()) {
11385       Diag(NewFD->getLocation(),
11386            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11387       Diag((*OtherUnmarkedIter)->getLocation(),
11388            diag::note_attribute_overloadable_prev_overload)
11389           << false;
11390 
11391       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11392     }
11393   }
11394 
11395   if (LangOpts.OpenMP)
11396     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11397 
11398   // Semantic checking for this function declaration (in isolation).
11399 
11400   if (getLangOpts().CPlusPlus) {
11401     // C++-specific checks.
11402     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11403       CheckConstructor(Constructor);
11404     } else if (CXXDestructorDecl *Destructor =
11405                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11406       CXXRecordDecl *Record = Destructor->getParent();
11407       QualType ClassType = Context.getTypeDeclType(Record);
11408 
11409       // FIXME: Shouldn't we be able to perform this check even when the class
11410       // type is dependent? Both gcc and edg can handle that.
11411       if (!ClassType->isDependentType()) {
11412         DeclarationName Name
11413           = Context.DeclarationNames.getCXXDestructorName(
11414                                         Context.getCanonicalType(ClassType));
11415         if (NewFD->getDeclName() != Name) {
11416           Diag(NewFD->getLocation(), diag::err_destructor_name);
11417           NewFD->setInvalidDecl();
11418           return Redeclaration;
11419         }
11420       }
11421     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11422       if (auto *TD = Guide->getDescribedFunctionTemplate())
11423         CheckDeductionGuideTemplate(TD);
11424 
11425       // A deduction guide is not on the list of entities that can be
11426       // explicitly specialized.
11427       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11428         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11429             << /*explicit specialization*/ 1;
11430     }
11431 
11432     // Find any virtual functions that this function overrides.
11433     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11434       if (!Method->isFunctionTemplateSpecialization() &&
11435           !Method->getDescribedFunctionTemplate() &&
11436           Method->isCanonicalDecl()) {
11437         AddOverriddenMethods(Method->getParent(), Method);
11438       }
11439       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11440         // C++2a [class.virtual]p6
11441         // A virtual method shall not have a requires-clause.
11442         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11443              diag::err_constrained_virtual_method);
11444 
11445       if (Method->isStatic())
11446         checkThisInStaticMemberFunctionType(Method);
11447     }
11448 
11449     // C++20: dcl.decl.general p4:
11450     // The optional requires-clause ([temp.pre]) in an init-declarator or
11451     // member-declarator shall be present only if the declarator declares a
11452     // templated function ([dcl.fct]).
11453     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11454       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11455         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11456     }
11457 
11458     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11459       ActOnConversionDeclarator(Conversion);
11460 
11461     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11462     if (NewFD->isOverloadedOperator() &&
11463         CheckOverloadedOperatorDeclaration(NewFD)) {
11464       NewFD->setInvalidDecl();
11465       return Redeclaration;
11466     }
11467 
11468     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11469     if (NewFD->getLiteralIdentifier() &&
11470         CheckLiteralOperatorDeclaration(NewFD)) {
11471       NewFD->setInvalidDecl();
11472       return Redeclaration;
11473     }
11474 
11475     // In C++, check default arguments now that we have merged decls. Unless
11476     // the lexical context is the class, because in this case this is done
11477     // during delayed parsing anyway.
11478     if (!CurContext->isRecord())
11479       CheckCXXDefaultArguments(NewFD);
11480 
11481     // If this function is declared as being extern "C", then check to see if
11482     // the function returns a UDT (class, struct, or union type) that is not C
11483     // compatible, and if it does, warn the user.
11484     // But, issue any diagnostic on the first declaration only.
11485     if (Previous.empty() && NewFD->isExternC()) {
11486       QualType R = NewFD->getReturnType();
11487       if (R->isIncompleteType() && !R->isVoidType())
11488         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11489             << NewFD << R;
11490       else if (!R.isPODType(Context) && !R->isVoidType() &&
11491                !R->isObjCObjectPointerType())
11492         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11493     }
11494 
11495     // C++1z [dcl.fct]p6:
11496     //   [...] whether the function has a non-throwing exception-specification
11497     //   [is] part of the function type
11498     //
11499     // This results in an ABI break between C++14 and C++17 for functions whose
11500     // declared type includes an exception-specification in a parameter or
11501     // return type. (Exception specifications on the function itself are OK in
11502     // most cases, and exception specifications are not permitted in most other
11503     // contexts where they could make it into a mangling.)
11504     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11505       auto HasNoexcept = [&](QualType T) -> bool {
11506         // Strip off declarator chunks that could be between us and a function
11507         // type. We don't need to look far, exception specifications are very
11508         // restricted prior to C++17.
11509         if (auto *RT = T->getAs<ReferenceType>())
11510           T = RT->getPointeeType();
11511         else if (T->isAnyPointerType())
11512           T = T->getPointeeType();
11513         else if (auto *MPT = T->getAs<MemberPointerType>())
11514           T = MPT->getPointeeType();
11515         if (auto *FPT = T->getAs<FunctionProtoType>())
11516           if (FPT->isNothrow())
11517             return true;
11518         return false;
11519       };
11520 
11521       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11522       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11523       for (QualType T : FPT->param_types())
11524         AnyNoexcept |= HasNoexcept(T);
11525       if (AnyNoexcept)
11526         Diag(NewFD->getLocation(),
11527              diag::warn_cxx17_compat_exception_spec_in_signature)
11528             << NewFD;
11529     }
11530 
11531     if (!Redeclaration && LangOpts.CUDA)
11532       checkCUDATargetOverload(NewFD, Previous);
11533   }
11534   return Redeclaration;
11535 }
11536 
11537 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11538   // C++11 [basic.start.main]p3:
11539   //   A program that [...] declares main to be inline, static or
11540   //   constexpr is ill-formed.
11541   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11542   //   appear in a declaration of main.
11543   // static main is not an error under C99, but we should warn about it.
11544   // We accept _Noreturn main as an extension.
11545   if (FD->getStorageClass() == SC_Static)
11546     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11547          ? diag::err_static_main : diag::warn_static_main)
11548       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11549   if (FD->isInlineSpecified())
11550     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11551       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11552   if (DS.isNoreturnSpecified()) {
11553     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11554     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11555     Diag(NoreturnLoc, diag::ext_noreturn_main);
11556     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11557       << FixItHint::CreateRemoval(NoreturnRange);
11558   }
11559   if (FD->isConstexpr()) {
11560     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11561         << FD->isConsteval()
11562         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11563     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11564   }
11565 
11566   if (getLangOpts().OpenCL) {
11567     Diag(FD->getLocation(), diag::err_opencl_no_main)
11568         << FD->hasAttr<OpenCLKernelAttr>();
11569     FD->setInvalidDecl();
11570     return;
11571   }
11572 
11573   // Functions named main in hlsl are default entries, but don't have specific
11574   // signatures they are required to conform to.
11575   if (getLangOpts().HLSL)
11576     return;
11577 
11578   QualType T = FD->getType();
11579   assert(T->isFunctionType() && "function decl is not of function type");
11580   const FunctionType* FT = T->castAs<FunctionType>();
11581 
11582   // Set default calling convention for main()
11583   if (FT->getCallConv() != CC_C) {
11584     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11585     FD->setType(QualType(FT, 0));
11586     T = Context.getCanonicalType(FD->getType());
11587   }
11588 
11589   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11590     // In C with GNU extensions we allow main() to have non-integer return
11591     // type, but we should warn about the extension, and we disable the
11592     // implicit-return-zero rule.
11593 
11594     // GCC in C mode accepts qualified 'int'.
11595     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11596       FD->setHasImplicitReturnZero(true);
11597     else {
11598       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11599       SourceRange RTRange = FD->getReturnTypeSourceRange();
11600       if (RTRange.isValid())
11601         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11602             << FixItHint::CreateReplacement(RTRange, "int");
11603     }
11604   } else {
11605     // In C and C++, main magically returns 0 if you fall off the end;
11606     // set the flag which tells us that.
11607     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11608 
11609     // All the standards say that main() should return 'int'.
11610     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11611       FD->setHasImplicitReturnZero(true);
11612     else {
11613       // Otherwise, this is just a flat-out error.
11614       SourceRange RTRange = FD->getReturnTypeSourceRange();
11615       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11616           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11617                                 : FixItHint());
11618       FD->setInvalidDecl(true);
11619     }
11620   }
11621 
11622   // Treat protoless main() as nullary.
11623   if (isa<FunctionNoProtoType>(FT)) return;
11624 
11625   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11626   unsigned nparams = FTP->getNumParams();
11627   assert(FD->getNumParams() == nparams);
11628 
11629   bool HasExtraParameters = (nparams > 3);
11630 
11631   if (FTP->isVariadic()) {
11632     Diag(FD->getLocation(), diag::ext_variadic_main);
11633     // FIXME: if we had information about the location of the ellipsis, we
11634     // could add a FixIt hint to remove it as a parameter.
11635   }
11636 
11637   // Darwin passes an undocumented fourth argument of type char**.  If
11638   // other platforms start sprouting these, the logic below will start
11639   // getting shifty.
11640   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11641     HasExtraParameters = false;
11642 
11643   if (HasExtraParameters) {
11644     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11645     FD->setInvalidDecl(true);
11646     nparams = 3;
11647   }
11648 
11649   // FIXME: a lot of the following diagnostics would be improved
11650   // if we had some location information about types.
11651 
11652   QualType CharPP =
11653     Context.getPointerType(Context.getPointerType(Context.CharTy));
11654   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11655 
11656   for (unsigned i = 0; i < nparams; ++i) {
11657     QualType AT = FTP->getParamType(i);
11658 
11659     bool mismatch = true;
11660 
11661     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11662       mismatch = false;
11663     else if (Expected[i] == CharPP) {
11664       // As an extension, the following forms are okay:
11665       //   char const **
11666       //   char const * const *
11667       //   char * const *
11668 
11669       QualifierCollector qs;
11670       const PointerType* PT;
11671       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11672           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11673           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11674                               Context.CharTy)) {
11675         qs.removeConst();
11676         mismatch = !qs.empty();
11677       }
11678     }
11679 
11680     if (mismatch) {
11681       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11682       // TODO: suggest replacing given type with expected type
11683       FD->setInvalidDecl(true);
11684     }
11685   }
11686 
11687   if (nparams == 1 && !FD->isInvalidDecl()) {
11688     Diag(FD->getLocation(), diag::warn_main_one_arg);
11689   }
11690 
11691   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11692     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11693     FD->setInvalidDecl();
11694   }
11695 }
11696 
11697 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11698 
11699   // Default calling convention for main and wmain is __cdecl
11700   if (FD->getName() == "main" || FD->getName() == "wmain")
11701     return false;
11702 
11703   // Default calling convention for MinGW is __cdecl
11704   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11705   if (T.isWindowsGNUEnvironment())
11706     return false;
11707 
11708   // Default calling convention for WinMain, wWinMain and DllMain
11709   // is __stdcall on 32 bit Windows
11710   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11711     return true;
11712 
11713   return false;
11714 }
11715 
11716 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11717   QualType T = FD->getType();
11718   assert(T->isFunctionType() && "function decl is not of function type");
11719   const FunctionType *FT = T->castAs<FunctionType>();
11720 
11721   // Set an implicit return of 'zero' if the function can return some integral,
11722   // enumeration, pointer or nullptr type.
11723   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11724       FT->getReturnType()->isAnyPointerType() ||
11725       FT->getReturnType()->isNullPtrType())
11726     // DllMain is exempt because a return value of zero means it failed.
11727     if (FD->getName() != "DllMain")
11728       FD->setHasImplicitReturnZero(true);
11729 
11730   // Explicity specified calling conventions are applied to MSVC entry points
11731   if (!hasExplicitCallingConv(T)) {
11732     if (isDefaultStdCall(FD, *this)) {
11733       if (FT->getCallConv() != CC_X86StdCall) {
11734         FT = Context.adjustFunctionType(
11735             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11736         FD->setType(QualType(FT, 0));
11737       }
11738     } else if (FT->getCallConv() != CC_C) {
11739       FT = Context.adjustFunctionType(FT,
11740                                       FT->getExtInfo().withCallingConv(CC_C));
11741       FD->setType(QualType(FT, 0));
11742     }
11743   }
11744 
11745   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11746     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11747     FD->setInvalidDecl();
11748   }
11749 }
11750 
11751 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11752   // FIXME: Need strict checking.  In C89, we need to check for
11753   // any assignment, increment, decrement, function-calls, or
11754   // commas outside of a sizeof.  In C99, it's the same list,
11755   // except that the aforementioned are allowed in unevaluated
11756   // expressions.  Everything else falls under the
11757   // "may accept other forms of constant expressions" exception.
11758   //
11759   // Regular C++ code will not end up here (exceptions: language extensions,
11760   // OpenCL C++ etc), so the constant expression rules there don't matter.
11761   if (Init->isValueDependent()) {
11762     assert(Init->containsErrors() &&
11763            "Dependent code should only occur in error-recovery path.");
11764     return true;
11765   }
11766   const Expr *Culprit;
11767   if (Init->isConstantInitializer(Context, false, &Culprit))
11768     return false;
11769   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11770     << Culprit->getSourceRange();
11771   return true;
11772 }
11773 
11774 namespace {
11775   // Visits an initialization expression to see if OrigDecl is evaluated in
11776   // its own initialization and throws a warning if it does.
11777   class SelfReferenceChecker
11778       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11779     Sema &S;
11780     Decl *OrigDecl;
11781     bool isRecordType;
11782     bool isPODType;
11783     bool isReferenceType;
11784 
11785     bool isInitList;
11786     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11787 
11788   public:
11789     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11790 
11791     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11792                                                     S(S), OrigDecl(OrigDecl) {
11793       isPODType = false;
11794       isRecordType = false;
11795       isReferenceType = false;
11796       isInitList = false;
11797       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11798         isPODType = VD->getType().isPODType(S.Context);
11799         isRecordType = VD->getType()->isRecordType();
11800         isReferenceType = VD->getType()->isReferenceType();
11801       }
11802     }
11803 
11804     // For most expressions, just call the visitor.  For initializer lists,
11805     // track the index of the field being initialized since fields are
11806     // initialized in order allowing use of previously initialized fields.
11807     void CheckExpr(Expr *E) {
11808       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11809       if (!InitList) {
11810         Visit(E);
11811         return;
11812       }
11813 
11814       // Track and increment the index here.
11815       isInitList = true;
11816       InitFieldIndex.push_back(0);
11817       for (auto Child : InitList->children()) {
11818         CheckExpr(cast<Expr>(Child));
11819         ++InitFieldIndex.back();
11820       }
11821       InitFieldIndex.pop_back();
11822     }
11823 
11824     // Returns true if MemberExpr is checked and no further checking is needed.
11825     // Returns false if additional checking is required.
11826     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11827       llvm::SmallVector<FieldDecl*, 4> Fields;
11828       Expr *Base = E;
11829       bool ReferenceField = false;
11830 
11831       // Get the field members used.
11832       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11833         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11834         if (!FD)
11835           return false;
11836         Fields.push_back(FD);
11837         if (FD->getType()->isReferenceType())
11838           ReferenceField = true;
11839         Base = ME->getBase()->IgnoreParenImpCasts();
11840       }
11841 
11842       // Keep checking only if the base Decl is the same.
11843       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11844       if (!DRE || DRE->getDecl() != OrigDecl)
11845         return false;
11846 
11847       // A reference field can be bound to an unininitialized field.
11848       if (CheckReference && !ReferenceField)
11849         return true;
11850 
11851       // Convert FieldDecls to their index number.
11852       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11853       for (const FieldDecl *I : llvm::reverse(Fields))
11854         UsedFieldIndex.push_back(I->getFieldIndex());
11855 
11856       // See if a warning is needed by checking the first difference in index
11857       // numbers.  If field being used has index less than the field being
11858       // initialized, then the use is safe.
11859       for (auto UsedIter = UsedFieldIndex.begin(),
11860                 UsedEnd = UsedFieldIndex.end(),
11861                 OrigIter = InitFieldIndex.begin(),
11862                 OrigEnd = InitFieldIndex.end();
11863            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11864         if (*UsedIter < *OrigIter)
11865           return true;
11866         if (*UsedIter > *OrigIter)
11867           break;
11868       }
11869 
11870       // TODO: Add a different warning which will print the field names.
11871       HandleDeclRefExpr(DRE);
11872       return true;
11873     }
11874 
11875     // For most expressions, the cast is directly above the DeclRefExpr.
11876     // For conditional operators, the cast can be outside the conditional
11877     // operator if both expressions are DeclRefExpr's.
11878     void HandleValue(Expr *E) {
11879       E = E->IgnoreParens();
11880       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11881         HandleDeclRefExpr(DRE);
11882         return;
11883       }
11884 
11885       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11886         Visit(CO->getCond());
11887         HandleValue(CO->getTrueExpr());
11888         HandleValue(CO->getFalseExpr());
11889         return;
11890       }
11891 
11892       if (BinaryConditionalOperator *BCO =
11893               dyn_cast<BinaryConditionalOperator>(E)) {
11894         Visit(BCO->getCond());
11895         HandleValue(BCO->getFalseExpr());
11896         return;
11897       }
11898 
11899       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11900         HandleValue(OVE->getSourceExpr());
11901         return;
11902       }
11903 
11904       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11905         if (BO->getOpcode() == BO_Comma) {
11906           Visit(BO->getLHS());
11907           HandleValue(BO->getRHS());
11908           return;
11909         }
11910       }
11911 
11912       if (isa<MemberExpr>(E)) {
11913         if (isInitList) {
11914           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11915                                       false /*CheckReference*/))
11916             return;
11917         }
11918 
11919         Expr *Base = E->IgnoreParenImpCasts();
11920         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11921           // Check for static member variables and don't warn on them.
11922           if (!isa<FieldDecl>(ME->getMemberDecl()))
11923             return;
11924           Base = ME->getBase()->IgnoreParenImpCasts();
11925         }
11926         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11927           HandleDeclRefExpr(DRE);
11928         return;
11929       }
11930 
11931       Visit(E);
11932     }
11933 
11934     // Reference types not handled in HandleValue are handled here since all
11935     // uses of references are bad, not just r-value uses.
11936     void VisitDeclRefExpr(DeclRefExpr *E) {
11937       if (isReferenceType)
11938         HandleDeclRefExpr(E);
11939     }
11940 
11941     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11942       if (E->getCastKind() == CK_LValueToRValue) {
11943         HandleValue(E->getSubExpr());
11944         return;
11945       }
11946 
11947       Inherited::VisitImplicitCastExpr(E);
11948     }
11949 
11950     void VisitMemberExpr(MemberExpr *E) {
11951       if (isInitList) {
11952         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11953           return;
11954       }
11955 
11956       // Don't warn on arrays since they can be treated as pointers.
11957       if (E->getType()->canDecayToPointerType()) return;
11958 
11959       // Warn when a non-static method call is followed by non-static member
11960       // field accesses, which is followed by a DeclRefExpr.
11961       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11962       bool Warn = (MD && !MD->isStatic());
11963       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11964       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11965         if (!isa<FieldDecl>(ME->getMemberDecl()))
11966           Warn = false;
11967         Base = ME->getBase()->IgnoreParenImpCasts();
11968       }
11969 
11970       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11971         if (Warn)
11972           HandleDeclRefExpr(DRE);
11973         return;
11974       }
11975 
11976       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11977       // Visit that expression.
11978       Visit(Base);
11979     }
11980 
11981     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11982       Expr *Callee = E->getCallee();
11983 
11984       if (isa<UnresolvedLookupExpr>(Callee))
11985         return Inherited::VisitCXXOperatorCallExpr(E);
11986 
11987       Visit(Callee);
11988       for (auto Arg: E->arguments())
11989         HandleValue(Arg->IgnoreParenImpCasts());
11990     }
11991 
11992     void VisitUnaryOperator(UnaryOperator *E) {
11993       // For POD record types, addresses of its own members are well-defined.
11994       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11995           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11996         if (!isPODType)
11997           HandleValue(E->getSubExpr());
11998         return;
11999       }
12000 
12001       if (E->isIncrementDecrementOp()) {
12002         HandleValue(E->getSubExpr());
12003         return;
12004       }
12005 
12006       Inherited::VisitUnaryOperator(E);
12007     }
12008 
12009     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12010 
12011     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12012       if (E->getConstructor()->isCopyConstructor()) {
12013         Expr *ArgExpr = E->getArg(0);
12014         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12015           if (ILE->getNumInits() == 1)
12016             ArgExpr = ILE->getInit(0);
12017         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12018           if (ICE->getCastKind() == CK_NoOp)
12019             ArgExpr = ICE->getSubExpr();
12020         HandleValue(ArgExpr);
12021         return;
12022       }
12023       Inherited::VisitCXXConstructExpr(E);
12024     }
12025 
12026     void VisitCallExpr(CallExpr *E) {
12027       // Treat std::move as a use.
12028       if (E->isCallToStdMove()) {
12029         HandleValue(E->getArg(0));
12030         return;
12031       }
12032 
12033       Inherited::VisitCallExpr(E);
12034     }
12035 
12036     void VisitBinaryOperator(BinaryOperator *E) {
12037       if (E->isCompoundAssignmentOp()) {
12038         HandleValue(E->getLHS());
12039         Visit(E->getRHS());
12040         return;
12041       }
12042 
12043       Inherited::VisitBinaryOperator(E);
12044     }
12045 
12046     // A custom visitor for BinaryConditionalOperator is needed because the
12047     // regular visitor would check the condition and true expression separately
12048     // but both point to the same place giving duplicate diagnostics.
12049     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12050       Visit(E->getCond());
12051       Visit(E->getFalseExpr());
12052     }
12053 
12054     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12055       Decl* ReferenceDecl = DRE->getDecl();
12056       if (OrigDecl != ReferenceDecl) return;
12057       unsigned diag;
12058       if (isReferenceType) {
12059         diag = diag::warn_uninit_self_reference_in_reference_init;
12060       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12061         diag = diag::warn_static_self_reference_in_init;
12062       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12063                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12064                  DRE->getDecl()->getType()->isRecordType()) {
12065         diag = diag::warn_uninit_self_reference_in_init;
12066       } else {
12067         // Local variables will be handled by the CFG analysis.
12068         return;
12069       }
12070 
12071       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12072                             S.PDiag(diag)
12073                                 << DRE->getDecl() << OrigDecl->getLocation()
12074                                 << DRE->getSourceRange());
12075     }
12076   };
12077 
12078   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12079   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12080                                  bool DirectInit) {
12081     // Parameters arguments are occassionially constructed with itself,
12082     // for instance, in recursive functions.  Skip them.
12083     if (isa<ParmVarDecl>(OrigDecl))
12084       return;
12085 
12086     E = E->IgnoreParens();
12087 
12088     // Skip checking T a = a where T is not a record or reference type.
12089     // Doing so is a way to silence uninitialized warnings.
12090     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12091       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12092         if (ICE->getCastKind() == CK_LValueToRValue)
12093           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12094             if (DRE->getDecl() == OrigDecl)
12095               return;
12096 
12097     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12098   }
12099 } // end anonymous namespace
12100 
12101 namespace {
12102   // Simple wrapper to add the name of a variable or (if no variable is
12103   // available) a DeclarationName into a diagnostic.
12104   struct VarDeclOrName {
12105     VarDecl *VDecl;
12106     DeclarationName Name;
12107 
12108     friend const Sema::SemaDiagnosticBuilder &
12109     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12110       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12111     }
12112   };
12113 } // end anonymous namespace
12114 
12115 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12116                                             DeclarationName Name, QualType Type,
12117                                             TypeSourceInfo *TSI,
12118                                             SourceRange Range, bool DirectInit,
12119                                             Expr *Init) {
12120   bool IsInitCapture = !VDecl;
12121   assert((!VDecl || !VDecl->isInitCapture()) &&
12122          "init captures are expected to be deduced prior to initialization");
12123 
12124   VarDeclOrName VN{VDecl, Name};
12125 
12126   DeducedType *Deduced = Type->getContainedDeducedType();
12127   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12128 
12129   // C++11 [dcl.spec.auto]p3
12130   if (!Init) {
12131     assert(VDecl && "no init for init capture deduction?");
12132 
12133     // Except for class argument deduction, and then for an initializing
12134     // declaration only, i.e. no static at class scope or extern.
12135     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12136         VDecl->hasExternalStorage() ||
12137         VDecl->isStaticDataMember()) {
12138       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12139         << VDecl->getDeclName() << Type;
12140       return QualType();
12141     }
12142   }
12143 
12144   ArrayRef<Expr*> DeduceInits;
12145   if (Init)
12146     DeduceInits = Init;
12147 
12148   if (DirectInit) {
12149     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12150       DeduceInits = PL->exprs();
12151   }
12152 
12153   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12154     assert(VDecl && "non-auto type for init capture deduction?");
12155     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12156     InitializationKind Kind = InitializationKind::CreateForInit(
12157         VDecl->getLocation(), DirectInit, Init);
12158     // FIXME: Initialization should not be taking a mutable list of inits.
12159     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12160     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12161                                                        InitsCopy);
12162   }
12163 
12164   if (DirectInit) {
12165     if (auto *IL = dyn_cast<InitListExpr>(Init))
12166       DeduceInits = IL->inits();
12167   }
12168 
12169   // Deduction only works if we have exactly one source expression.
12170   if (DeduceInits.empty()) {
12171     // It isn't possible to write this directly, but it is possible to
12172     // end up in this situation with "auto x(some_pack...);"
12173     Diag(Init->getBeginLoc(), IsInitCapture
12174                                   ? diag::err_init_capture_no_expression
12175                                   : diag::err_auto_var_init_no_expression)
12176         << VN << Type << Range;
12177     return QualType();
12178   }
12179 
12180   if (DeduceInits.size() > 1) {
12181     Diag(DeduceInits[1]->getBeginLoc(),
12182          IsInitCapture ? diag::err_init_capture_multiple_expressions
12183                        : diag::err_auto_var_init_multiple_expressions)
12184         << VN << Type << Range;
12185     return QualType();
12186   }
12187 
12188   Expr *DeduceInit = DeduceInits[0];
12189   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12190     Diag(Init->getBeginLoc(), IsInitCapture
12191                                   ? diag::err_init_capture_paren_braces
12192                                   : diag::err_auto_var_init_paren_braces)
12193         << isa<InitListExpr>(Init) << VN << Type << Range;
12194     return QualType();
12195   }
12196 
12197   // Expressions default to 'id' when we're in a debugger.
12198   bool DefaultedAnyToId = false;
12199   if (getLangOpts().DebuggerCastResultToId &&
12200       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12201     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12202     if (Result.isInvalid()) {
12203       return QualType();
12204     }
12205     Init = Result.get();
12206     DefaultedAnyToId = true;
12207   }
12208 
12209   // C++ [dcl.decomp]p1:
12210   //   If the assignment-expression [...] has array type A and no ref-qualifier
12211   //   is present, e has type cv A
12212   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12213       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12214       DeduceInit->getType()->isConstantArrayType())
12215     return Context.getQualifiedType(DeduceInit->getType(),
12216                                     Type.getQualifiers());
12217 
12218   QualType DeducedType;
12219   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12220     if (!IsInitCapture)
12221       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12222     else if (isa<InitListExpr>(Init))
12223       Diag(Range.getBegin(),
12224            diag::err_init_capture_deduction_failure_from_init_list)
12225           << VN
12226           << (DeduceInit->getType().isNull() ? TSI->getType()
12227                                              : DeduceInit->getType())
12228           << DeduceInit->getSourceRange();
12229     else
12230       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12231           << VN << TSI->getType()
12232           << (DeduceInit->getType().isNull() ? TSI->getType()
12233                                              : DeduceInit->getType())
12234           << DeduceInit->getSourceRange();
12235   }
12236 
12237   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12238   // 'id' instead of a specific object type prevents most of our usual
12239   // checks.
12240   // We only want to warn outside of template instantiations, though:
12241   // inside a template, the 'id' could have come from a parameter.
12242   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12243       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12244     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12245     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12246   }
12247 
12248   return DeducedType;
12249 }
12250 
12251 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12252                                          Expr *Init) {
12253   assert(!Init || !Init->containsErrors());
12254   QualType DeducedType = deduceVarTypeFromInitializer(
12255       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12256       VDecl->getSourceRange(), DirectInit, Init);
12257   if (DeducedType.isNull()) {
12258     VDecl->setInvalidDecl();
12259     return true;
12260   }
12261 
12262   VDecl->setType(DeducedType);
12263   assert(VDecl->isLinkageValid());
12264 
12265   // In ARC, infer lifetime.
12266   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12267     VDecl->setInvalidDecl();
12268 
12269   if (getLangOpts().OpenCL)
12270     deduceOpenCLAddressSpace(VDecl);
12271 
12272   // If this is a redeclaration, check that the type we just deduced matches
12273   // the previously declared type.
12274   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12275     // We never need to merge the type, because we cannot form an incomplete
12276     // array of auto, nor deduce such a type.
12277     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12278   }
12279 
12280   // Check the deduced type is valid for a variable declaration.
12281   CheckVariableDeclarationType(VDecl);
12282   return VDecl->isInvalidDecl();
12283 }
12284 
12285 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12286                                               SourceLocation Loc) {
12287   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12288     Init = EWC->getSubExpr();
12289 
12290   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12291     Init = CE->getSubExpr();
12292 
12293   QualType InitType = Init->getType();
12294   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12295           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12296          "shouldn't be called if type doesn't have a non-trivial C struct");
12297   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12298     for (auto I : ILE->inits()) {
12299       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12300           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12301         continue;
12302       SourceLocation SL = I->getExprLoc();
12303       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12304     }
12305     return;
12306   }
12307 
12308   if (isa<ImplicitValueInitExpr>(Init)) {
12309     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12310       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12311                             NTCUK_Init);
12312   } else {
12313     // Assume all other explicit initializers involving copying some existing
12314     // object.
12315     // TODO: ignore any explicit initializers where we can guarantee
12316     // copy-elision.
12317     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12318       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12319   }
12320 }
12321 
12322 namespace {
12323 
12324 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12325   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12326   // in the source code or implicitly by the compiler if it is in a union
12327   // defined in a system header and has non-trivial ObjC ownership
12328   // qualifications. We don't want those fields to participate in determining
12329   // whether the containing union is non-trivial.
12330   return FD->hasAttr<UnavailableAttr>();
12331 }
12332 
12333 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12334     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12335                                     void> {
12336   using Super =
12337       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12338                                     void>;
12339 
12340   DiagNonTrivalCUnionDefaultInitializeVisitor(
12341       QualType OrigTy, SourceLocation OrigLoc,
12342       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12343       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12344 
12345   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12346                      const FieldDecl *FD, bool InNonTrivialUnion) {
12347     if (const auto *AT = S.Context.getAsArrayType(QT))
12348       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12349                                      InNonTrivialUnion);
12350     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12351   }
12352 
12353   void visitARCStrong(QualType QT, const FieldDecl *FD,
12354                       bool InNonTrivialUnion) {
12355     if (InNonTrivialUnion)
12356       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12357           << 1 << 0 << QT << FD->getName();
12358   }
12359 
12360   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12361     if (InNonTrivialUnion)
12362       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12363           << 1 << 0 << QT << FD->getName();
12364   }
12365 
12366   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12367     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12368     if (RD->isUnion()) {
12369       if (OrigLoc.isValid()) {
12370         bool IsUnion = false;
12371         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12372           IsUnion = OrigRD->isUnion();
12373         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12374             << 0 << OrigTy << IsUnion << UseContext;
12375         // Reset OrigLoc so that this diagnostic is emitted only once.
12376         OrigLoc = SourceLocation();
12377       }
12378       InNonTrivialUnion = true;
12379     }
12380 
12381     if (InNonTrivialUnion)
12382       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12383           << 0 << 0 << QT.getUnqualifiedType() << "";
12384 
12385     for (const FieldDecl *FD : RD->fields())
12386       if (!shouldIgnoreForRecordTriviality(FD))
12387         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12388   }
12389 
12390   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12391 
12392   // The non-trivial C union type or the struct/union type that contains a
12393   // non-trivial C union.
12394   QualType OrigTy;
12395   SourceLocation OrigLoc;
12396   Sema::NonTrivialCUnionContext UseContext;
12397   Sema &S;
12398 };
12399 
12400 struct DiagNonTrivalCUnionDestructedTypeVisitor
12401     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12402   using Super =
12403       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12404 
12405   DiagNonTrivalCUnionDestructedTypeVisitor(
12406       QualType OrigTy, SourceLocation OrigLoc,
12407       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12408       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12409 
12410   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12411                      const FieldDecl *FD, bool InNonTrivialUnion) {
12412     if (const auto *AT = S.Context.getAsArrayType(QT))
12413       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12414                                      InNonTrivialUnion);
12415     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12416   }
12417 
12418   void visitARCStrong(QualType QT, const FieldDecl *FD,
12419                       bool InNonTrivialUnion) {
12420     if (InNonTrivialUnion)
12421       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12422           << 1 << 1 << QT << FD->getName();
12423   }
12424 
12425   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12426     if (InNonTrivialUnion)
12427       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12428           << 1 << 1 << QT << FD->getName();
12429   }
12430 
12431   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12432     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12433     if (RD->isUnion()) {
12434       if (OrigLoc.isValid()) {
12435         bool IsUnion = false;
12436         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12437           IsUnion = OrigRD->isUnion();
12438         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12439             << 1 << OrigTy << IsUnion << UseContext;
12440         // Reset OrigLoc so that this diagnostic is emitted only once.
12441         OrigLoc = SourceLocation();
12442       }
12443       InNonTrivialUnion = true;
12444     }
12445 
12446     if (InNonTrivialUnion)
12447       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12448           << 0 << 1 << QT.getUnqualifiedType() << "";
12449 
12450     for (const FieldDecl *FD : RD->fields())
12451       if (!shouldIgnoreForRecordTriviality(FD))
12452         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12453   }
12454 
12455   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12456   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12457                           bool InNonTrivialUnion) {}
12458 
12459   // The non-trivial C union type or the struct/union type that contains a
12460   // non-trivial C union.
12461   QualType OrigTy;
12462   SourceLocation OrigLoc;
12463   Sema::NonTrivialCUnionContext UseContext;
12464   Sema &S;
12465 };
12466 
12467 struct DiagNonTrivalCUnionCopyVisitor
12468     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12469   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12470 
12471   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12472                                  Sema::NonTrivialCUnionContext UseContext,
12473                                  Sema &S)
12474       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12475 
12476   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12477                      const FieldDecl *FD, bool InNonTrivialUnion) {
12478     if (const auto *AT = S.Context.getAsArrayType(QT))
12479       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12480                                      InNonTrivialUnion);
12481     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12482   }
12483 
12484   void visitARCStrong(QualType QT, const FieldDecl *FD,
12485                       bool InNonTrivialUnion) {
12486     if (InNonTrivialUnion)
12487       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12488           << 1 << 2 << QT << FD->getName();
12489   }
12490 
12491   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12492     if (InNonTrivialUnion)
12493       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12494           << 1 << 2 << QT << FD->getName();
12495   }
12496 
12497   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12498     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12499     if (RD->isUnion()) {
12500       if (OrigLoc.isValid()) {
12501         bool IsUnion = false;
12502         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12503           IsUnion = OrigRD->isUnion();
12504         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12505             << 2 << OrigTy << IsUnion << UseContext;
12506         // Reset OrigLoc so that this diagnostic is emitted only once.
12507         OrigLoc = SourceLocation();
12508       }
12509       InNonTrivialUnion = true;
12510     }
12511 
12512     if (InNonTrivialUnion)
12513       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12514           << 0 << 2 << QT.getUnqualifiedType() << "";
12515 
12516     for (const FieldDecl *FD : RD->fields())
12517       if (!shouldIgnoreForRecordTriviality(FD))
12518         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12519   }
12520 
12521   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12522                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12523   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12524   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12525                             bool InNonTrivialUnion) {}
12526 
12527   // The non-trivial C union type or the struct/union type that contains a
12528   // non-trivial C union.
12529   QualType OrigTy;
12530   SourceLocation OrigLoc;
12531   Sema::NonTrivialCUnionContext UseContext;
12532   Sema &S;
12533 };
12534 
12535 } // namespace
12536 
12537 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12538                                  NonTrivialCUnionContext UseContext,
12539                                  unsigned NonTrivialKind) {
12540   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12541           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12542           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12543          "shouldn't be called if type doesn't have a non-trivial C union");
12544 
12545   if ((NonTrivialKind & NTCUK_Init) &&
12546       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12547     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12548         .visit(QT, nullptr, false);
12549   if ((NonTrivialKind & NTCUK_Destruct) &&
12550       QT.hasNonTrivialToPrimitiveDestructCUnion())
12551     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12552         .visit(QT, nullptr, false);
12553   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12554     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12555         .visit(QT, nullptr, false);
12556 }
12557 
12558 /// AddInitializerToDecl - Adds the initializer Init to the
12559 /// declaration dcl. If DirectInit is true, this is C++ direct
12560 /// initialization rather than copy initialization.
12561 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12562   // If there is no declaration, there was an error parsing it.  Just ignore
12563   // the initializer.
12564   if (!RealDecl || RealDecl->isInvalidDecl()) {
12565     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12566     return;
12567   }
12568 
12569   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12570     // Pure-specifiers are handled in ActOnPureSpecifier.
12571     Diag(Method->getLocation(), diag::err_member_function_initialization)
12572       << Method->getDeclName() << Init->getSourceRange();
12573     Method->setInvalidDecl();
12574     return;
12575   }
12576 
12577   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12578   if (!VDecl) {
12579     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12580     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12581     RealDecl->setInvalidDecl();
12582     return;
12583   }
12584 
12585   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12586   if (VDecl->getType()->isUndeducedType()) {
12587     // Attempt typo correction early so that the type of the init expression can
12588     // be deduced based on the chosen correction if the original init contains a
12589     // TypoExpr.
12590     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12591     if (!Res.isUsable()) {
12592       // There are unresolved typos in Init, just drop them.
12593       // FIXME: improve the recovery strategy to preserve the Init.
12594       RealDecl->setInvalidDecl();
12595       return;
12596     }
12597     if (Res.get()->containsErrors()) {
12598       // Invalidate the decl as we don't know the type for recovery-expr yet.
12599       RealDecl->setInvalidDecl();
12600       VDecl->setInit(Res.get());
12601       return;
12602     }
12603     Init = Res.get();
12604 
12605     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12606       return;
12607   }
12608 
12609   // dllimport cannot be used on variable definitions.
12610   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12611     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12612     VDecl->setInvalidDecl();
12613     return;
12614   }
12615 
12616   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12617     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12618     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12619     VDecl->setInvalidDecl();
12620     return;
12621   }
12622 
12623   if (!VDecl->getType()->isDependentType()) {
12624     // A definition must end up with a complete type, which means it must be
12625     // complete with the restriction that an array type might be completed by
12626     // the initializer; note that later code assumes this restriction.
12627     QualType BaseDeclType = VDecl->getType();
12628     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12629       BaseDeclType = Array->getElementType();
12630     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12631                             diag::err_typecheck_decl_incomplete_type)) {
12632       RealDecl->setInvalidDecl();
12633       return;
12634     }
12635 
12636     // The variable can not have an abstract class type.
12637     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12638                                diag::err_abstract_type_in_decl,
12639                                AbstractVariableType))
12640       VDecl->setInvalidDecl();
12641   }
12642 
12643   // If adding the initializer will turn this declaration into a definition,
12644   // and we already have a definition for this variable, diagnose or otherwise
12645   // handle the situation.
12646   if (VarDecl *Def = VDecl->getDefinition())
12647     if (Def != VDecl &&
12648         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12649         !VDecl->isThisDeclarationADemotedDefinition() &&
12650         checkVarDeclRedefinition(Def, VDecl))
12651       return;
12652 
12653   if (getLangOpts().CPlusPlus) {
12654     // C++ [class.static.data]p4
12655     //   If a static data member is of const integral or const
12656     //   enumeration type, its declaration in the class definition can
12657     //   specify a constant-initializer which shall be an integral
12658     //   constant expression (5.19). In that case, the member can appear
12659     //   in integral constant expressions. The member shall still be
12660     //   defined in a namespace scope if it is used in the program and the
12661     //   namespace scope definition shall not contain an initializer.
12662     //
12663     // We already performed a redefinition check above, but for static
12664     // data members we also need to check whether there was an in-class
12665     // declaration with an initializer.
12666     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12667       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12668           << VDecl->getDeclName();
12669       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12670            diag::note_previous_initializer)
12671           << 0;
12672       return;
12673     }
12674 
12675     if (VDecl->hasLocalStorage())
12676       setFunctionHasBranchProtectedScope();
12677 
12678     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12679       VDecl->setInvalidDecl();
12680       return;
12681     }
12682   }
12683 
12684   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12685   // a kernel function cannot be initialized."
12686   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12687     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12688     VDecl->setInvalidDecl();
12689     return;
12690   }
12691 
12692   // The LoaderUninitialized attribute acts as a definition (of undef).
12693   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12694     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12695     VDecl->setInvalidDecl();
12696     return;
12697   }
12698 
12699   // Get the decls type and save a reference for later, since
12700   // CheckInitializerTypes may change it.
12701   QualType DclT = VDecl->getType(), SavT = DclT;
12702 
12703   // Expressions default to 'id' when we're in a debugger
12704   // and we are assigning it to a variable of Objective-C pointer type.
12705   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12706       Init->getType() == Context.UnknownAnyTy) {
12707     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12708     if (Result.isInvalid()) {
12709       VDecl->setInvalidDecl();
12710       return;
12711     }
12712     Init = Result.get();
12713   }
12714 
12715   // Perform the initialization.
12716   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12717   if (!VDecl->isInvalidDecl()) {
12718     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12719     InitializationKind Kind = InitializationKind::CreateForInit(
12720         VDecl->getLocation(), DirectInit, Init);
12721 
12722     MultiExprArg Args = Init;
12723     if (CXXDirectInit)
12724       Args = MultiExprArg(CXXDirectInit->getExprs(),
12725                           CXXDirectInit->getNumExprs());
12726 
12727     // Try to correct any TypoExprs in the initialization arguments.
12728     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12729       ExprResult Res = CorrectDelayedTyposInExpr(
12730           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12731           [this, Entity, Kind](Expr *E) {
12732             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12733             return Init.Failed() ? ExprError() : E;
12734           });
12735       if (Res.isInvalid()) {
12736         VDecl->setInvalidDecl();
12737       } else if (Res.get() != Args[Idx]) {
12738         Args[Idx] = Res.get();
12739       }
12740     }
12741     if (VDecl->isInvalidDecl())
12742       return;
12743 
12744     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12745                                    /*TopLevelOfInitList=*/false,
12746                                    /*TreatUnavailableAsInvalid=*/false);
12747     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12748     if (Result.isInvalid()) {
12749       // If the provided initializer fails to initialize the var decl,
12750       // we attach a recovery expr for better recovery.
12751       auto RecoveryExpr =
12752           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12753       if (RecoveryExpr.get())
12754         VDecl->setInit(RecoveryExpr.get());
12755       return;
12756     }
12757 
12758     Init = Result.getAs<Expr>();
12759   }
12760 
12761   // Check for self-references within variable initializers.
12762   // Variables declared within a function/method body (except for references)
12763   // are handled by a dataflow analysis.
12764   // This is undefined behavior in C++, but valid in C.
12765   if (getLangOpts().CPlusPlus)
12766     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12767         VDecl->getType()->isReferenceType())
12768       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12769 
12770   // If the type changed, it means we had an incomplete type that was
12771   // completed by the initializer. For example:
12772   //   int ary[] = { 1, 3, 5 };
12773   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12774   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12775     VDecl->setType(DclT);
12776 
12777   if (!VDecl->isInvalidDecl()) {
12778     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12779 
12780     if (VDecl->hasAttr<BlocksAttr>())
12781       checkRetainCycles(VDecl, Init);
12782 
12783     // It is safe to assign a weak reference into a strong variable.
12784     // Although this code can still have problems:
12785     //   id x = self.weakProp;
12786     //   id y = self.weakProp;
12787     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12788     // paths through the function. This should be revisited if
12789     // -Wrepeated-use-of-weak is made flow-sensitive.
12790     if (FunctionScopeInfo *FSI = getCurFunction())
12791       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12792            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12793           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12794                            Init->getBeginLoc()))
12795         FSI->markSafeWeakUse(Init);
12796   }
12797 
12798   // The initialization is usually a full-expression.
12799   //
12800   // FIXME: If this is a braced initialization of an aggregate, it is not
12801   // an expression, and each individual field initializer is a separate
12802   // full-expression. For instance, in:
12803   //
12804   //   struct Temp { ~Temp(); };
12805   //   struct S { S(Temp); };
12806   //   struct T { S a, b; } t = { Temp(), Temp() }
12807   //
12808   // we should destroy the first Temp before constructing the second.
12809   ExprResult Result =
12810       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12811                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12812   if (Result.isInvalid()) {
12813     VDecl->setInvalidDecl();
12814     return;
12815   }
12816   Init = Result.get();
12817 
12818   // Attach the initializer to the decl.
12819   VDecl->setInit(Init);
12820 
12821   if (VDecl->isLocalVarDecl()) {
12822     // Don't check the initializer if the declaration is malformed.
12823     if (VDecl->isInvalidDecl()) {
12824       // do nothing
12825 
12826     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12827     // This is true even in C++ for OpenCL.
12828     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12829       CheckForConstantInitializer(Init, DclT);
12830 
12831     // Otherwise, C++ does not restrict the initializer.
12832     } else if (getLangOpts().CPlusPlus) {
12833       // do nothing
12834 
12835     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12836     // static storage duration shall be constant expressions or string literals.
12837     } else if (VDecl->getStorageClass() == SC_Static) {
12838       CheckForConstantInitializer(Init, DclT);
12839 
12840     // C89 is stricter than C99 for aggregate initializers.
12841     // C89 6.5.7p3: All the expressions [...] in an initializer list
12842     // for an object that has aggregate or union type shall be
12843     // constant expressions.
12844     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12845                isa<InitListExpr>(Init)) {
12846       const Expr *Culprit;
12847       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12848         Diag(Culprit->getExprLoc(),
12849              diag::ext_aggregate_init_not_constant)
12850           << Culprit->getSourceRange();
12851       }
12852     }
12853 
12854     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12855       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12856         if (VDecl->hasLocalStorage())
12857           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12858   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12859              VDecl->getLexicalDeclContext()->isRecord()) {
12860     // This is an in-class initialization for a static data member, e.g.,
12861     //
12862     // struct S {
12863     //   static const int value = 17;
12864     // };
12865 
12866     // C++ [class.mem]p4:
12867     //   A member-declarator can contain a constant-initializer only
12868     //   if it declares a static member (9.4) of const integral or
12869     //   const enumeration type, see 9.4.2.
12870     //
12871     // C++11 [class.static.data]p3:
12872     //   If a non-volatile non-inline const static data member is of integral
12873     //   or enumeration type, its declaration in the class definition can
12874     //   specify a brace-or-equal-initializer in which every initializer-clause
12875     //   that is an assignment-expression is a constant expression. A static
12876     //   data member of literal type can be declared in the class definition
12877     //   with the constexpr specifier; if so, its declaration shall specify a
12878     //   brace-or-equal-initializer in which every initializer-clause that is
12879     //   an assignment-expression is a constant expression.
12880 
12881     // Do nothing on dependent types.
12882     if (DclT->isDependentType()) {
12883 
12884     // Allow any 'static constexpr' members, whether or not they are of literal
12885     // type. We separately check that every constexpr variable is of literal
12886     // type.
12887     } else if (VDecl->isConstexpr()) {
12888 
12889     // Require constness.
12890     } else if (!DclT.isConstQualified()) {
12891       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12892         << Init->getSourceRange();
12893       VDecl->setInvalidDecl();
12894 
12895     // We allow integer constant expressions in all cases.
12896     } else if (DclT->isIntegralOrEnumerationType()) {
12897       // Check whether the expression is a constant expression.
12898       SourceLocation Loc;
12899       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12900         // In C++11, a non-constexpr const static data member with an
12901         // in-class initializer cannot be volatile.
12902         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12903       else if (Init->isValueDependent())
12904         ; // Nothing to check.
12905       else if (Init->isIntegerConstantExpr(Context, &Loc))
12906         ; // Ok, it's an ICE!
12907       else if (Init->getType()->isScopedEnumeralType() &&
12908                Init->isCXX11ConstantExpr(Context))
12909         ; // Ok, it is a scoped-enum constant expression.
12910       else if (Init->isEvaluatable(Context)) {
12911         // If we can constant fold the initializer through heroics, accept it,
12912         // but report this as a use of an extension for -pedantic.
12913         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12914           << Init->getSourceRange();
12915       } else {
12916         // Otherwise, this is some crazy unknown case.  Report the issue at the
12917         // location provided by the isIntegerConstantExpr failed check.
12918         Diag(Loc, diag::err_in_class_initializer_non_constant)
12919           << Init->getSourceRange();
12920         VDecl->setInvalidDecl();
12921       }
12922 
12923     // We allow foldable floating-point constants as an extension.
12924     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12925       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12926       // it anyway and provide a fixit to add the 'constexpr'.
12927       if (getLangOpts().CPlusPlus11) {
12928         Diag(VDecl->getLocation(),
12929              diag::ext_in_class_initializer_float_type_cxx11)
12930             << DclT << Init->getSourceRange();
12931         Diag(VDecl->getBeginLoc(),
12932              diag::note_in_class_initializer_float_type_cxx11)
12933             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12934       } else {
12935         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12936           << DclT << Init->getSourceRange();
12937 
12938         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12939           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12940             << Init->getSourceRange();
12941           VDecl->setInvalidDecl();
12942         }
12943       }
12944 
12945     // Suggest adding 'constexpr' in C++11 for literal types.
12946     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12947       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12948           << DclT << Init->getSourceRange()
12949           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12950       VDecl->setConstexpr(true);
12951 
12952     } else {
12953       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12954         << DclT << Init->getSourceRange();
12955       VDecl->setInvalidDecl();
12956     }
12957   } else if (VDecl->isFileVarDecl()) {
12958     // In C, extern is typically used to avoid tentative definitions when
12959     // declaring variables in headers, but adding an intializer makes it a
12960     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12961     // In C++, extern is often used to give implictly static const variables
12962     // external linkage, so don't warn in that case. If selectany is present,
12963     // this might be header code intended for C and C++ inclusion, so apply the
12964     // C++ rules.
12965     if (VDecl->getStorageClass() == SC_Extern &&
12966         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12967          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12968         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12969         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12970       Diag(VDecl->getLocation(), diag::warn_extern_init);
12971 
12972     // In Microsoft C++ mode, a const variable defined in namespace scope has
12973     // external linkage by default if the variable is declared with
12974     // __declspec(dllexport).
12975     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12976         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12977         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12978       VDecl->setStorageClass(SC_Extern);
12979 
12980     // C99 6.7.8p4. All file scoped initializers need to be constant.
12981     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12982       CheckForConstantInitializer(Init, DclT);
12983   }
12984 
12985   QualType InitType = Init->getType();
12986   if (!InitType.isNull() &&
12987       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12988        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12989     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12990 
12991   // We will represent direct-initialization similarly to copy-initialization:
12992   //    int x(1);  -as-> int x = 1;
12993   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12994   //
12995   // Clients that want to distinguish between the two forms, can check for
12996   // direct initializer using VarDecl::getInitStyle().
12997   // A major benefit is that clients that don't particularly care about which
12998   // exactly form was it (like the CodeGen) can handle both cases without
12999   // special case code.
13000 
13001   // C++ 8.5p11:
13002   // The form of initialization (using parentheses or '=') is generally
13003   // insignificant, but does matter when the entity being initialized has a
13004   // class type.
13005   if (CXXDirectInit) {
13006     assert(DirectInit && "Call-style initializer must be direct init.");
13007     VDecl->setInitStyle(VarDecl::CallInit);
13008   } else if (DirectInit) {
13009     // This must be list-initialization. No other way is direct-initialization.
13010     VDecl->setInitStyle(VarDecl::ListInit);
13011   }
13012 
13013   if (LangOpts.OpenMP &&
13014       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13015       VDecl->isFileVarDecl())
13016     DeclsToCheckForDeferredDiags.insert(VDecl);
13017   CheckCompleteVariableDeclaration(VDecl);
13018 }
13019 
13020 /// ActOnInitializerError - Given that there was an error parsing an
13021 /// initializer for the given declaration, try to at least re-establish
13022 /// invariants such as whether a variable's type is either dependent or
13023 /// complete.
13024 void Sema::ActOnInitializerError(Decl *D) {
13025   // Our main concern here is re-establishing invariants like "a
13026   // variable's type is either dependent or complete".
13027   if (!D || D->isInvalidDecl()) return;
13028 
13029   VarDecl *VD = dyn_cast<VarDecl>(D);
13030   if (!VD) return;
13031 
13032   // Bindings are not usable if we can't make sense of the initializer.
13033   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13034     for (auto *BD : DD->bindings())
13035       BD->setInvalidDecl();
13036 
13037   // Auto types are meaningless if we can't make sense of the initializer.
13038   if (VD->getType()->isUndeducedType()) {
13039     D->setInvalidDecl();
13040     return;
13041   }
13042 
13043   QualType Ty = VD->getType();
13044   if (Ty->isDependentType()) return;
13045 
13046   // Require a complete type.
13047   if (RequireCompleteType(VD->getLocation(),
13048                           Context.getBaseElementType(Ty),
13049                           diag::err_typecheck_decl_incomplete_type)) {
13050     VD->setInvalidDecl();
13051     return;
13052   }
13053 
13054   // Require a non-abstract type.
13055   if (RequireNonAbstractType(VD->getLocation(), Ty,
13056                              diag::err_abstract_type_in_decl,
13057                              AbstractVariableType)) {
13058     VD->setInvalidDecl();
13059     return;
13060   }
13061 
13062   // Don't bother complaining about constructors or destructors,
13063   // though.
13064 }
13065 
13066 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13067   // If there is no declaration, there was an error parsing it. Just ignore it.
13068   if (!RealDecl)
13069     return;
13070 
13071   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13072     QualType Type = Var->getType();
13073 
13074     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13075     if (isa<DecompositionDecl>(RealDecl)) {
13076       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13077       Var->setInvalidDecl();
13078       return;
13079     }
13080 
13081     if (Type->isUndeducedType() &&
13082         DeduceVariableDeclarationType(Var, false, nullptr))
13083       return;
13084 
13085     // C++11 [class.static.data]p3: A static data member can be declared with
13086     // the constexpr specifier; if so, its declaration shall specify
13087     // a brace-or-equal-initializer.
13088     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13089     // the definition of a variable [...] or the declaration of a static data
13090     // member.
13091     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13092         !Var->isThisDeclarationADemotedDefinition()) {
13093       if (Var->isStaticDataMember()) {
13094         // C++1z removes the relevant rule; the in-class declaration is always
13095         // a definition there.
13096         if (!getLangOpts().CPlusPlus17 &&
13097             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13098           Diag(Var->getLocation(),
13099                diag::err_constexpr_static_mem_var_requires_init)
13100               << Var;
13101           Var->setInvalidDecl();
13102           return;
13103         }
13104       } else {
13105         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13106         Var->setInvalidDecl();
13107         return;
13108       }
13109     }
13110 
13111     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13112     // be initialized.
13113     if (!Var->isInvalidDecl() &&
13114         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13115         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13116       bool HasConstExprDefaultConstructor = false;
13117       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13118         for (auto *Ctor : RD->ctors()) {
13119           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13120               Ctor->getMethodQualifiers().getAddressSpace() ==
13121                   LangAS::opencl_constant) {
13122             HasConstExprDefaultConstructor = true;
13123           }
13124         }
13125       }
13126       if (!HasConstExprDefaultConstructor) {
13127         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13128         Var->setInvalidDecl();
13129         return;
13130       }
13131     }
13132 
13133     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13134       if (Var->getStorageClass() == SC_Extern) {
13135         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13136             << Var;
13137         Var->setInvalidDecl();
13138         return;
13139       }
13140       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13141                               diag::err_typecheck_decl_incomplete_type)) {
13142         Var->setInvalidDecl();
13143         return;
13144       }
13145       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13146         if (!RD->hasTrivialDefaultConstructor()) {
13147           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13148           Var->setInvalidDecl();
13149           return;
13150         }
13151       }
13152       // The declaration is unitialized, no need for further checks.
13153       return;
13154     }
13155 
13156     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13157     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13158         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13159       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13160                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13161 
13162 
13163     switch (DefKind) {
13164     case VarDecl::Definition:
13165       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13166         break;
13167 
13168       // We have an out-of-line definition of a static data member
13169       // that has an in-class initializer, so we type-check this like
13170       // a declaration.
13171       //
13172       LLVM_FALLTHROUGH;
13173 
13174     case VarDecl::DeclarationOnly:
13175       // It's only a declaration.
13176 
13177       // Block scope. C99 6.7p7: If an identifier for an object is
13178       // declared with no linkage (C99 6.2.2p6), the type for the
13179       // object shall be complete.
13180       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13181           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13182           RequireCompleteType(Var->getLocation(), Type,
13183                               diag::err_typecheck_decl_incomplete_type))
13184         Var->setInvalidDecl();
13185 
13186       // Make sure that the type is not abstract.
13187       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13188           RequireNonAbstractType(Var->getLocation(), Type,
13189                                  diag::err_abstract_type_in_decl,
13190                                  AbstractVariableType))
13191         Var->setInvalidDecl();
13192       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13193           Var->getStorageClass() == SC_PrivateExtern) {
13194         Diag(Var->getLocation(), diag::warn_private_extern);
13195         Diag(Var->getLocation(), diag::note_private_extern);
13196       }
13197 
13198       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13199           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13200         ExternalDeclarations.push_back(Var);
13201 
13202       return;
13203 
13204     case VarDecl::TentativeDefinition:
13205       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13206       // object that has file scope without an initializer, and without a
13207       // storage-class specifier or with the storage-class specifier "static",
13208       // constitutes a tentative definition. Note: A tentative definition with
13209       // external linkage is valid (C99 6.2.2p5).
13210       if (!Var->isInvalidDecl()) {
13211         if (const IncompleteArrayType *ArrayT
13212                                     = Context.getAsIncompleteArrayType(Type)) {
13213           if (RequireCompleteSizedType(
13214                   Var->getLocation(), ArrayT->getElementType(),
13215                   diag::err_array_incomplete_or_sizeless_type))
13216             Var->setInvalidDecl();
13217         } else if (Var->getStorageClass() == SC_Static) {
13218           // C99 6.9.2p3: If the declaration of an identifier for an object is
13219           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13220           // declared type shall not be an incomplete type.
13221           // NOTE: code such as the following
13222           //     static struct s;
13223           //     struct s { int a; };
13224           // is accepted by gcc. Hence here we issue a warning instead of
13225           // an error and we do not invalidate the static declaration.
13226           // NOTE: to avoid multiple warnings, only check the first declaration.
13227           if (Var->isFirstDecl())
13228             RequireCompleteType(Var->getLocation(), Type,
13229                                 diag::ext_typecheck_decl_incomplete_type);
13230         }
13231       }
13232 
13233       // Record the tentative definition; we're done.
13234       if (!Var->isInvalidDecl())
13235         TentativeDefinitions.push_back(Var);
13236       return;
13237     }
13238 
13239     // Provide a specific diagnostic for uninitialized variable
13240     // definitions with incomplete array type.
13241     if (Type->isIncompleteArrayType()) {
13242       Diag(Var->getLocation(),
13243            diag::err_typecheck_incomplete_array_needs_initializer);
13244       Var->setInvalidDecl();
13245       return;
13246     }
13247 
13248     // Provide a specific diagnostic for uninitialized variable
13249     // definitions with reference type.
13250     if (Type->isReferenceType()) {
13251       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13252           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13253       return;
13254     }
13255 
13256     // Do not attempt to type-check the default initializer for a
13257     // variable with dependent type.
13258     if (Type->isDependentType())
13259       return;
13260 
13261     if (Var->isInvalidDecl())
13262       return;
13263 
13264     if (!Var->hasAttr<AliasAttr>()) {
13265       if (RequireCompleteType(Var->getLocation(),
13266                               Context.getBaseElementType(Type),
13267                               diag::err_typecheck_decl_incomplete_type)) {
13268         Var->setInvalidDecl();
13269         return;
13270       }
13271     } else {
13272       return;
13273     }
13274 
13275     // The variable can not have an abstract class type.
13276     if (RequireNonAbstractType(Var->getLocation(), Type,
13277                                diag::err_abstract_type_in_decl,
13278                                AbstractVariableType)) {
13279       Var->setInvalidDecl();
13280       return;
13281     }
13282 
13283     // Check for jumps past the implicit initializer.  C++0x
13284     // clarifies that this applies to a "variable with automatic
13285     // storage duration", not a "local variable".
13286     // C++11 [stmt.dcl]p3
13287     //   A program that jumps from a point where a variable with automatic
13288     //   storage duration is not in scope to a point where it is in scope is
13289     //   ill-formed unless the variable has scalar type, class type with a
13290     //   trivial default constructor and a trivial destructor, a cv-qualified
13291     //   version of one of these types, or an array of one of the preceding
13292     //   types and is declared without an initializer.
13293     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13294       if (const RecordType *Record
13295             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13296         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13297         // Mark the function (if we're in one) for further checking even if the
13298         // looser rules of C++11 do not require such checks, so that we can
13299         // diagnose incompatibilities with C++98.
13300         if (!CXXRecord->isPOD())
13301           setFunctionHasBranchProtectedScope();
13302       }
13303     }
13304     // In OpenCL, we can't initialize objects in the __local address space,
13305     // even implicitly, so don't synthesize an implicit initializer.
13306     if (getLangOpts().OpenCL &&
13307         Var->getType().getAddressSpace() == LangAS::opencl_local)
13308       return;
13309     // C++03 [dcl.init]p9:
13310     //   If no initializer is specified for an object, and the
13311     //   object is of (possibly cv-qualified) non-POD class type (or
13312     //   array thereof), the object shall be default-initialized; if
13313     //   the object is of const-qualified type, the underlying class
13314     //   type shall have a user-declared default
13315     //   constructor. Otherwise, if no initializer is specified for
13316     //   a non- static object, the object and its subobjects, if
13317     //   any, have an indeterminate initial value); if the object
13318     //   or any of its subobjects are of const-qualified type, the
13319     //   program is ill-formed.
13320     // C++0x [dcl.init]p11:
13321     //   If no initializer is specified for an object, the object is
13322     //   default-initialized; [...].
13323     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13324     InitializationKind Kind
13325       = InitializationKind::CreateDefault(Var->getLocation());
13326 
13327     InitializationSequence InitSeq(*this, Entity, Kind, None);
13328     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13329 
13330     if (Init.get()) {
13331       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13332       // This is important for template substitution.
13333       Var->setInitStyle(VarDecl::CallInit);
13334     } else if (Init.isInvalid()) {
13335       // If default-init fails, attach a recovery-expr initializer to track
13336       // that initialization was attempted and failed.
13337       auto RecoveryExpr =
13338           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13339       if (RecoveryExpr.get())
13340         Var->setInit(RecoveryExpr.get());
13341     }
13342 
13343     CheckCompleteVariableDeclaration(Var);
13344   }
13345 }
13346 
13347 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13348   // If there is no declaration, there was an error parsing it. Ignore it.
13349   if (!D)
13350     return;
13351 
13352   VarDecl *VD = dyn_cast<VarDecl>(D);
13353   if (!VD) {
13354     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13355     D->setInvalidDecl();
13356     return;
13357   }
13358 
13359   VD->setCXXForRangeDecl(true);
13360 
13361   // for-range-declaration cannot be given a storage class specifier.
13362   int Error = -1;
13363   switch (VD->getStorageClass()) {
13364   case SC_None:
13365     break;
13366   case SC_Extern:
13367     Error = 0;
13368     break;
13369   case SC_Static:
13370     Error = 1;
13371     break;
13372   case SC_PrivateExtern:
13373     Error = 2;
13374     break;
13375   case SC_Auto:
13376     Error = 3;
13377     break;
13378   case SC_Register:
13379     Error = 4;
13380     break;
13381   }
13382 
13383   // for-range-declaration cannot be given a storage class specifier con't.
13384   switch (VD->getTSCSpec()) {
13385   case TSCS_thread_local:
13386     Error = 6;
13387     break;
13388   case TSCS___thread:
13389   case TSCS__Thread_local:
13390   case TSCS_unspecified:
13391     break;
13392   }
13393 
13394   if (Error != -1) {
13395     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13396         << VD << Error;
13397     D->setInvalidDecl();
13398   }
13399 }
13400 
13401 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13402                                             IdentifierInfo *Ident,
13403                                             ParsedAttributes &Attrs) {
13404   // C++1y [stmt.iter]p1:
13405   //   A range-based for statement of the form
13406   //      for ( for-range-identifier : for-range-initializer ) statement
13407   //   is equivalent to
13408   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13409   DeclSpec DS(Attrs.getPool().getFactory());
13410 
13411   const char *PrevSpec;
13412   unsigned DiagID;
13413   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13414                      getPrintingPolicy());
13415 
13416   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13417   D.SetIdentifier(Ident, IdentLoc);
13418   D.takeAttributes(Attrs);
13419 
13420   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13421                 IdentLoc);
13422   Decl *Var = ActOnDeclarator(S, D);
13423   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13424   FinalizeDeclaration(Var);
13425   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13426                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13427                                                       : IdentLoc);
13428 }
13429 
13430 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13431   if (var->isInvalidDecl()) return;
13432 
13433   MaybeAddCUDAConstantAttr(var);
13434 
13435   if (getLangOpts().OpenCL) {
13436     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13437     // initialiser
13438     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13439         !var->hasInit()) {
13440       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13441           << 1 /*Init*/;
13442       var->setInvalidDecl();
13443       return;
13444     }
13445   }
13446 
13447   // In Objective-C, don't allow jumps past the implicit initialization of a
13448   // local retaining variable.
13449   if (getLangOpts().ObjC &&
13450       var->hasLocalStorage()) {
13451     switch (var->getType().getObjCLifetime()) {
13452     case Qualifiers::OCL_None:
13453     case Qualifiers::OCL_ExplicitNone:
13454     case Qualifiers::OCL_Autoreleasing:
13455       break;
13456 
13457     case Qualifiers::OCL_Weak:
13458     case Qualifiers::OCL_Strong:
13459       setFunctionHasBranchProtectedScope();
13460       break;
13461     }
13462   }
13463 
13464   if (var->hasLocalStorage() &&
13465       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13466     setFunctionHasBranchProtectedScope();
13467 
13468   // Warn about externally-visible variables being defined without a
13469   // prior declaration.  We only want to do this for global
13470   // declarations, but we also specifically need to avoid doing it for
13471   // class members because the linkage of an anonymous class can
13472   // change if it's later given a typedef name.
13473   if (var->isThisDeclarationADefinition() &&
13474       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13475       var->isExternallyVisible() && var->hasLinkage() &&
13476       !var->isInline() && !var->getDescribedVarTemplate() &&
13477       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13478       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13479       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13480                                   var->getLocation())) {
13481     // Find a previous declaration that's not a definition.
13482     VarDecl *prev = var->getPreviousDecl();
13483     while (prev && prev->isThisDeclarationADefinition())
13484       prev = prev->getPreviousDecl();
13485 
13486     if (!prev) {
13487       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13488       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13489           << /* variable */ 0;
13490     }
13491   }
13492 
13493   // Cache the result of checking for constant initialization.
13494   Optional<bool> CacheHasConstInit;
13495   const Expr *CacheCulprit = nullptr;
13496   auto checkConstInit = [&]() mutable {
13497     if (!CacheHasConstInit)
13498       CacheHasConstInit = var->getInit()->isConstantInitializer(
13499             Context, var->getType()->isReferenceType(), &CacheCulprit);
13500     return *CacheHasConstInit;
13501   };
13502 
13503   if (var->getTLSKind() == VarDecl::TLS_Static) {
13504     if (var->getType().isDestructedType()) {
13505       // GNU C++98 edits for __thread, [basic.start.term]p3:
13506       //   The type of an object with thread storage duration shall not
13507       //   have a non-trivial destructor.
13508       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13509       if (getLangOpts().CPlusPlus11)
13510         Diag(var->getLocation(), diag::note_use_thread_local);
13511     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13512       if (!checkConstInit()) {
13513         // GNU C++98 edits for __thread, [basic.start.init]p4:
13514         //   An object of thread storage duration shall not require dynamic
13515         //   initialization.
13516         // FIXME: Need strict checking here.
13517         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13518           << CacheCulprit->getSourceRange();
13519         if (getLangOpts().CPlusPlus11)
13520           Diag(var->getLocation(), diag::note_use_thread_local);
13521       }
13522     }
13523   }
13524 
13525 
13526   if (!var->getType()->isStructureType() && var->hasInit() &&
13527       isa<InitListExpr>(var->getInit())) {
13528     const auto *ILE = cast<InitListExpr>(var->getInit());
13529     unsigned NumInits = ILE->getNumInits();
13530     if (NumInits > 2)
13531       for (unsigned I = 0; I < NumInits; ++I) {
13532         const auto *Init = ILE->getInit(I);
13533         if (!Init)
13534           break;
13535         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13536         if (!SL)
13537           break;
13538 
13539         unsigned NumConcat = SL->getNumConcatenated();
13540         // Diagnose missing comma in string array initialization.
13541         // Do not warn when all the elements in the initializer are concatenated
13542         // together. Do not warn for macros too.
13543         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13544           bool OnlyOneMissingComma = true;
13545           for (unsigned J = I + 1; J < NumInits; ++J) {
13546             const auto *Init = ILE->getInit(J);
13547             if (!Init)
13548               break;
13549             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13550             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13551               OnlyOneMissingComma = false;
13552               break;
13553             }
13554           }
13555 
13556           if (OnlyOneMissingComma) {
13557             SmallVector<FixItHint, 1> Hints;
13558             for (unsigned i = 0; i < NumConcat - 1; ++i)
13559               Hints.push_back(FixItHint::CreateInsertion(
13560                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13561 
13562             Diag(SL->getStrTokenLoc(1),
13563                  diag::warn_concatenated_literal_array_init)
13564                 << Hints;
13565             Diag(SL->getBeginLoc(),
13566                  diag::note_concatenated_string_literal_silence);
13567           }
13568           // In any case, stop now.
13569           break;
13570         }
13571       }
13572   }
13573 
13574 
13575   QualType type = var->getType();
13576 
13577   if (var->hasAttr<BlocksAttr>())
13578     getCurFunction()->addByrefBlockVar(var);
13579 
13580   Expr *Init = var->getInit();
13581   bool GlobalStorage = var->hasGlobalStorage();
13582   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13583   QualType baseType = Context.getBaseElementType(type);
13584   bool HasConstInit = true;
13585 
13586   // Check whether the initializer is sufficiently constant.
13587   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13588       !Init->isValueDependent() &&
13589       (GlobalStorage || var->isConstexpr() ||
13590        var->mightBeUsableInConstantExpressions(Context))) {
13591     // If this variable might have a constant initializer or might be usable in
13592     // constant expressions, check whether or not it actually is now.  We can't
13593     // do this lazily, because the result might depend on things that change
13594     // later, such as which constexpr functions happen to be defined.
13595     SmallVector<PartialDiagnosticAt, 8> Notes;
13596     if (!getLangOpts().CPlusPlus11) {
13597       // Prior to C++11, in contexts where a constant initializer is required,
13598       // the set of valid constant initializers is described by syntactic rules
13599       // in [expr.const]p2-6.
13600       // FIXME: Stricter checking for these rules would be useful for constinit /
13601       // -Wglobal-constructors.
13602       HasConstInit = checkConstInit();
13603 
13604       // Compute and cache the constant value, and remember that we have a
13605       // constant initializer.
13606       if (HasConstInit) {
13607         (void)var->checkForConstantInitialization(Notes);
13608         Notes.clear();
13609       } else if (CacheCulprit) {
13610         Notes.emplace_back(CacheCulprit->getExprLoc(),
13611                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13612         Notes.back().second << CacheCulprit->getSourceRange();
13613       }
13614     } else {
13615       // Evaluate the initializer to see if it's a constant initializer.
13616       HasConstInit = var->checkForConstantInitialization(Notes);
13617     }
13618 
13619     if (HasConstInit) {
13620       // FIXME: Consider replacing the initializer with a ConstantExpr.
13621     } else if (var->isConstexpr()) {
13622       SourceLocation DiagLoc = var->getLocation();
13623       // If the note doesn't add any useful information other than a source
13624       // location, fold it into the primary diagnostic.
13625       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13626                                    diag::note_invalid_subexpr_in_const_expr) {
13627         DiagLoc = Notes[0].first;
13628         Notes.clear();
13629       }
13630       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13631           << var << Init->getSourceRange();
13632       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13633         Diag(Notes[I].first, Notes[I].second);
13634     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13635       auto *Attr = var->getAttr<ConstInitAttr>();
13636       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13637           << Init->getSourceRange();
13638       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13639           << Attr->getRange() << Attr->isConstinit();
13640       for (auto &it : Notes)
13641         Diag(it.first, it.second);
13642     } else if (IsGlobal &&
13643                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13644                                            var->getLocation())) {
13645       // Warn about globals which don't have a constant initializer.  Don't
13646       // warn about globals with a non-trivial destructor because we already
13647       // warned about them.
13648       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13649       if (!(RD && !RD->hasTrivialDestructor())) {
13650         // checkConstInit() here permits trivial default initialization even in
13651         // C++11 onwards, where such an initializer is not a constant initializer
13652         // but nonetheless doesn't require a global constructor.
13653         if (!checkConstInit())
13654           Diag(var->getLocation(), diag::warn_global_constructor)
13655               << Init->getSourceRange();
13656       }
13657     }
13658   }
13659 
13660   // Apply section attributes and pragmas to global variables.
13661   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13662       !inTemplateInstantiation()) {
13663     PragmaStack<StringLiteral *> *Stack = nullptr;
13664     int SectionFlags = ASTContext::PSF_Read;
13665     if (var->getType().isConstQualified()) {
13666       if (HasConstInit)
13667         Stack = &ConstSegStack;
13668       else {
13669         Stack = &BSSSegStack;
13670         SectionFlags |= ASTContext::PSF_Write;
13671       }
13672     } else if (var->hasInit() && HasConstInit) {
13673       Stack = &DataSegStack;
13674       SectionFlags |= ASTContext::PSF_Write;
13675     } else {
13676       Stack = &BSSSegStack;
13677       SectionFlags |= ASTContext::PSF_Write;
13678     }
13679     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13680       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13681         SectionFlags |= ASTContext::PSF_Implicit;
13682       UnifySection(SA->getName(), SectionFlags, var);
13683     } else if (Stack->CurrentValue) {
13684       SectionFlags |= ASTContext::PSF_Implicit;
13685       auto SectionName = Stack->CurrentValue->getString();
13686       var->addAttr(SectionAttr::CreateImplicit(
13687           Context, SectionName, Stack->CurrentPragmaLocation,
13688           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13689       if (UnifySection(SectionName, SectionFlags, var))
13690         var->dropAttr<SectionAttr>();
13691     }
13692 
13693     // Apply the init_seg attribute if this has an initializer.  If the
13694     // initializer turns out to not be dynamic, we'll end up ignoring this
13695     // attribute.
13696     if (CurInitSeg && var->getInit())
13697       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13698                                                CurInitSegLoc,
13699                                                AttributeCommonInfo::AS_Pragma));
13700   }
13701 
13702   // All the following checks are C++ only.
13703   if (!getLangOpts().CPlusPlus) {
13704     // If this variable must be emitted, add it as an initializer for the
13705     // current module.
13706     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13707       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13708     return;
13709   }
13710 
13711   // Require the destructor.
13712   if (!type->isDependentType())
13713     if (const RecordType *recordType = baseType->getAs<RecordType>())
13714       FinalizeVarWithDestructor(var, recordType);
13715 
13716   // If this variable must be emitted, add it as an initializer for the current
13717   // module.
13718   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13719     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13720 
13721   // Build the bindings if this is a structured binding declaration.
13722   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13723     CheckCompleteDecompositionDeclaration(DD);
13724 }
13725 
13726 /// Check if VD needs to be dllexport/dllimport due to being in a
13727 /// dllexport/import function.
13728 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13729   assert(VD->isStaticLocal());
13730 
13731   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13732 
13733   // Find outermost function when VD is in lambda function.
13734   while (FD && !getDLLAttr(FD) &&
13735          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13736          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13737     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13738   }
13739 
13740   if (!FD)
13741     return;
13742 
13743   // Static locals inherit dll attributes from their function.
13744   if (Attr *A = getDLLAttr(FD)) {
13745     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13746     NewAttr->setInherited(true);
13747     VD->addAttr(NewAttr);
13748   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13749     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13750     NewAttr->setInherited(true);
13751     VD->addAttr(NewAttr);
13752 
13753     // Export this function to enforce exporting this static variable even
13754     // if it is not used in this compilation unit.
13755     if (!FD->hasAttr<DLLExportAttr>())
13756       FD->addAttr(NewAttr);
13757 
13758   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13759     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13760     NewAttr->setInherited(true);
13761     VD->addAttr(NewAttr);
13762   }
13763 }
13764 
13765 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13766 /// any semantic actions necessary after any initializer has been attached.
13767 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13768   // Note that we are no longer parsing the initializer for this declaration.
13769   ParsingInitForAutoVars.erase(ThisDecl);
13770 
13771   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13772   if (!VD)
13773     return;
13774 
13775   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13776   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13777       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13778     if (PragmaClangBSSSection.Valid)
13779       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13780           Context, PragmaClangBSSSection.SectionName,
13781           PragmaClangBSSSection.PragmaLocation,
13782           AttributeCommonInfo::AS_Pragma));
13783     if (PragmaClangDataSection.Valid)
13784       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13785           Context, PragmaClangDataSection.SectionName,
13786           PragmaClangDataSection.PragmaLocation,
13787           AttributeCommonInfo::AS_Pragma));
13788     if (PragmaClangRodataSection.Valid)
13789       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13790           Context, PragmaClangRodataSection.SectionName,
13791           PragmaClangRodataSection.PragmaLocation,
13792           AttributeCommonInfo::AS_Pragma));
13793     if (PragmaClangRelroSection.Valid)
13794       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13795           Context, PragmaClangRelroSection.SectionName,
13796           PragmaClangRelroSection.PragmaLocation,
13797           AttributeCommonInfo::AS_Pragma));
13798   }
13799 
13800   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13801     for (auto *BD : DD->bindings()) {
13802       FinalizeDeclaration(BD);
13803     }
13804   }
13805 
13806   checkAttributesAfterMerging(*this, *VD);
13807 
13808   // Perform TLS alignment check here after attributes attached to the variable
13809   // which may affect the alignment have been processed. Only perform the check
13810   // if the target has a maximum TLS alignment (zero means no constraints).
13811   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13812     // Protect the check so that it's not performed on dependent types and
13813     // dependent alignments (we can't determine the alignment in that case).
13814     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13815       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13816       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13817         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13818           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13819           << (unsigned)MaxAlignChars.getQuantity();
13820       }
13821     }
13822   }
13823 
13824   if (VD->isStaticLocal())
13825     CheckStaticLocalForDllExport(VD);
13826 
13827   // Perform check for initializers of device-side global variables.
13828   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13829   // 7.5). We must also apply the same checks to all __shared__
13830   // variables whether they are local or not. CUDA also allows
13831   // constant initializers for __constant__ and __device__ variables.
13832   if (getLangOpts().CUDA)
13833     checkAllowedCUDAInitializer(VD);
13834 
13835   // Grab the dllimport or dllexport attribute off of the VarDecl.
13836   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13837 
13838   // Imported static data members cannot be defined out-of-line.
13839   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13840     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13841         VD->isThisDeclarationADefinition()) {
13842       // We allow definitions of dllimport class template static data members
13843       // with a warning.
13844       CXXRecordDecl *Context =
13845         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13846       bool IsClassTemplateMember =
13847           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13848           Context->getDescribedClassTemplate();
13849 
13850       Diag(VD->getLocation(),
13851            IsClassTemplateMember
13852                ? diag::warn_attribute_dllimport_static_field_definition
13853                : diag::err_attribute_dllimport_static_field_definition);
13854       Diag(IA->getLocation(), diag::note_attribute);
13855       if (!IsClassTemplateMember)
13856         VD->setInvalidDecl();
13857     }
13858   }
13859 
13860   // dllimport/dllexport variables cannot be thread local, their TLS index
13861   // isn't exported with the variable.
13862   if (DLLAttr && VD->getTLSKind()) {
13863     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13864     if (F && getDLLAttr(F)) {
13865       assert(VD->isStaticLocal());
13866       // But if this is a static local in a dlimport/dllexport function, the
13867       // function will never be inlined, which means the var would never be
13868       // imported, so having it marked import/export is safe.
13869     } else {
13870       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13871                                                                     << DLLAttr;
13872       VD->setInvalidDecl();
13873     }
13874   }
13875 
13876   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13877     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13878       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13879           << Attr;
13880       VD->dropAttr<UsedAttr>();
13881     }
13882   }
13883   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13884     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13885       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13886           << Attr;
13887       VD->dropAttr<RetainAttr>();
13888     }
13889   }
13890 
13891   const DeclContext *DC = VD->getDeclContext();
13892   // If there's a #pragma GCC visibility in scope, and this isn't a class
13893   // member, set the visibility of this variable.
13894   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13895     AddPushedVisibilityAttribute(VD);
13896 
13897   // FIXME: Warn on unused var template partial specializations.
13898   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13899     MarkUnusedFileScopedDecl(VD);
13900 
13901   // Now we have parsed the initializer and can update the table of magic
13902   // tag values.
13903   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13904       !VD->getType()->isIntegralOrEnumerationType())
13905     return;
13906 
13907   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13908     const Expr *MagicValueExpr = VD->getInit();
13909     if (!MagicValueExpr) {
13910       continue;
13911     }
13912     Optional<llvm::APSInt> MagicValueInt;
13913     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13914       Diag(I->getRange().getBegin(),
13915            diag::err_type_tag_for_datatype_not_ice)
13916         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13917       continue;
13918     }
13919     if (MagicValueInt->getActiveBits() > 64) {
13920       Diag(I->getRange().getBegin(),
13921            diag::err_type_tag_for_datatype_too_large)
13922         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13923       continue;
13924     }
13925     uint64_t MagicValue = MagicValueInt->getZExtValue();
13926     RegisterTypeTagForDatatype(I->getArgumentKind(),
13927                                MagicValue,
13928                                I->getMatchingCType(),
13929                                I->getLayoutCompatible(),
13930                                I->getMustBeNull());
13931   }
13932 }
13933 
13934 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13935   auto *VD = dyn_cast<VarDecl>(DD);
13936   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13937 }
13938 
13939 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13940                                                    ArrayRef<Decl *> Group) {
13941   SmallVector<Decl*, 8> Decls;
13942 
13943   if (DS.isTypeSpecOwned())
13944     Decls.push_back(DS.getRepAsDecl());
13945 
13946   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13947   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13948   bool DiagnosedMultipleDecomps = false;
13949   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13950   bool DiagnosedNonDeducedAuto = false;
13951 
13952   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13953     if (Decl *D = Group[i]) {
13954       // For declarators, there are some additional syntactic-ish checks we need
13955       // to perform.
13956       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13957         if (!FirstDeclaratorInGroup)
13958           FirstDeclaratorInGroup = DD;
13959         if (!FirstDecompDeclaratorInGroup)
13960           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13961         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13962             !hasDeducedAuto(DD))
13963           FirstNonDeducedAutoInGroup = DD;
13964 
13965         if (FirstDeclaratorInGroup != DD) {
13966           // A decomposition declaration cannot be combined with any other
13967           // declaration in the same group.
13968           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13969             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13970                  diag::err_decomp_decl_not_alone)
13971                 << FirstDeclaratorInGroup->getSourceRange()
13972                 << DD->getSourceRange();
13973             DiagnosedMultipleDecomps = true;
13974           }
13975 
13976           // A declarator that uses 'auto' in any way other than to declare a
13977           // variable with a deduced type cannot be combined with any other
13978           // declarator in the same group.
13979           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13980             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13981                  diag::err_auto_non_deduced_not_alone)
13982                 << FirstNonDeducedAutoInGroup->getType()
13983                        ->hasAutoForTrailingReturnType()
13984                 << FirstDeclaratorInGroup->getSourceRange()
13985                 << DD->getSourceRange();
13986             DiagnosedNonDeducedAuto = true;
13987           }
13988         }
13989       }
13990 
13991       Decls.push_back(D);
13992     }
13993   }
13994 
13995   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13996     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13997       handleTagNumbering(Tag, S);
13998       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13999           getLangOpts().CPlusPlus)
14000         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14001     }
14002   }
14003 
14004   return BuildDeclaratorGroup(Decls);
14005 }
14006 
14007 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14008 /// group, performing any necessary semantic checking.
14009 Sema::DeclGroupPtrTy
14010 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14011   // C++14 [dcl.spec.auto]p7: (DR1347)
14012   //   If the type that replaces the placeholder type is not the same in each
14013   //   deduction, the program is ill-formed.
14014   if (Group.size() > 1) {
14015     QualType Deduced;
14016     VarDecl *DeducedDecl = nullptr;
14017     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14018       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14019       if (!D || D->isInvalidDecl())
14020         break;
14021       DeducedType *DT = D->getType()->getContainedDeducedType();
14022       if (!DT || DT->getDeducedType().isNull())
14023         continue;
14024       if (Deduced.isNull()) {
14025         Deduced = DT->getDeducedType();
14026         DeducedDecl = D;
14027       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14028         auto *AT = dyn_cast<AutoType>(DT);
14029         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14030                         diag::err_auto_different_deductions)
14031                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14032                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14033                    << D->getDeclName();
14034         if (DeducedDecl->hasInit())
14035           Dia << DeducedDecl->getInit()->getSourceRange();
14036         if (D->getInit())
14037           Dia << D->getInit()->getSourceRange();
14038         D->setInvalidDecl();
14039         break;
14040       }
14041     }
14042   }
14043 
14044   ActOnDocumentableDecls(Group);
14045 
14046   return DeclGroupPtrTy::make(
14047       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14048 }
14049 
14050 void Sema::ActOnDocumentableDecl(Decl *D) {
14051   ActOnDocumentableDecls(D);
14052 }
14053 
14054 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14055   // Don't parse the comment if Doxygen diagnostics are ignored.
14056   if (Group.empty() || !Group[0])
14057     return;
14058 
14059   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14060                       Group[0]->getLocation()) &&
14061       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14062                       Group[0]->getLocation()))
14063     return;
14064 
14065   if (Group.size() >= 2) {
14066     // This is a decl group.  Normally it will contain only declarations
14067     // produced from declarator list.  But in case we have any definitions or
14068     // additional declaration references:
14069     //   'typedef struct S {} S;'
14070     //   'typedef struct S *S;'
14071     //   'struct S *pS;'
14072     // FinalizeDeclaratorGroup adds these as separate declarations.
14073     Decl *MaybeTagDecl = Group[0];
14074     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14075       Group = Group.slice(1);
14076     }
14077   }
14078 
14079   // FIMXE: We assume every Decl in the group is in the same file.
14080   // This is false when preprocessor constructs the group from decls in
14081   // different files (e. g. macros or #include).
14082   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14083 }
14084 
14085 /// Common checks for a parameter-declaration that should apply to both function
14086 /// parameters and non-type template parameters.
14087 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14088   // Check that there are no default arguments inside the type of this
14089   // parameter.
14090   if (getLangOpts().CPlusPlus)
14091     CheckExtraCXXDefaultArguments(D);
14092 
14093   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14094   if (D.getCXXScopeSpec().isSet()) {
14095     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14096       << D.getCXXScopeSpec().getRange();
14097   }
14098 
14099   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14100   // simple identifier except [...irrelevant cases...].
14101   switch (D.getName().getKind()) {
14102   case UnqualifiedIdKind::IK_Identifier:
14103     break;
14104 
14105   case UnqualifiedIdKind::IK_OperatorFunctionId:
14106   case UnqualifiedIdKind::IK_ConversionFunctionId:
14107   case UnqualifiedIdKind::IK_LiteralOperatorId:
14108   case UnqualifiedIdKind::IK_ConstructorName:
14109   case UnqualifiedIdKind::IK_DestructorName:
14110   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14111   case UnqualifiedIdKind::IK_DeductionGuideName:
14112     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14113       << GetNameForDeclarator(D).getName();
14114     break;
14115 
14116   case UnqualifiedIdKind::IK_TemplateId:
14117   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14118     // GetNameForDeclarator would not produce a useful name in this case.
14119     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14120     break;
14121   }
14122 }
14123 
14124 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14125 /// to introduce parameters into function prototype scope.
14126 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14127   const DeclSpec &DS = D.getDeclSpec();
14128 
14129   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14130 
14131   // C++03 [dcl.stc]p2 also permits 'auto'.
14132   StorageClass SC = SC_None;
14133   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14134     SC = SC_Register;
14135     // In C++11, the 'register' storage class specifier is deprecated.
14136     // In C++17, it is not allowed, but we tolerate it as an extension.
14137     if (getLangOpts().CPlusPlus11) {
14138       Diag(DS.getStorageClassSpecLoc(),
14139            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14140                                      : diag::warn_deprecated_register)
14141         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14142     }
14143   } else if (getLangOpts().CPlusPlus &&
14144              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14145     SC = SC_Auto;
14146   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14147     Diag(DS.getStorageClassSpecLoc(),
14148          diag::err_invalid_storage_class_in_func_decl);
14149     D.getMutableDeclSpec().ClearStorageClassSpecs();
14150   }
14151 
14152   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14153     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14154       << DeclSpec::getSpecifierName(TSCS);
14155   if (DS.isInlineSpecified())
14156     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14157         << getLangOpts().CPlusPlus17;
14158   if (DS.hasConstexprSpecifier())
14159     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14160         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14161 
14162   DiagnoseFunctionSpecifiers(DS);
14163 
14164   CheckFunctionOrTemplateParamDeclarator(S, D);
14165 
14166   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14167   QualType parmDeclType = TInfo->getType();
14168 
14169   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14170   IdentifierInfo *II = D.getIdentifier();
14171   if (II) {
14172     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14173                    ForVisibleRedeclaration);
14174     LookupName(R, S);
14175     if (R.isSingleResult()) {
14176       NamedDecl *PrevDecl = R.getFoundDecl();
14177       if (PrevDecl->isTemplateParameter()) {
14178         // Maybe we will complain about the shadowed template parameter.
14179         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14180         // Just pretend that we didn't see the previous declaration.
14181         PrevDecl = nullptr;
14182       } else if (S->isDeclScope(PrevDecl)) {
14183         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14184         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14185 
14186         // Recover by removing the name
14187         II = nullptr;
14188         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14189         D.setInvalidType(true);
14190       }
14191     }
14192   }
14193 
14194   // Temporarily put parameter variables in the translation unit, not
14195   // the enclosing context.  This prevents them from accidentally
14196   // looking like class members in C++.
14197   ParmVarDecl *New =
14198       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14199                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14200 
14201   if (D.isInvalidType())
14202     New->setInvalidDecl();
14203 
14204   assert(S->isFunctionPrototypeScope());
14205   assert(S->getFunctionPrototypeDepth() >= 1);
14206   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14207                     S->getNextFunctionPrototypeIndex());
14208 
14209   // Add the parameter declaration into this scope.
14210   S->AddDecl(New);
14211   if (II)
14212     IdResolver.AddDecl(New);
14213 
14214   ProcessDeclAttributes(S, New, D);
14215 
14216   if (D.getDeclSpec().isModulePrivateSpecified())
14217     Diag(New->getLocation(), diag::err_module_private_local)
14218         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14219         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14220 
14221   if (New->hasAttr<BlocksAttr>()) {
14222     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14223   }
14224 
14225   if (getLangOpts().OpenCL)
14226     deduceOpenCLAddressSpace(New);
14227 
14228   return New;
14229 }
14230 
14231 /// Synthesizes a variable for a parameter arising from a
14232 /// typedef.
14233 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14234                                               SourceLocation Loc,
14235                                               QualType T) {
14236   /* FIXME: setting StartLoc == Loc.
14237      Would it be worth to modify callers so as to provide proper source
14238      location for the unnamed parameters, embedding the parameter's type? */
14239   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14240                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14241                                            SC_None, nullptr);
14242   Param->setImplicit();
14243   return Param;
14244 }
14245 
14246 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14247   // Don't diagnose unused-parameter errors in template instantiations; we
14248   // will already have done so in the template itself.
14249   if (inTemplateInstantiation())
14250     return;
14251 
14252   for (const ParmVarDecl *Parameter : Parameters) {
14253     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14254         !Parameter->hasAttr<UnusedAttr>()) {
14255       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14256         << Parameter->getDeclName();
14257     }
14258   }
14259 }
14260 
14261 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14262     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14263   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14264     return;
14265 
14266   // Warn if the return value is pass-by-value and larger than the specified
14267   // threshold.
14268   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14269     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14270     if (Size > LangOpts.NumLargeByValueCopy)
14271       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14272   }
14273 
14274   // Warn if any parameter is pass-by-value and larger than the specified
14275   // threshold.
14276   for (const ParmVarDecl *Parameter : Parameters) {
14277     QualType T = Parameter->getType();
14278     if (T->isDependentType() || !T.isPODType(Context))
14279       continue;
14280     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14281     if (Size > LangOpts.NumLargeByValueCopy)
14282       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14283           << Parameter << Size;
14284   }
14285 }
14286 
14287 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14288                                   SourceLocation NameLoc, IdentifierInfo *Name,
14289                                   QualType T, TypeSourceInfo *TSInfo,
14290                                   StorageClass SC) {
14291   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14292   if (getLangOpts().ObjCAutoRefCount &&
14293       T.getObjCLifetime() == Qualifiers::OCL_None &&
14294       T->isObjCLifetimeType()) {
14295 
14296     Qualifiers::ObjCLifetime lifetime;
14297 
14298     // Special cases for arrays:
14299     //   - if it's const, use __unsafe_unretained
14300     //   - otherwise, it's an error
14301     if (T->isArrayType()) {
14302       if (!T.isConstQualified()) {
14303         if (DelayedDiagnostics.shouldDelayDiagnostics())
14304           DelayedDiagnostics.add(
14305               sema::DelayedDiagnostic::makeForbiddenType(
14306               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14307         else
14308           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14309               << TSInfo->getTypeLoc().getSourceRange();
14310       }
14311       lifetime = Qualifiers::OCL_ExplicitNone;
14312     } else {
14313       lifetime = T->getObjCARCImplicitLifetime();
14314     }
14315     T = Context.getLifetimeQualifiedType(T, lifetime);
14316   }
14317 
14318   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14319                                          Context.getAdjustedParameterType(T),
14320                                          TSInfo, SC, nullptr);
14321 
14322   // Make a note if we created a new pack in the scope of a lambda, so that
14323   // we know that references to that pack must also be expanded within the
14324   // lambda scope.
14325   if (New->isParameterPack())
14326     if (auto *LSI = getEnclosingLambda())
14327       LSI->LocalPacks.push_back(New);
14328 
14329   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14330       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14331     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14332                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14333 
14334   // Parameters can not be abstract class types.
14335   // For record types, this is done by the AbstractClassUsageDiagnoser once
14336   // the class has been completely parsed.
14337   if (!CurContext->isRecord() &&
14338       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14339                              AbstractParamType))
14340     New->setInvalidDecl();
14341 
14342   // Parameter declarators cannot be interface types. All ObjC objects are
14343   // passed by reference.
14344   if (T->isObjCObjectType()) {
14345     SourceLocation TypeEndLoc =
14346         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14347     Diag(NameLoc,
14348          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14349       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14350     T = Context.getObjCObjectPointerType(T);
14351     New->setType(T);
14352   }
14353 
14354   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14355   // duration shall not be qualified by an address-space qualifier."
14356   // Since all parameters have automatic store duration, they can not have
14357   // an address space.
14358   if (T.getAddressSpace() != LangAS::Default &&
14359       // OpenCL allows function arguments declared to be an array of a type
14360       // to be qualified with an address space.
14361       !(getLangOpts().OpenCL &&
14362         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14363     Diag(NameLoc, diag::err_arg_with_address_space);
14364     New->setInvalidDecl();
14365   }
14366 
14367   // PPC MMA non-pointer types are not allowed as function argument types.
14368   if (Context.getTargetInfo().getTriple().isPPC64() &&
14369       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14370     New->setInvalidDecl();
14371   }
14372 
14373   return New;
14374 }
14375 
14376 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14377                                            SourceLocation LocAfterDecls) {
14378   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14379 
14380   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14381   // in the declaration list shall have at least one declarator, those
14382   // declarators shall only declare identifiers from the identifier list, and
14383   // every identifier in the identifier list shall be declared.
14384   //
14385   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14386   // identifiers it names shall be declared in the declaration list."
14387   //
14388   // This is why we only diagnose in C99 and later. Note, the other conditions
14389   // listed are checked elsewhere.
14390   if (!FTI.hasPrototype) {
14391     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14392       --i;
14393       if (FTI.Params[i].Param == nullptr) {
14394         if (getLangOpts().C99) {
14395           SmallString<256> Code;
14396           llvm::raw_svector_ostream(Code)
14397               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14398           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14399               << FTI.Params[i].Ident
14400               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14401         }
14402 
14403         // Implicitly declare the argument as type 'int' for lack of a better
14404         // type.
14405         AttributeFactory attrs;
14406         DeclSpec DS(attrs);
14407         const char* PrevSpec; // unused
14408         unsigned DiagID; // unused
14409         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14410                            DiagID, Context.getPrintingPolicy());
14411         // Use the identifier location for the type source range.
14412         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14413         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14414         Declarator ParamD(DS, ParsedAttributesView::none(),
14415                           DeclaratorContext::KNRTypeList);
14416         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14417         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14418       }
14419     }
14420   }
14421 }
14422 
14423 Decl *
14424 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14425                               MultiTemplateParamsArg TemplateParameterLists,
14426                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14427   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14428   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14429   Scope *ParentScope = FnBodyScope->getParent();
14430 
14431   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14432   // we define a non-templated function definition, we will create a declaration
14433   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14434   // The base function declaration will have the equivalent of an `omp declare
14435   // variant` annotation which specifies the mangled definition as a
14436   // specialization function under the OpenMP context defined as part of the
14437   // `omp begin declare variant`.
14438   SmallVector<FunctionDecl *, 4> Bases;
14439   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14440     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14441         ParentScope, D, TemplateParameterLists, Bases);
14442 
14443   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14444   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14445   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14446 
14447   if (!Bases.empty())
14448     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14449 
14450   return Dcl;
14451 }
14452 
14453 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14454   Consumer.HandleInlineFunctionDefinition(D);
14455 }
14456 
14457 static bool
14458 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14459                                 const FunctionDecl *&PossiblePrototype) {
14460   // Don't warn about invalid declarations.
14461   if (FD->isInvalidDecl())
14462     return false;
14463 
14464   // Or declarations that aren't global.
14465   if (!FD->isGlobal())
14466     return false;
14467 
14468   // Don't warn about C++ member functions.
14469   if (isa<CXXMethodDecl>(FD))
14470     return false;
14471 
14472   // Don't warn about 'main'.
14473   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14474     if (IdentifierInfo *II = FD->getIdentifier())
14475       if (II->isStr("main") || II->isStr("efi_main"))
14476         return false;
14477 
14478   // Don't warn about inline functions.
14479   if (FD->isInlined())
14480     return false;
14481 
14482   // Don't warn about function templates.
14483   if (FD->getDescribedFunctionTemplate())
14484     return false;
14485 
14486   // Don't warn about function template specializations.
14487   if (FD->isFunctionTemplateSpecialization())
14488     return false;
14489 
14490   // Don't warn for OpenCL kernels.
14491   if (FD->hasAttr<OpenCLKernelAttr>())
14492     return false;
14493 
14494   // Don't warn on explicitly deleted functions.
14495   if (FD->isDeleted())
14496     return false;
14497 
14498   // Don't warn on implicitly local functions (such as having local-typed
14499   // parameters).
14500   if (!FD->isExternallyVisible())
14501     return false;
14502 
14503   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14504        Prev; Prev = Prev->getPreviousDecl()) {
14505     // Ignore any declarations that occur in function or method
14506     // scope, because they aren't visible from the header.
14507     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14508       continue;
14509 
14510     PossiblePrototype = Prev;
14511     return Prev->getType()->isFunctionNoProtoType();
14512   }
14513 
14514   return true;
14515 }
14516 
14517 void
14518 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14519                                    const FunctionDecl *EffectiveDefinition,
14520                                    SkipBodyInfo *SkipBody) {
14521   const FunctionDecl *Definition = EffectiveDefinition;
14522   if (!Definition &&
14523       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14524     return;
14525 
14526   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14527     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14528       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14529         // A merged copy of the same function, instantiated as a member of
14530         // the same class, is OK.
14531         if (declaresSameEntity(OrigFD, OrigDef) &&
14532             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14533                                cast<Decl>(FD->getLexicalDeclContext())))
14534           return;
14535       }
14536     }
14537   }
14538 
14539   if (canRedefineFunction(Definition, getLangOpts()))
14540     return;
14541 
14542   // Don't emit an error when this is redefinition of a typo-corrected
14543   // definition.
14544   if (TypoCorrectedFunctionDefinitions.count(Definition))
14545     return;
14546 
14547   // If we don't have a visible definition of the function, and it's inline or
14548   // a template, skip the new definition.
14549   if (SkipBody && !hasVisibleDefinition(Definition) &&
14550       (Definition->getFormalLinkage() == InternalLinkage ||
14551        Definition->isInlined() ||
14552        Definition->getDescribedFunctionTemplate() ||
14553        Definition->getNumTemplateParameterLists())) {
14554     SkipBody->ShouldSkip = true;
14555     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14556     if (auto *TD = Definition->getDescribedFunctionTemplate())
14557       makeMergedDefinitionVisible(TD);
14558     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14559     return;
14560   }
14561 
14562   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14563       Definition->getStorageClass() == SC_Extern)
14564     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14565         << FD << getLangOpts().CPlusPlus;
14566   else
14567     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14568 
14569   Diag(Definition->getLocation(), diag::note_previous_definition);
14570   FD->setInvalidDecl();
14571 }
14572 
14573 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14574                                    Sema &S) {
14575   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14576 
14577   LambdaScopeInfo *LSI = S.PushLambdaScope();
14578   LSI->CallOperator = CallOperator;
14579   LSI->Lambda = LambdaClass;
14580   LSI->ReturnType = CallOperator->getReturnType();
14581   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14582 
14583   if (LCD == LCD_None)
14584     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14585   else if (LCD == LCD_ByCopy)
14586     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14587   else if (LCD == LCD_ByRef)
14588     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14589   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14590 
14591   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14592   LSI->Mutable = !CallOperator->isConst();
14593 
14594   // Add the captures to the LSI so they can be noted as already
14595   // captured within tryCaptureVar.
14596   auto I = LambdaClass->field_begin();
14597   for (const auto &C : LambdaClass->captures()) {
14598     if (C.capturesVariable()) {
14599       VarDecl *VD = C.getCapturedVar();
14600       if (VD->isInitCapture())
14601         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14602       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14603       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14604           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14605           /*EllipsisLoc*/C.isPackExpansion()
14606                          ? C.getEllipsisLoc() : SourceLocation(),
14607           I->getType(), /*Invalid*/false);
14608 
14609     } else if (C.capturesThis()) {
14610       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14611                           C.getCaptureKind() == LCK_StarThis);
14612     } else {
14613       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14614                              I->getType());
14615     }
14616     ++I;
14617   }
14618 }
14619 
14620 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14621                                     SkipBodyInfo *SkipBody,
14622                                     FnBodyKind BodyKind) {
14623   if (!D) {
14624     // Parsing the function declaration failed in some way. Push on a fake scope
14625     // anyway so we can try to parse the function body.
14626     PushFunctionScope();
14627     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14628     return D;
14629   }
14630 
14631   FunctionDecl *FD = nullptr;
14632 
14633   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14634     FD = FunTmpl->getTemplatedDecl();
14635   else
14636     FD = cast<FunctionDecl>(D);
14637 
14638   // Do not push if it is a lambda because one is already pushed when building
14639   // the lambda in ActOnStartOfLambdaDefinition().
14640   if (!isLambdaCallOperator(FD))
14641     PushExpressionEvaluationContext(
14642         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14643                           : ExprEvalContexts.back().Context);
14644 
14645   // Check for defining attributes before the check for redefinition.
14646   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14647     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14648     FD->dropAttr<AliasAttr>();
14649     FD->setInvalidDecl();
14650   }
14651   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14652     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14653     FD->dropAttr<IFuncAttr>();
14654     FD->setInvalidDecl();
14655   }
14656 
14657   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14658     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14659         Ctor->isDefaultConstructor() &&
14660         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14661       // If this is an MS ABI dllexport default constructor, instantiate any
14662       // default arguments.
14663       InstantiateDefaultCtorDefaultArgs(Ctor);
14664     }
14665   }
14666 
14667   // See if this is a redefinition. If 'will have body' (or similar) is already
14668   // set, then these checks were already performed when it was set.
14669   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14670       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14671     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14672 
14673     // If we're skipping the body, we're done. Don't enter the scope.
14674     if (SkipBody && SkipBody->ShouldSkip)
14675       return D;
14676   }
14677 
14678   // Mark this function as "will have a body eventually".  This lets users to
14679   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14680   // this function.
14681   FD->setWillHaveBody();
14682 
14683   // If we are instantiating a generic lambda call operator, push
14684   // a LambdaScopeInfo onto the function stack.  But use the information
14685   // that's already been calculated (ActOnLambdaExpr) to prime the current
14686   // LambdaScopeInfo.
14687   // When the template operator is being specialized, the LambdaScopeInfo,
14688   // has to be properly restored so that tryCaptureVariable doesn't try
14689   // and capture any new variables. In addition when calculating potential
14690   // captures during transformation of nested lambdas, it is necessary to
14691   // have the LSI properly restored.
14692   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14693     assert(inTemplateInstantiation() &&
14694            "There should be an active template instantiation on the stack "
14695            "when instantiating a generic lambda!");
14696     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14697   } else {
14698     // Enter a new function scope
14699     PushFunctionScope();
14700   }
14701 
14702   // Builtin functions cannot be defined.
14703   if (unsigned BuiltinID = FD->getBuiltinID()) {
14704     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14705         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14706       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14707       FD->setInvalidDecl();
14708     }
14709   }
14710 
14711   // The return type of a function definition must be complete (C99 6.9.1p3),
14712   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14713   QualType ResultType = FD->getReturnType();
14714   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14715       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14716       RequireCompleteType(FD->getLocation(), ResultType,
14717                           diag::err_func_def_incomplete_result))
14718     FD->setInvalidDecl();
14719 
14720   if (FnBodyScope)
14721     PushDeclContext(FnBodyScope, FD);
14722 
14723   // Check the validity of our function parameters
14724   if (BodyKind != FnBodyKind::Delete)
14725     CheckParmsForFunctionDef(FD->parameters(),
14726                              /*CheckParameterNames=*/true);
14727 
14728   // Add non-parameter declarations already in the function to the current
14729   // scope.
14730   if (FnBodyScope) {
14731     for (Decl *NPD : FD->decls()) {
14732       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14733       if (!NonParmDecl)
14734         continue;
14735       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14736              "parameters should not be in newly created FD yet");
14737 
14738       // If the decl has a name, make it accessible in the current scope.
14739       if (NonParmDecl->getDeclName())
14740         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14741 
14742       // Similarly, dive into enums and fish their constants out, making them
14743       // accessible in this scope.
14744       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14745         for (auto *EI : ED->enumerators())
14746           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14747       }
14748     }
14749   }
14750 
14751   // Introduce our parameters into the function scope
14752   for (auto Param : FD->parameters()) {
14753     Param->setOwningFunction(FD);
14754 
14755     // If this has an identifier, add it to the scope stack.
14756     if (Param->getIdentifier() && FnBodyScope) {
14757       CheckShadow(FnBodyScope, Param);
14758 
14759       PushOnScopeChains(Param, FnBodyScope);
14760     }
14761   }
14762 
14763   // Ensure that the function's exception specification is instantiated.
14764   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14765     ResolveExceptionSpec(D->getLocation(), FPT);
14766 
14767   // dllimport cannot be applied to non-inline function definitions.
14768   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14769       !FD->isTemplateInstantiation()) {
14770     assert(!FD->hasAttr<DLLExportAttr>());
14771     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14772     FD->setInvalidDecl();
14773     return D;
14774   }
14775   // We want to attach documentation to original Decl (which might be
14776   // a function template).
14777   ActOnDocumentableDecl(D);
14778   if (getCurLexicalContext()->isObjCContainer() &&
14779       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14780       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14781     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14782 
14783   return D;
14784 }
14785 
14786 /// Given the set of return statements within a function body,
14787 /// compute the variables that are subject to the named return value
14788 /// optimization.
14789 ///
14790 /// Each of the variables that is subject to the named return value
14791 /// optimization will be marked as NRVO variables in the AST, and any
14792 /// return statement that has a marked NRVO variable as its NRVO candidate can
14793 /// use the named return value optimization.
14794 ///
14795 /// This function applies a very simplistic algorithm for NRVO: if every return
14796 /// statement in the scope of a variable has the same NRVO candidate, that
14797 /// candidate is an NRVO variable.
14798 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14799   ReturnStmt **Returns = Scope->Returns.data();
14800 
14801   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14802     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14803       if (!NRVOCandidate->isNRVOVariable())
14804         Returns[I]->setNRVOCandidate(nullptr);
14805     }
14806   }
14807 }
14808 
14809 bool Sema::canDelayFunctionBody(const Declarator &D) {
14810   // We can't delay parsing the body of a constexpr function template (yet).
14811   if (D.getDeclSpec().hasConstexprSpecifier())
14812     return false;
14813 
14814   // We can't delay parsing the body of a function template with a deduced
14815   // return type (yet).
14816   if (D.getDeclSpec().hasAutoTypeSpec()) {
14817     // If the placeholder introduces a non-deduced trailing return type,
14818     // we can still delay parsing it.
14819     if (D.getNumTypeObjects()) {
14820       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14821       if (Outer.Kind == DeclaratorChunk::Function &&
14822           Outer.Fun.hasTrailingReturnType()) {
14823         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14824         return Ty.isNull() || !Ty->isUndeducedType();
14825       }
14826     }
14827     return false;
14828   }
14829 
14830   return true;
14831 }
14832 
14833 bool Sema::canSkipFunctionBody(Decl *D) {
14834   // We cannot skip the body of a function (or function template) which is
14835   // constexpr, since we may need to evaluate its body in order to parse the
14836   // rest of the file.
14837   // We cannot skip the body of a function with an undeduced return type,
14838   // because any callers of that function need to know the type.
14839   if (const FunctionDecl *FD = D->getAsFunction()) {
14840     if (FD->isConstexpr())
14841       return false;
14842     // We can't simply call Type::isUndeducedType here, because inside template
14843     // auto can be deduced to a dependent type, which is not considered
14844     // "undeduced".
14845     if (FD->getReturnType()->getContainedDeducedType())
14846       return false;
14847   }
14848   return Consumer.shouldSkipFunctionBody(D);
14849 }
14850 
14851 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14852   if (!Decl)
14853     return nullptr;
14854   if (FunctionDecl *FD = Decl->getAsFunction())
14855     FD->setHasSkippedBody();
14856   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14857     MD->setHasSkippedBody();
14858   return Decl;
14859 }
14860 
14861 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14862   return ActOnFinishFunctionBody(D, BodyArg, false);
14863 }
14864 
14865 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14866 /// body.
14867 class ExitFunctionBodyRAII {
14868 public:
14869   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14870   ~ExitFunctionBodyRAII() {
14871     if (!IsLambda)
14872       S.PopExpressionEvaluationContext();
14873   }
14874 
14875 private:
14876   Sema &S;
14877   bool IsLambda = false;
14878 };
14879 
14880 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14881   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14882 
14883   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14884     if (EscapeInfo.count(BD))
14885       return EscapeInfo[BD];
14886 
14887     bool R = false;
14888     const BlockDecl *CurBD = BD;
14889 
14890     do {
14891       R = !CurBD->doesNotEscape();
14892       if (R)
14893         break;
14894       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14895     } while (CurBD);
14896 
14897     return EscapeInfo[BD] = R;
14898   };
14899 
14900   // If the location where 'self' is implicitly retained is inside a escaping
14901   // block, emit a diagnostic.
14902   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14903        S.ImplicitlyRetainedSelfLocs)
14904     if (IsOrNestedInEscapingBlock(P.second))
14905       S.Diag(P.first, diag::warn_implicitly_retains_self)
14906           << FixItHint::CreateInsertion(P.first, "self->");
14907 }
14908 
14909 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14910                                     bool IsInstantiation) {
14911   FunctionScopeInfo *FSI = getCurFunction();
14912   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14913 
14914   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14915     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14916 
14917   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14918   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14919 
14920   if (getLangOpts().Coroutines && FSI->isCoroutine())
14921     CheckCompletedCoroutineBody(FD, Body);
14922 
14923   {
14924     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14925     // one is already popped when finishing the lambda in BuildLambdaExpr().
14926     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14927     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14928 
14929     if (FD) {
14930       FD->setBody(Body);
14931       FD->setWillHaveBody(false);
14932 
14933       if (getLangOpts().CPlusPlus14) {
14934         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14935             FD->getReturnType()->isUndeducedType()) {
14936           // For a function with a deduced result type to return void,
14937           // the result type as written must be 'auto' or 'decltype(auto)',
14938           // possibly cv-qualified or constrained, but not ref-qualified.
14939           if (!FD->getReturnType()->getAs<AutoType>()) {
14940             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14941                 << FD->getReturnType();
14942             FD->setInvalidDecl();
14943           } else {
14944             // Falling off the end of the function is the same as 'return;'.
14945             Expr *Dummy = nullptr;
14946             if (DeduceFunctionTypeFromReturnExpr(
14947                     FD, dcl->getLocation(), Dummy,
14948                     FD->getReturnType()->getAs<AutoType>()))
14949               FD->setInvalidDecl();
14950           }
14951         }
14952       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14953         // In C++11, we don't use 'auto' deduction rules for lambda call
14954         // operators because we don't support return type deduction.
14955         auto *LSI = getCurLambda();
14956         if (LSI->HasImplicitReturnType) {
14957           deduceClosureReturnType(*LSI);
14958 
14959           // C++11 [expr.prim.lambda]p4:
14960           //   [...] if there are no return statements in the compound-statement
14961           //   [the deduced type is] the type void
14962           QualType RetType =
14963               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14964 
14965           // Update the return type to the deduced type.
14966           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14967           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14968                                               Proto->getExtProtoInfo()));
14969         }
14970       }
14971 
14972       // If the function implicitly returns zero (like 'main') or is naked,
14973       // don't complain about missing return statements.
14974       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14975         WP.disableCheckFallThrough();
14976 
14977       // MSVC permits the use of pure specifier (=0) on function definition,
14978       // defined at class scope, warn about this non-standard construct.
14979       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14980         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14981 
14982       if (!FD->isInvalidDecl()) {
14983         // Don't diagnose unused parameters of defaulted, deleted or naked
14984         // functions.
14985         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14986             !FD->hasAttr<NakedAttr>())
14987           DiagnoseUnusedParameters(FD->parameters());
14988         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14989                                                FD->getReturnType(), FD);
14990 
14991         // If this is a structor, we need a vtable.
14992         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14993           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14994         else if (CXXDestructorDecl *Destructor =
14995                      dyn_cast<CXXDestructorDecl>(FD))
14996           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14997 
14998         // Try to apply the named return value optimization. We have to check
14999         // if we can do this here because lambdas keep return statements around
15000         // to deduce an implicit return type.
15001         if (FD->getReturnType()->isRecordType() &&
15002             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15003           computeNRVO(Body, FSI);
15004       }
15005 
15006       // GNU warning -Wmissing-prototypes:
15007       //   Warn if a global function is defined without a previous
15008       //   prototype declaration. This warning is issued even if the
15009       //   definition itself provides a prototype. The aim is to detect
15010       //   global functions that fail to be declared in header files.
15011       const FunctionDecl *PossiblePrototype = nullptr;
15012       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15013         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15014 
15015         if (PossiblePrototype) {
15016           // We found a declaration that is not a prototype,
15017           // but that could be a zero-parameter prototype
15018           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15019             TypeLoc TL = TI->getTypeLoc();
15020             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15021               Diag(PossiblePrototype->getLocation(),
15022                    diag::note_declaration_not_a_prototype)
15023                   << (FD->getNumParams() != 0)
15024                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15025                                                     FTL.getRParenLoc(), "void")
15026                                               : FixItHint{});
15027           }
15028         } else {
15029           // Returns true if the token beginning at this Loc is `const`.
15030           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15031                                   const LangOptions &LangOpts) {
15032             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15033             if (LocInfo.first.isInvalid())
15034               return false;
15035 
15036             bool Invalid = false;
15037             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15038             if (Invalid)
15039               return false;
15040 
15041             if (LocInfo.second > Buffer.size())
15042               return false;
15043 
15044             const char *LexStart = Buffer.data() + LocInfo.second;
15045             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15046 
15047             return StartTok.consume_front("const") &&
15048                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15049                     StartTok.startswith("/*") || StartTok.startswith("//"));
15050           };
15051 
15052           auto findBeginLoc = [&]() {
15053             // If the return type has `const` qualifier, we want to insert
15054             // `static` before `const` (and not before the typename).
15055             if ((FD->getReturnType()->isAnyPointerType() &&
15056                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15057                 FD->getReturnType().isConstQualified()) {
15058               // But only do this if we can determine where the `const` is.
15059 
15060               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15061                                getLangOpts()))
15062 
15063                 return FD->getBeginLoc();
15064             }
15065             return FD->getTypeSpecStartLoc();
15066           };
15067           Diag(FD->getTypeSpecStartLoc(),
15068                diag::note_static_for_internal_linkage)
15069               << /* function */ 1
15070               << (FD->getStorageClass() == SC_None
15071                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15072                       : FixItHint{});
15073         }
15074       }
15075 
15076       // If the function being defined does not have a prototype, then we may
15077       // need to diagnose it as changing behavior in C2x because we now know
15078       // whether the function accepts arguments or not. This only handles the
15079       // case where the definition has no prototype but does have parameters
15080       // and either there is no previous potential prototype, or the previous
15081       // potential prototype also has no actual prototype. This handles cases
15082       // like:
15083       //   void f(); void f(a) int a; {}
15084       //   void g(a) int a; {}
15085       // See MergeFunctionDecl() for other cases of the behavior change
15086       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15087       // type without a prototype.
15088       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15089           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15090                                   !PossiblePrototype->isImplicit()))) {
15091         // The function definition has parameters, so this will change behavior
15092         // in C2x. If there is a possible prototype, it comes before the
15093         // function definition.
15094         // FIXME: The declaration may have already been diagnosed as being
15095         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15096         // there's no way to test for the "changes behavior" condition in
15097         // SemaType.cpp when forming the declaration's function type. So, we do
15098         // this awkward dance instead.
15099         //
15100         // If we have a possible prototype and it declares a function with a
15101         // prototype, we don't want to diagnose it; if we have a possible
15102         // prototype and it has no prototype, it may have already been
15103         // diagnosed in SemaType.cpp as deprecated depending on whether
15104         // -Wstrict-prototypes is enabled. If we already warned about it being
15105         // deprecated, add a note that it also changes behavior. If we didn't
15106         // warn about it being deprecated (because the diagnostic is not
15107         // enabled), warn now that it is deprecated and changes behavior.
15108 
15109         // This K&R C function definition definitely changes behavior in C2x,
15110         // so diagnose it.
15111         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15112             << /*definition*/ 1 << /* not supported in C2x */ 0;
15113 
15114         // If we have a possible prototype for the function which is a user-
15115         // visible declaration, we already tested that it has no prototype.
15116         // This will change behavior in C2x. This gets a warning rather than a
15117         // note because it's the same behavior-changing problem as with the
15118         // definition.
15119         if (PossiblePrototype)
15120           Diag(PossiblePrototype->getLocation(),
15121                diag::warn_non_prototype_changes_behavior)
15122               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15123               << /*definition*/ 1;
15124       }
15125 
15126       // Warn on CPUDispatch with an actual body.
15127       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15128         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15129           if (!CmpndBody->body_empty())
15130             Diag(CmpndBody->body_front()->getBeginLoc(),
15131                  diag::warn_dispatch_body_ignored);
15132 
15133       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15134         const CXXMethodDecl *KeyFunction;
15135         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15136             MD->isVirtual() &&
15137             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15138             MD == KeyFunction->getCanonicalDecl()) {
15139           // Update the key-function state if necessary for this ABI.
15140           if (FD->isInlined() &&
15141               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15142             Context.setNonKeyFunction(MD);
15143 
15144             // If the newly-chosen key function is already defined, then we
15145             // need to mark the vtable as used retroactively.
15146             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15147             const FunctionDecl *Definition;
15148             if (KeyFunction && KeyFunction->isDefined(Definition))
15149               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15150           } else {
15151             // We just defined they key function; mark the vtable as used.
15152             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15153           }
15154         }
15155       }
15156 
15157       assert(
15158           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15159           "Function parsing confused");
15160     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15161       assert(MD == getCurMethodDecl() && "Method parsing confused");
15162       MD->setBody(Body);
15163       if (!MD->isInvalidDecl()) {
15164         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15165                                                MD->getReturnType(), MD);
15166 
15167         if (Body)
15168           computeNRVO(Body, FSI);
15169       }
15170       if (FSI->ObjCShouldCallSuper) {
15171         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15172             << MD->getSelector().getAsString();
15173         FSI->ObjCShouldCallSuper = false;
15174       }
15175       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15176         const ObjCMethodDecl *InitMethod = nullptr;
15177         bool isDesignated =
15178             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15179         assert(isDesignated && InitMethod);
15180         (void)isDesignated;
15181 
15182         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15183           auto IFace = MD->getClassInterface();
15184           if (!IFace)
15185             return false;
15186           auto SuperD = IFace->getSuperClass();
15187           if (!SuperD)
15188             return false;
15189           return SuperD->getIdentifier() ==
15190                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15191         };
15192         // Don't issue this warning for unavailable inits or direct subclasses
15193         // of NSObject.
15194         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15195           Diag(MD->getLocation(),
15196                diag::warn_objc_designated_init_missing_super_call);
15197           Diag(InitMethod->getLocation(),
15198                diag::note_objc_designated_init_marked_here);
15199         }
15200         FSI->ObjCWarnForNoDesignatedInitChain = false;
15201       }
15202       if (FSI->ObjCWarnForNoInitDelegation) {
15203         // Don't issue this warning for unavaialable inits.
15204         if (!MD->isUnavailable())
15205           Diag(MD->getLocation(),
15206                diag::warn_objc_secondary_init_missing_init_call);
15207         FSI->ObjCWarnForNoInitDelegation = false;
15208       }
15209 
15210       diagnoseImplicitlyRetainedSelf(*this);
15211     } else {
15212       // Parsing the function declaration failed in some way. Pop the fake scope
15213       // we pushed on.
15214       PopFunctionScopeInfo(ActivePolicy, dcl);
15215       return nullptr;
15216     }
15217 
15218     if (Body && FSI->HasPotentialAvailabilityViolations)
15219       DiagnoseUnguardedAvailabilityViolations(dcl);
15220 
15221     assert(!FSI->ObjCShouldCallSuper &&
15222            "This should only be set for ObjC methods, which should have been "
15223            "handled in the block above.");
15224 
15225     // Verify and clean out per-function state.
15226     if (Body && (!FD || !FD->isDefaulted())) {
15227       // C++ constructors that have function-try-blocks can't have return
15228       // statements in the handlers of that block. (C++ [except.handle]p14)
15229       // Verify this.
15230       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15231         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15232 
15233       // Verify that gotos and switch cases don't jump into scopes illegally.
15234       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15235         DiagnoseInvalidJumps(Body);
15236 
15237       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15238         if (!Destructor->getParent()->isDependentType())
15239           CheckDestructor(Destructor);
15240 
15241         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15242                                                Destructor->getParent());
15243       }
15244 
15245       // If any errors have occurred, clear out any temporaries that may have
15246       // been leftover. This ensures that these temporaries won't be picked up
15247       // for deletion in some later function.
15248       if (hasUncompilableErrorOccurred() ||
15249           getDiagnostics().getSuppressAllDiagnostics()) {
15250         DiscardCleanupsInEvaluationContext();
15251       }
15252       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15253         // Since the body is valid, issue any analysis-based warnings that are
15254         // enabled.
15255         ActivePolicy = &WP;
15256       }
15257 
15258       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15259           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15260         FD->setInvalidDecl();
15261 
15262       if (FD && FD->hasAttr<NakedAttr>()) {
15263         for (const Stmt *S : Body->children()) {
15264           // Allow local register variables without initializer as they don't
15265           // require prologue.
15266           bool RegisterVariables = false;
15267           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15268             for (const auto *Decl : DS->decls()) {
15269               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15270                 RegisterVariables =
15271                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15272                 if (!RegisterVariables)
15273                   break;
15274               }
15275             }
15276           }
15277           if (RegisterVariables)
15278             continue;
15279           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15280             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15281             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15282             FD->setInvalidDecl();
15283             break;
15284           }
15285         }
15286       }
15287 
15288       assert(ExprCleanupObjects.size() ==
15289                  ExprEvalContexts.back().NumCleanupObjects &&
15290              "Leftover temporaries in function");
15291       assert(!Cleanup.exprNeedsCleanups() &&
15292              "Unaccounted cleanups in function");
15293       assert(MaybeODRUseExprs.empty() &&
15294              "Leftover expressions for odr-use checking");
15295     }
15296   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15297     // the declaration context below. Otherwise, we're unable to transform
15298     // 'this' expressions when transforming immediate context functions.
15299 
15300   if (!IsInstantiation)
15301     PopDeclContext();
15302 
15303   PopFunctionScopeInfo(ActivePolicy, dcl);
15304   // If any errors have occurred, clear out any temporaries that may have
15305   // been leftover. This ensures that these temporaries won't be picked up for
15306   // deletion in some later function.
15307   if (hasUncompilableErrorOccurred()) {
15308     DiscardCleanupsInEvaluationContext();
15309   }
15310 
15311   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15312                                   !LangOpts.OMPTargetTriples.empty())) ||
15313              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15314     auto ES = getEmissionStatus(FD);
15315     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15316         ES == Sema::FunctionEmissionStatus::Unknown)
15317       DeclsToCheckForDeferredDiags.insert(FD);
15318   }
15319 
15320   if (FD && !FD->isDeleted())
15321     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15322 
15323   return dcl;
15324 }
15325 
15326 /// When we finish delayed parsing of an attribute, we must attach it to the
15327 /// relevant Decl.
15328 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15329                                        ParsedAttributes &Attrs) {
15330   // Always attach attributes to the underlying decl.
15331   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15332     D = TD->getTemplatedDecl();
15333   ProcessDeclAttributeList(S, D, Attrs);
15334 
15335   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15336     if (Method->isStatic())
15337       checkThisInStaticMemberFunctionAttributes(Method);
15338 }
15339 
15340 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15341 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15342 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15343                                           IdentifierInfo &II, Scope *S) {
15344   // It is not valid to implicitly define a function in C2x.
15345   assert(LangOpts.implicitFunctionsAllowed() &&
15346          "Implicit function declarations aren't allowed in this language mode");
15347 
15348   // Find the scope in which the identifier is injected and the corresponding
15349   // DeclContext.
15350   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15351   // In that case, we inject the declaration into the translation unit scope
15352   // instead.
15353   Scope *BlockScope = S;
15354   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15355     BlockScope = BlockScope->getParent();
15356 
15357   Scope *ContextScope = BlockScope;
15358   while (!ContextScope->getEntity())
15359     ContextScope = ContextScope->getParent();
15360   ContextRAII SavedContext(*this, ContextScope->getEntity());
15361 
15362   // Before we produce a declaration for an implicitly defined
15363   // function, see whether there was a locally-scoped declaration of
15364   // this name as a function or variable. If so, use that
15365   // (non-visible) declaration, and complain about it.
15366   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15367   if (ExternCPrev) {
15368     // We still need to inject the function into the enclosing block scope so
15369     // that later (non-call) uses can see it.
15370     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15371 
15372     // C89 footnote 38:
15373     //   If in fact it is not defined as having type "function returning int",
15374     //   the behavior is undefined.
15375     if (!isa<FunctionDecl>(ExternCPrev) ||
15376         !Context.typesAreCompatible(
15377             cast<FunctionDecl>(ExternCPrev)->getType(),
15378             Context.getFunctionNoProtoType(Context.IntTy))) {
15379       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15380           << ExternCPrev << !getLangOpts().C99;
15381       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15382       return ExternCPrev;
15383     }
15384   }
15385 
15386   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15387   unsigned diag_id;
15388   if (II.getName().startswith("__builtin_"))
15389     diag_id = diag::warn_builtin_unknown;
15390   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15391   else if (getLangOpts().C99)
15392     diag_id = diag::ext_implicit_function_decl_c99;
15393   else
15394     diag_id = diag::warn_implicit_function_decl;
15395 
15396   TypoCorrection Corrected;
15397   // Because typo correction is expensive, only do it if the implicit
15398   // function declaration is going to be treated as an error.
15399   //
15400   // Perform the corection before issuing the main diagnostic, as some consumers
15401   // use typo-correction callbacks to enhance the main diagnostic.
15402   if (S && !ExternCPrev &&
15403       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15404     DeclFilterCCC<FunctionDecl> CCC{};
15405     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15406                             S, nullptr, CCC, CTK_NonError);
15407   }
15408 
15409   Diag(Loc, diag_id) << &II;
15410   if (Corrected) {
15411     // If the correction is going to suggest an implicitly defined function,
15412     // skip the correction as not being a particularly good idea.
15413     bool Diagnose = true;
15414     if (const auto *D = Corrected.getCorrectionDecl())
15415       Diagnose = !D->isImplicit();
15416     if (Diagnose)
15417       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15418                    /*ErrorRecovery*/ false);
15419   }
15420 
15421   // If we found a prior declaration of this function, don't bother building
15422   // another one. We've already pushed that one into scope, so there's nothing
15423   // more to do.
15424   if (ExternCPrev)
15425     return ExternCPrev;
15426 
15427   // Set a Declarator for the implicit definition: int foo();
15428   const char *Dummy;
15429   AttributeFactory attrFactory;
15430   DeclSpec DS(attrFactory);
15431   unsigned DiagID;
15432   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15433                                   Context.getPrintingPolicy());
15434   (void)Error; // Silence warning.
15435   assert(!Error && "Error setting up implicit decl!");
15436   SourceLocation NoLoc;
15437   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15438   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15439                                              /*IsAmbiguous=*/false,
15440                                              /*LParenLoc=*/NoLoc,
15441                                              /*Params=*/nullptr,
15442                                              /*NumParams=*/0,
15443                                              /*EllipsisLoc=*/NoLoc,
15444                                              /*RParenLoc=*/NoLoc,
15445                                              /*RefQualifierIsLvalueRef=*/true,
15446                                              /*RefQualifierLoc=*/NoLoc,
15447                                              /*MutableLoc=*/NoLoc, EST_None,
15448                                              /*ESpecRange=*/SourceRange(),
15449                                              /*Exceptions=*/nullptr,
15450                                              /*ExceptionRanges=*/nullptr,
15451                                              /*NumExceptions=*/0,
15452                                              /*NoexceptExpr=*/nullptr,
15453                                              /*ExceptionSpecTokens=*/nullptr,
15454                                              /*DeclsInPrototype=*/None, Loc,
15455                                              Loc, D),
15456                 std::move(DS.getAttributes()), SourceLocation());
15457   D.SetIdentifier(&II, Loc);
15458 
15459   // Insert this function into the enclosing block scope.
15460   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15461   FD->setImplicit();
15462 
15463   AddKnownFunctionAttributes(FD);
15464 
15465   return FD;
15466 }
15467 
15468 /// If this function is a C++ replaceable global allocation function
15469 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15470 /// adds any function attributes that we know a priori based on the standard.
15471 ///
15472 /// We need to check for duplicate attributes both here and where user-written
15473 /// attributes are applied to declarations.
15474 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15475     FunctionDecl *FD) {
15476   if (FD->isInvalidDecl())
15477     return;
15478 
15479   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15480       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15481     return;
15482 
15483   Optional<unsigned> AlignmentParam;
15484   bool IsNothrow = false;
15485   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15486     return;
15487 
15488   // C++2a [basic.stc.dynamic.allocation]p4:
15489   //   An allocation function that has a non-throwing exception specification
15490   //   indicates failure by returning a null pointer value. Any other allocation
15491   //   function never returns a null pointer value and indicates failure only by
15492   //   throwing an exception [...]
15493   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15494     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15495 
15496   // C++2a [basic.stc.dynamic.allocation]p2:
15497   //   An allocation function attempts to allocate the requested amount of
15498   //   storage. [...] If the request succeeds, the value returned by a
15499   //   replaceable allocation function is a [...] pointer value p0 different
15500   //   from any previously returned value p1 [...]
15501   //
15502   // However, this particular information is being added in codegen,
15503   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15504 
15505   // C++2a [basic.stc.dynamic.allocation]p2:
15506   //   An allocation function attempts to allocate the requested amount of
15507   //   storage. If it is successful, it returns the address of the start of a
15508   //   block of storage whose length in bytes is at least as large as the
15509   //   requested size.
15510   if (!FD->hasAttr<AllocSizeAttr>()) {
15511     FD->addAttr(AllocSizeAttr::CreateImplicit(
15512         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15513         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15514   }
15515 
15516   // C++2a [basic.stc.dynamic.allocation]p3:
15517   //   For an allocation function [...], the pointer returned on a successful
15518   //   call shall represent the address of storage that is aligned as follows:
15519   //   (3.1) If the allocation function takes an argument of type
15520   //         std​::​align_­val_­t, the storage will have the alignment
15521   //         specified by the value of this argument.
15522   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15523     FD->addAttr(AllocAlignAttr::CreateImplicit(
15524         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15525   }
15526 
15527   // FIXME:
15528   // C++2a [basic.stc.dynamic.allocation]p3:
15529   //   For an allocation function [...], the pointer returned on a successful
15530   //   call shall represent the address of storage that is aligned as follows:
15531   //   (3.2) Otherwise, if the allocation function is named operator new[],
15532   //         the storage is aligned for any object that does not have
15533   //         new-extended alignment ([basic.align]) and is no larger than the
15534   //         requested size.
15535   //   (3.3) Otherwise, the storage is aligned for any object that does not
15536   //         have new-extended alignment and is of the requested size.
15537 }
15538 
15539 /// Adds any function attributes that we know a priori based on
15540 /// the declaration of this function.
15541 ///
15542 /// These attributes can apply both to implicitly-declared builtins
15543 /// (like __builtin___printf_chk) or to library-declared functions
15544 /// like NSLog or printf.
15545 ///
15546 /// We need to check for duplicate attributes both here and where user-written
15547 /// attributes are applied to declarations.
15548 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15549   if (FD->isInvalidDecl())
15550     return;
15551 
15552   // If this is a built-in function, map its builtin attributes to
15553   // actual attributes.
15554   if (unsigned BuiltinID = FD->getBuiltinID()) {
15555     // Handle printf-formatting attributes.
15556     unsigned FormatIdx;
15557     bool HasVAListArg;
15558     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15559       if (!FD->hasAttr<FormatAttr>()) {
15560         const char *fmt = "printf";
15561         unsigned int NumParams = FD->getNumParams();
15562         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15563             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15564           fmt = "NSString";
15565         FD->addAttr(FormatAttr::CreateImplicit(Context,
15566                                                &Context.Idents.get(fmt),
15567                                                FormatIdx+1,
15568                                                HasVAListArg ? 0 : FormatIdx+2,
15569                                                FD->getLocation()));
15570       }
15571     }
15572     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15573                                              HasVAListArg)) {
15574      if (!FD->hasAttr<FormatAttr>())
15575        FD->addAttr(FormatAttr::CreateImplicit(Context,
15576                                               &Context.Idents.get("scanf"),
15577                                               FormatIdx+1,
15578                                               HasVAListArg ? 0 : FormatIdx+2,
15579                                               FD->getLocation()));
15580     }
15581 
15582     // Handle automatically recognized callbacks.
15583     SmallVector<int, 4> Encoding;
15584     if (!FD->hasAttr<CallbackAttr>() &&
15585         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15586       FD->addAttr(CallbackAttr::CreateImplicit(
15587           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15588 
15589     // Mark const if we don't care about errno and that is the only thing
15590     // preventing the function from being const. This allows IRgen to use LLVM
15591     // intrinsics for such functions.
15592     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15593         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15594       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15595 
15596     // We make "fma" on GNU or Windows const because we know it does not set
15597     // errno in those environments even though it could set errno based on the
15598     // C standard.
15599     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15600     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15601         !FD->hasAttr<ConstAttr>()) {
15602       switch (BuiltinID) {
15603       case Builtin::BI__builtin_fma:
15604       case Builtin::BI__builtin_fmaf:
15605       case Builtin::BI__builtin_fmal:
15606       case Builtin::BIfma:
15607       case Builtin::BIfmaf:
15608       case Builtin::BIfmal:
15609         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15610         break;
15611       default:
15612         break;
15613       }
15614     }
15615 
15616     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15617         !FD->hasAttr<ReturnsTwiceAttr>())
15618       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15619                                          FD->getLocation()));
15620     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15621       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15622     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15623       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15624     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15625       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15626     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15627         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15628       // Add the appropriate attribute, depending on the CUDA compilation mode
15629       // and which target the builtin belongs to. For example, during host
15630       // compilation, aux builtins are __device__, while the rest are __host__.
15631       if (getLangOpts().CUDAIsDevice !=
15632           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15633         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15634       else
15635         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15636     }
15637 
15638     // Add known guaranteed alignment for allocation functions.
15639     switch (BuiltinID) {
15640     case Builtin::BImemalign:
15641     case Builtin::BIaligned_alloc:
15642       if (!FD->hasAttr<AllocAlignAttr>())
15643         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15644                                                    FD->getLocation()));
15645       break;
15646     default:
15647       break;
15648     }
15649 
15650     // Add allocsize attribute for allocation functions.
15651     switch (BuiltinID) {
15652     case Builtin::BIcalloc:
15653       FD->addAttr(AllocSizeAttr::CreateImplicit(
15654           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15655       break;
15656     case Builtin::BImemalign:
15657     case Builtin::BIaligned_alloc:
15658     case Builtin::BIrealloc:
15659       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15660                                                 ParamIdx(), FD->getLocation()));
15661       break;
15662     case Builtin::BImalloc:
15663       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15664                                                 ParamIdx(), FD->getLocation()));
15665       break;
15666     default:
15667       break;
15668     }
15669   }
15670 
15671   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15672 
15673   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15674   // throw, add an implicit nothrow attribute to any extern "C" function we come
15675   // across.
15676   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15677       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15678     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15679     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15680       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15681   }
15682 
15683   IdentifierInfo *Name = FD->getIdentifier();
15684   if (!Name)
15685     return;
15686   if ((!getLangOpts().CPlusPlus &&
15687        FD->getDeclContext()->isTranslationUnit()) ||
15688       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15689        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15690        LinkageSpecDecl::lang_c)) {
15691     // Okay: this could be a libc/libm/Objective-C function we know
15692     // about.
15693   } else
15694     return;
15695 
15696   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15697     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15698     // target-specific builtins, perhaps?
15699     if (!FD->hasAttr<FormatAttr>())
15700       FD->addAttr(FormatAttr::CreateImplicit(Context,
15701                                              &Context.Idents.get("printf"), 2,
15702                                              Name->isStr("vasprintf") ? 0 : 3,
15703                                              FD->getLocation()));
15704   }
15705 
15706   if (Name->isStr("__CFStringMakeConstantString")) {
15707     // We already have a __builtin___CFStringMakeConstantString,
15708     // but builds that use -fno-constant-cfstrings don't go through that.
15709     if (!FD->hasAttr<FormatArgAttr>())
15710       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15711                                                 FD->getLocation()));
15712   }
15713 }
15714 
15715 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15716                                     TypeSourceInfo *TInfo) {
15717   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15718   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15719 
15720   if (!TInfo) {
15721     assert(D.isInvalidType() && "no declarator info for valid type");
15722     TInfo = Context.getTrivialTypeSourceInfo(T);
15723   }
15724 
15725   // Scope manipulation handled by caller.
15726   TypedefDecl *NewTD =
15727       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15728                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15729 
15730   // Bail out immediately if we have an invalid declaration.
15731   if (D.isInvalidType()) {
15732     NewTD->setInvalidDecl();
15733     return NewTD;
15734   }
15735 
15736   if (D.getDeclSpec().isModulePrivateSpecified()) {
15737     if (CurContext->isFunctionOrMethod())
15738       Diag(NewTD->getLocation(), diag::err_module_private_local)
15739           << 2 << NewTD
15740           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15741           << FixItHint::CreateRemoval(
15742                  D.getDeclSpec().getModulePrivateSpecLoc());
15743     else
15744       NewTD->setModulePrivate();
15745   }
15746 
15747   // C++ [dcl.typedef]p8:
15748   //   If the typedef declaration defines an unnamed class (or
15749   //   enum), the first typedef-name declared by the declaration
15750   //   to be that class type (or enum type) is used to denote the
15751   //   class type (or enum type) for linkage purposes only.
15752   // We need to check whether the type was declared in the declaration.
15753   switch (D.getDeclSpec().getTypeSpecType()) {
15754   case TST_enum:
15755   case TST_struct:
15756   case TST_interface:
15757   case TST_union:
15758   case TST_class: {
15759     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15760     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15761     break;
15762   }
15763 
15764   default:
15765     break;
15766   }
15767 
15768   return NewTD;
15769 }
15770 
15771 /// Check that this is a valid underlying type for an enum declaration.
15772 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15773   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15774   QualType T = TI->getType();
15775 
15776   if (T->isDependentType())
15777     return false;
15778 
15779   // This doesn't use 'isIntegralType' despite the error message mentioning
15780   // integral type because isIntegralType would also allow enum types in C.
15781   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15782     if (BT->isInteger())
15783       return false;
15784 
15785   if (T->isBitIntType())
15786     return false;
15787 
15788   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15789 }
15790 
15791 /// Check whether this is a valid redeclaration of a previous enumeration.
15792 /// \return true if the redeclaration was invalid.
15793 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15794                                   QualType EnumUnderlyingTy, bool IsFixed,
15795                                   const EnumDecl *Prev) {
15796   if (IsScoped != Prev->isScoped()) {
15797     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15798       << Prev->isScoped();
15799     Diag(Prev->getLocation(), diag::note_previous_declaration);
15800     return true;
15801   }
15802 
15803   if (IsFixed && Prev->isFixed()) {
15804     if (!EnumUnderlyingTy->isDependentType() &&
15805         !Prev->getIntegerType()->isDependentType() &&
15806         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15807                                         Prev->getIntegerType())) {
15808       // TODO: Highlight the underlying type of the redeclaration.
15809       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15810         << EnumUnderlyingTy << Prev->getIntegerType();
15811       Diag(Prev->getLocation(), diag::note_previous_declaration)
15812           << Prev->getIntegerTypeRange();
15813       return true;
15814     }
15815   } else if (IsFixed != Prev->isFixed()) {
15816     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15817       << Prev->isFixed();
15818     Diag(Prev->getLocation(), diag::note_previous_declaration);
15819     return true;
15820   }
15821 
15822   return false;
15823 }
15824 
15825 /// Get diagnostic %select index for tag kind for
15826 /// redeclaration diagnostic message.
15827 /// WARNING: Indexes apply to particular diagnostics only!
15828 ///
15829 /// \returns diagnostic %select index.
15830 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15831   switch (Tag) {
15832   case TTK_Struct: return 0;
15833   case TTK_Interface: return 1;
15834   case TTK_Class:  return 2;
15835   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15836   }
15837 }
15838 
15839 /// Determine if tag kind is a class-key compatible with
15840 /// class for redeclaration (class, struct, or __interface).
15841 ///
15842 /// \returns true iff the tag kind is compatible.
15843 static bool isClassCompatTagKind(TagTypeKind Tag)
15844 {
15845   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15846 }
15847 
15848 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15849                                              TagTypeKind TTK) {
15850   if (isa<TypedefDecl>(PrevDecl))
15851     return NTK_Typedef;
15852   else if (isa<TypeAliasDecl>(PrevDecl))
15853     return NTK_TypeAlias;
15854   else if (isa<ClassTemplateDecl>(PrevDecl))
15855     return NTK_Template;
15856   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15857     return NTK_TypeAliasTemplate;
15858   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15859     return NTK_TemplateTemplateArgument;
15860   switch (TTK) {
15861   case TTK_Struct:
15862   case TTK_Interface:
15863   case TTK_Class:
15864     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15865   case TTK_Union:
15866     return NTK_NonUnion;
15867   case TTK_Enum:
15868     return NTK_NonEnum;
15869   }
15870   llvm_unreachable("invalid TTK");
15871 }
15872 
15873 /// Determine whether a tag with a given kind is acceptable
15874 /// as a redeclaration of the given tag declaration.
15875 ///
15876 /// \returns true if the new tag kind is acceptable, false otherwise.
15877 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15878                                         TagTypeKind NewTag, bool isDefinition,
15879                                         SourceLocation NewTagLoc,
15880                                         const IdentifierInfo *Name) {
15881   // C++ [dcl.type.elab]p3:
15882   //   The class-key or enum keyword present in the
15883   //   elaborated-type-specifier shall agree in kind with the
15884   //   declaration to which the name in the elaborated-type-specifier
15885   //   refers. This rule also applies to the form of
15886   //   elaborated-type-specifier that declares a class-name or
15887   //   friend class since it can be construed as referring to the
15888   //   definition of the class. Thus, in any
15889   //   elaborated-type-specifier, the enum keyword shall be used to
15890   //   refer to an enumeration (7.2), the union class-key shall be
15891   //   used to refer to a union (clause 9), and either the class or
15892   //   struct class-key shall be used to refer to a class (clause 9)
15893   //   declared using the class or struct class-key.
15894   TagTypeKind OldTag = Previous->getTagKind();
15895   if (OldTag != NewTag &&
15896       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15897     return false;
15898 
15899   // Tags are compatible, but we might still want to warn on mismatched tags.
15900   // Non-class tags can't be mismatched at this point.
15901   if (!isClassCompatTagKind(NewTag))
15902     return true;
15903 
15904   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15905   // by our warning analysis. We don't want to warn about mismatches with (eg)
15906   // declarations in system headers that are designed to be specialized, but if
15907   // a user asks us to warn, we should warn if their code contains mismatched
15908   // declarations.
15909   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15910     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15911                                       Loc);
15912   };
15913   if (IsIgnoredLoc(NewTagLoc))
15914     return true;
15915 
15916   auto IsIgnored = [&](const TagDecl *Tag) {
15917     return IsIgnoredLoc(Tag->getLocation());
15918   };
15919   while (IsIgnored(Previous)) {
15920     Previous = Previous->getPreviousDecl();
15921     if (!Previous)
15922       return true;
15923     OldTag = Previous->getTagKind();
15924   }
15925 
15926   bool isTemplate = false;
15927   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15928     isTemplate = Record->getDescribedClassTemplate();
15929 
15930   if (inTemplateInstantiation()) {
15931     if (OldTag != NewTag) {
15932       // In a template instantiation, do not offer fix-its for tag mismatches
15933       // since they usually mess up the template instead of fixing the problem.
15934       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15935         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15936         << getRedeclDiagFromTagKind(OldTag);
15937       // FIXME: Note previous location?
15938     }
15939     return true;
15940   }
15941 
15942   if (isDefinition) {
15943     // On definitions, check all previous tags and issue a fix-it for each
15944     // one that doesn't match the current tag.
15945     if (Previous->getDefinition()) {
15946       // Don't suggest fix-its for redefinitions.
15947       return true;
15948     }
15949 
15950     bool previousMismatch = false;
15951     for (const TagDecl *I : Previous->redecls()) {
15952       if (I->getTagKind() != NewTag) {
15953         // Ignore previous declarations for which the warning was disabled.
15954         if (IsIgnored(I))
15955           continue;
15956 
15957         if (!previousMismatch) {
15958           previousMismatch = true;
15959           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15960             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15961             << getRedeclDiagFromTagKind(I->getTagKind());
15962         }
15963         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15964           << getRedeclDiagFromTagKind(NewTag)
15965           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15966                TypeWithKeyword::getTagTypeKindName(NewTag));
15967       }
15968     }
15969     return true;
15970   }
15971 
15972   // Identify the prevailing tag kind: this is the kind of the definition (if
15973   // there is a non-ignored definition), or otherwise the kind of the prior
15974   // (non-ignored) declaration.
15975   const TagDecl *PrevDef = Previous->getDefinition();
15976   if (PrevDef && IsIgnored(PrevDef))
15977     PrevDef = nullptr;
15978   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15979   if (Redecl->getTagKind() != NewTag) {
15980     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15981       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15982       << getRedeclDiagFromTagKind(OldTag);
15983     Diag(Redecl->getLocation(), diag::note_previous_use);
15984 
15985     // If there is a previous definition, suggest a fix-it.
15986     if (PrevDef) {
15987       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15988         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15989         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15990              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15991     }
15992   }
15993 
15994   return true;
15995 }
15996 
15997 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15998 /// from an outer enclosing namespace or file scope inside a friend declaration.
15999 /// This should provide the commented out code in the following snippet:
16000 ///   namespace N {
16001 ///     struct X;
16002 ///     namespace M {
16003 ///       struct Y { friend struct /*N::*/ X; };
16004 ///     }
16005 ///   }
16006 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16007                                          SourceLocation NameLoc) {
16008   // While the decl is in a namespace, do repeated lookup of that name and see
16009   // if we get the same namespace back.  If we do not, continue until
16010   // translation unit scope, at which point we have a fully qualified NNS.
16011   SmallVector<IdentifierInfo *, 4> Namespaces;
16012   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16013   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16014     // This tag should be declared in a namespace, which can only be enclosed by
16015     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16016     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16017     if (!Namespace || Namespace->isAnonymousNamespace())
16018       return FixItHint();
16019     IdentifierInfo *II = Namespace->getIdentifier();
16020     Namespaces.push_back(II);
16021     NamedDecl *Lookup = SemaRef.LookupSingleName(
16022         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16023     if (Lookup == Namespace)
16024       break;
16025   }
16026 
16027   // Once we have all the namespaces, reverse them to go outermost first, and
16028   // build an NNS.
16029   SmallString<64> Insertion;
16030   llvm::raw_svector_ostream OS(Insertion);
16031   if (DC->isTranslationUnit())
16032     OS << "::";
16033   std::reverse(Namespaces.begin(), Namespaces.end());
16034   for (auto *II : Namespaces)
16035     OS << II->getName() << "::";
16036   return FixItHint::CreateInsertion(NameLoc, Insertion);
16037 }
16038 
16039 /// Determine whether a tag originally declared in context \p OldDC can
16040 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16041 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16042 /// using-declaration).
16043 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16044                                          DeclContext *NewDC) {
16045   OldDC = OldDC->getRedeclContext();
16046   NewDC = NewDC->getRedeclContext();
16047 
16048   if (OldDC->Equals(NewDC))
16049     return true;
16050 
16051   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16052   // encloses the other).
16053   if (S.getLangOpts().MSVCCompat &&
16054       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16055     return true;
16056 
16057   return false;
16058 }
16059 
16060 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16061 /// former case, Name will be non-null.  In the later case, Name will be null.
16062 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16063 /// reference/declaration/definition of a tag.
16064 ///
16065 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16066 /// trailing-type-specifier) other than one in an alias-declaration.
16067 ///
16068 /// \param SkipBody If non-null, will be set to indicate if the caller should
16069 /// skip the definition of this tag and treat it as if it were a declaration.
16070 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16071                      SourceLocation KWLoc, CXXScopeSpec &SS,
16072                      IdentifierInfo *Name, SourceLocation NameLoc,
16073                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16074                      SourceLocation ModulePrivateLoc,
16075                      MultiTemplateParamsArg TemplateParameterLists,
16076                      bool &OwnedDecl, bool &IsDependent,
16077                      SourceLocation ScopedEnumKWLoc,
16078                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16079                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16080                      SkipBodyInfo *SkipBody) {
16081   // If this is not a definition, it must have a name.
16082   IdentifierInfo *OrigName = Name;
16083   assert((Name != nullptr || TUK == TUK_Definition) &&
16084          "Nameless record must be a definition!");
16085   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16086 
16087   OwnedDecl = false;
16088   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16089   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16090 
16091   // FIXME: Check member specializations more carefully.
16092   bool isMemberSpecialization = false;
16093   bool Invalid = false;
16094 
16095   // We only need to do this matching if we have template parameters
16096   // or a scope specifier, which also conveniently avoids this work
16097   // for non-C++ cases.
16098   if (TemplateParameterLists.size() > 0 ||
16099       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16100     if (TemplateParameterList *TemplateParams =
16101             MatchTemplateParametersToScopeSpecifier(
16102                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16103                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16104       if (Kind == TTK_Enum) {
16105         Diag(KWLoc, diag::err_enum_template);
16106         return nullptr;
16107       }
16108 
16109       if (TemplateParams->size() > 0) {
16110         // This is a declaration or definition of a class template (which may
16111         // be a member of another template).
16112 
16113         if (Invalid)
16114           return nullptr;
16115 
16116         OwnedDecl = false;
16117         DeclResult Result = CheckClassTemplate(
16118             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16119             AS, ModulePrivateLoc,
16120             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16121             TemplateParameterLists.data(), SkipBody);
16122         return Result.get();
16123       } else {
16124         // The "template<>" header is extraneous.
16125         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16126           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16127         isMemberSpecialization = true;
16128       }
16129     }
16130 
16131     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16132         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16133       return nullptr;
16134   }
16135 
16136   // Figure out the underlying type if this a enum declaration. We need to do
16137   // this early, because it's needed to detect if this is an incompatible
16138   // redeclaration.
16139   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16140   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16141 
16142   if (Kind == TTK_Enum) {
16143     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16144       // No underlying type explicitly specified, or we failed to parse the
16145       // type, default to int.
16146       EnumUnderlying = Context.IntTy.getTypePtr();
16147     } else if (UnderlyingType.get()) {
16148       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16149       // integral type; any cv-qualification is ignored.
16150       TypeSourceInfo *TI = nullptr;
16151       GetTypeFromParser(UnderlyingType.get(), &TI);
16152       EnumUnderlying = TI;
16153 
16154       if (CheckEnumUnderlyingType(TI))
16155         // Recover by falling back to int.
16156         EnumUnderlying = Context.IntTy.getTypePtr();
16157 
16158       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16159                                           UPPC_FixedUnderlyingType))
16160         EnumUnderlying = Context.IntTy.getTypePtr();
16161 
16162     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16163       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16164       // of 'int'. However, if this is an unfixed forward declaration, don't set
16165       // the underlying type unless the user enables -fms-compatibility. This
16166       // makes unfixed forward declared enums incomplete and is more conforming.
16167       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16168         EnumUnderlying = Context.IntTy.getTypePtr();
16169     }
16170   }
16171 
16172   DeclContext *SearchDC = CurContext;
16173   DeclContext *DC = CurContext;
16174   bool isStdBadAlloc = false;
16175   bool isStdAlignValT = false;
16176 
16177   RedeclarationKind Redecl = forRedeclarationInCurContext();
16178   if (TUK == TUK_Friend || TUK == TUK_Reference)
16179     Redecl = NotForRedeclaration;
16180 
16181   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16182   /// implemented asks for structural equivalence checking, the returned decl
16183   /// here is passed back to the parser, allowing the tag body to be parsed.
16184   auto createTagFromNewDecl = [&]() -> TagDecl * {
16185     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16186     // If there is an identifier, use the location of the identifier as the
16187     // location of the decl, otherwise use the location of the struct/union
16188     // keyword.
16189     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16190     TagDecl *New = nullptr;
16191 
16192     if (Kind == TTK_Enum) {
16193       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16194                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16195       // If this is an undefined enum, bail.
16196       if (TUK != TUK_Definition && !Invalid)
16197         return nullptr;
16198       if (EnumUnderlying) {
16199         EnumDecl *ED = cast<EnumDecl>(New);
16200         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16201           ED->setIntegerTypeSourceInfo(TI);
16202         else
16203           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16204         ED->setPromotionType(ED->getIntegerType());
16205       }
16206     } else { // struct/union
16207       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16208                                nullptr);
16209     }
16210 
16211     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16212       // Add alignment attributes if necessary; these attributes are checked
16213       // when the ASTContext lays out the structure.
16214       //
16215       // It is important for implementing the correct semantics that this
16216       // happen here (in ActOnTag). The #pragma pack stack is
16217       // maintained as a result of parser callbacks which can occur at
16218       // many points during the parsing of a struct declaration (because
16219       // the #pragma tokens are effectively skipped over during the
16220       // parsing of the struct).
16221       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16222         AddAlignmentAttributesForRecord(RD);
16223         AddMsStructLayoutForRecord(RD);
16224       }
16225     }
16226     New->setLexicalDeclContext(CurContext);
16227     return New;
16228   };
16229 
16230   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16231   if (Name && SS.isNotEmpty()) {
16232     // We have a nested-name tag ('struct foo::bar').
16233 
16234     // Check for invalid 'foo::'.
16235     if (SS.isInvalid()) {
16236       Name = nullptr;
16237       goto CreateNewDecl;
16238     }
16239 
16240     // If this is a friend or a reference to a class in a dependent
16241     // context, don't try to make a decl for it.
16242     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16243       DC = computeDeclContext(SS, false);
16244       if (!DC) {
16245         IsDependent = true;
16246         return nullptr;
16247       }
16248     } else {
16249       DC = computeDeclContext(SS, true);
16250       if (!DC) {
16251         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16252           << SS.getRange();
16253         return nullptr;
16254       }
16255     }
16256 
16257     if (RequireCompleteDeclContext(SS, DC))
16258       return nullptr;
16259 
16260     SearchDC = DC;
16261     // Look-up name inside 'foo::'.
16262     LookupQualifiedName(Previous, DC);
16263 
16264     if (Previous.isAmbiguous())
16265       return nullptr;
16266 
16267     if (Previous.empty()) {
16268       // Name lookup did not find anything. However, if the
16269       // nested-name-specifier refers to the current instantiation,
16270       // and that current instantiation has any dependent base
16271       // classes, we might find something at instantiation time: treat
16272       // this as a dependent elaborated-type-specifier.
16273       // But this only makes any sense for reference-like lookups.
16274       if (Previous.wasNotFoundInCurrentInstantiation() &&
16275           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16276         IsDependent = true;
16277         return nullptr;
16278       }
16279 
16280       // A tag 'foo::bar' must already exist.
16281       Diag(NameLoc, diag::err_not_tag_in_scope)
16282         << Kind << Name << DC << SS.getRange();
16283       Name = nullptr;
16284       Invalid = true;
16285       goto CreateNewDecl;
16286     }
16287   } else if (Name) {
16288     // C++14 [class.mem]p14:
16289     //   If T is the name of a class, then each of the following shall have a
16290     //   name different from T:
16291     //    -- every member of class T that is itself a type
16292     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16293         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16294       return nullptr;
16295 
16296     // If this is a named struct, check to see if there was a previous forward
16297     // declaration or definition.
16298     // FIXME: We're looking into outer scopes here, even when we
16299     // shouldn't be. Doing so can result in ambiguities that we
16300     // shouldn't be diagnosing.
16301     LookupName(Previous, S);
16302 
16303     // When declaring or defining a tag, ignore ambiguities introduced
16304     // by types using'ed into this scope.
16305     if (Previous.isAmbiguous() &&
16306         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16307       LookupResult::Filter F = Previous.makeFilter();
16308       while (F.hasNext()) {
16309         NamedDecl *ND = F.next();
16310         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16311                 SearchDC->getRedeclContext()))
16312           F.erase();
16313       }
16314       F.done();
16315     }
16316 
16317     // C++11 [namespace.memdef]p3:
16318     //   If the name in a friend declaration is neither qualified nor
16319     //   a template-id and the declaration is a function or an
16320     //   elaborated-type-specifier, the lookup to determine whether
16321     //   the entity has been previously declared shall not consider
16322     //   any scopes outside the innermost enclosing namespace.
16323     //
16324     // MSVC doesn't implement the above rule for types, so a friend tag
16325     // declaration may be a redeclaration of a type declared in an enclosing
16326     // scope.  They do implement this rule for friend functions.
16327     //
16328     // Does it matter that this should be by scope instead of by
16329     // semantic context?
16330     if (!Previous.empty() && TUK == TUK_Friend) {
16331       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16332       LookupResult::Filter F = Previous.makeFilter();
16333       bool FriendSawTagOutsideEnclosingNamespace = false;
16334       while (F.hasNext()) {
16335         NamedDecl *ND = F.next();
16336         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16337         if (DC->isFileContext() &&
16338             !EnclosingNS->Encloses(ND->getDeclContext())) {
16339           if (getLangOpts().MSVCCompat)
16340             FriendSawTagOutsideEnclosingNamespace = true;
16341           else
16342             F.erase();
16343         }
16344       }
16345       F.done();
16346 
16347       // Diagnose this MSVC extension in the easy case where lookup would have
16348       // unambiguously found something outside the enclosing namespace.
16349       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16350         NamedDecl *ND = Previous.getFoundDecl();
16351         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16352             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16353       }
16354     }
16355 
16356     // Note:  there used to be some attempt at recovery here.
16357     if (Previous.isAmbiguous())
16358       return nullptr;
16359 
16360     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16361       // FIXME: This makes sure that we ignore the contexts associated
16362       // with C structs, unions, and enums when looking for a matching
16363       // tag declaration or definition. See the similar lookup tweak
16364       // in Sema::LookupName; is there a better way to deal with this?
16365       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16366         SearchDC = SearchDC->getParent();
16367     } else if (getLangOpts().CPlusPlus) {
16368       // Inside ObjCContainer want to keep it as a lexical decl context but go
16369       // past it (most often to TranslationUnit) to find the semantic decl
16370       // context.
16371       while (isa<ObjCContainerDecl>(SearchDC))
16372         SearchDC = SearchDC->getParent();
16373     }
16374   } else if (getLangOpts().CPlusPlus) {
16375     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16376     // TagDecl the same way as we skip it for named TagDecl.
16377     while (isa<ObjCContainerDecl>(SearchDC))
16378       SearchDC = SearchDC->getParent();
16379   }
16380 
16381   if (Previous.isSingleResult() &&
16382       Previous.getFoundDecl()->isTemplateParameter()) {
16383     // Maybe we will complain about the shadowed template parameter.
16384     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16385     // Just pretend that we didn't see the previous declaration.
16386     Previous.clear();
16387   }
16388 
16389   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16390       DC->Equals(getStdNamespace())) {
16391     if (Name->isStr("bad_alloc")) {
16392       // This is a declaration of or a reference to "std::bad_alloc".
16393       isStdBadAlloc = true;
16394 
16395       // If std::bad_alloc has been implicitly declared (but made invisible to
16396       // name lookup), fill in this implicit declaration as the previous
16397       // declaration, so that the declarations get chained appropriately.
16398       if (Previous.empty() && StdBadAlloc)
16399         Previous.addDecl(getStdBadAlloc());
16400     } else if (Name->isStr("align_val_t")) {
16401       isStdAlignValT = true;
16402       if (Previous.empty() && StdAlignValT)
16403         Previous.addDecl(getStdAlignValT());
16404     }
16405   }
16406 
16407   // If we didn't find a previous declaration, and this is a reference
16408   // (or friend reference), move to the correct scope.  In C++, we
16409   // also need to do a redeclaration lookup there, just in case
16410   // there's a shadow friend decl.
16411   if (Name && Previous.empty() &&
16412       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16413     if (Invalid) goto CreateNewDecl;
16414     assert(SS.isEmpty());
16415 
16416     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16417       // C++ [basic.scope.pdecl]p5:
16418       //   -- for an elaborated-type-specifier of the form
16419       //
16420       //          class-key identifier
16421       //
16422       //      if the elaborated-type-specifier is used in the
16423       //      decl-specifier-seq or parameter-declaration-clause of a
16424       //      function defined in namespace scope, the identifier is
16425       //      declared as a class-name in the namespace that contains
16426       //      the declaration; otherwise, except as a friend
16427       //      declaration, the identifier is declared in the smallest
16428       //      non-class, non-function-prototype scope that contains the
16429       //      declaration.
16430       //
16431       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16432       // C structs and unions.
16433       //
16434       // It is an error in C++ to declare (rather than define) an enum
16435       // type, including via an elaborated type specifier.  We'll
16436       // diagnose that later; for now, declare the enum in the same
16437       // scope as we would have picked for any other tag type.
16438       //
16439       // GNU C also supports this behavior as part of its incomplete
16440       // enum types extension, while GNU C++ does not.
16441       //
16442       // Find the context where we'll be declaring the tag.
16443       // FIXME: We would like to maintain the current DeclContext as the
16444       // lexical context,
16445       SearchDC = getTagInjectionContext(SearchDC);
16446 
16447       // Find the scope where we'll be declaring the tag.
16448       S = getTagInjectionScope(S, getLangOpts());
16449     } else {
16450       assert(TUK == TUK_Friend);
16451       // C++ [namespace.memdef]p3:
16452       //   If a friend declaration in a non-local class first declares a
16453       //   class or function, the friend class or function is a member of
16454       //   the innermost enclosing namespace.
16455       SearchDC = SearchDC->getEnclosingNamespaceContext();
16456     }
16457 
16458     // In C++, we need to do a redeclaration lookup to properly
16459     // diagnose some problems.
16460     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16461     // hidden declaration so that we don't get ambiguity errors when using a
16462     // type declared by an elaborated-type-specifier.  In C that is not correct
16463     // and we should instead merge compatible types found by lookup.
16464     if (getLangOpts().CPlusPlus) {
16465       // FIXME: This can perform qualified lookups into function contexts,
16466       // which are meaningless.
16467       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16468       LookupQualifiedName(Previous, SearchDC);
16469     } else {
16470       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16471       LookupName(Previous, S);
16472     }
16473   }
16474 
16475   // If we have a known previous declaration to use, then use it.
16476   if (Previous.empty() && SkipBody && SkipBody->Previous)
16477     Previous.addDecl(SkipBody->Previous);
16478 
16479   if (!Previous.empty()) {
16480     NamedDecl *PrevDecl = Previous.getFoundDecl();
16481     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16482 
16483     // It's okay to have a tag decl in the same scope as a typedef
16484     // which hides a tag decl in the same scope.  Finding this
16485     // with a redeclaration lookup can only actually happen in C++.
16486     //
16487     // This is also okay for elaborated-type-specifiers, which is
16488     // technically forbidden by the current standard but which is
16489     // okay according to the likely resolution of an open issue;
16490     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16491     if (getLangOpts().CPlusPlus) {
16492       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16493         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16494           TagDecl *Tag = TT->getDecl();
16495           if (Tag->getDeclName() == Name &&
16496               Tag->getDeclContext()->getRedeclContext()
16497                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16498             PrevDecl = Tag;
16499             Previous.clear();
16500             Previous.addDecl(Tag);
16501             Previous.resolveKind();
16502           }
16503         }
16504       }
16505     }
16506 
16507     // If this is a redeclaration of a using shadow declaration, it must
16508     // declare a tag in the same context. In MSVC mode, we allow a
16509     // redefinition if either context is within the other.
16510     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16511       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16512       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16513           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16514           !(OldTag && isAcceptableTagRedeclContext(
16515                           *this, OldTag->getDeclContext(), SearchDC))) {
16516         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16517         Diag(Shadow->getTargetDecl()->getLocation(),
16518              diag::note_using_decl_target);
16519         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16520             << 0;
16521         // Recover by ignoring the old declaration.
16522         Previous.clear();
16523         goto CreateNewDecl;
16524       }
16525     }
16526 
16527     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16528       // If this is a use of a previous tag, or if the tag is already declared
16529       // in the same scope (so that the definition/declaration completes or
16530       // rementions the tag), reuse the decl.
16531       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16532           isDeclInScope(DirectPrevDecl, SearchDC, S,
16533                         SS.isNotEmpty() || isMemberSpecialization)) {
16534         // Make sure that this wasn't declared as an enum and now used as a
16535         // struct or something similar.
16536         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16537                                           TUK == TUK_Definition, KWLoc,
16538                                           Name)) {
16539           bool SafeToContinue
16540             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16541                Kind != TTK_Enum);
16542           if (SafeToContinue)
16543             Diag(KWLoc, diag::err_use_with_wrong_tag)
16544               << Name
16545               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16546                                               PrevTagDecl->getKindName());
16547           else
16548             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16549           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16550 
16551           if (SafeToContinue)
16552             Kind = PrevTagDecl->getTagKind();
16553           else {
16554             // Recover by making this an anonymous redefinition.
16555             Name = nullptr;
16556             Previous.clear();
16557             Invalid = true;
16558           }
16559         }
16560 
16561         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16562           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16563           if (TUK == TUK_Reference || TUK == TUK_Friend)
16564             return PrevTagDecl;
16565 
16566           QualType EnumUnderlyingTy;
16567           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16568             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16569           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16570             EnumUnderlyingTy = QualType(T, 0);
16571 
16572           // All conflicts with previous declarations are recovered by
16573           // returning the previous declaration, unless this is a definition,
16574           // in which case we want the caller to bail out.
16575           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16576                                      ScopedEnum, EnumUnderlyingTy,
16577                                      IsFixed, PrevEnum))
16578             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16579         }
16580 
16581         // C++11 [class.mem]p1:
16582         //   A member shall not be declared twice in the member-specification,
16583         //   except that a nested class or member class template can be declared
16584         //   and then later defined.
16585         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16586             S->isDeclScope(PrevDecl)) {
16587           Diag(NameLoc, diag::ext_member_redeclared);
16588           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16589         }
16590 
16591         if (!Invalid) {
16592           // If this is a use, just return the declaration we found, unless
16593           // we have attributes.
16594           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16595             if (!Attrs.empty()) {
16596               // FIXME: Diagnose these attributes. For now, we create a new
16597               // declaration to hold them.
16598             } else if (TUK == TUK_Reference &&
16599                        (PrevTagDecl->getFriendObjectKind() ==
16600                             Decl::FOK_Undeclared ||
16601                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16602                        SS.isEmpty()) {
16603               // This declaration is a reference to an existing entity, but
16604               // has different visibility from that entity: it either makes
16605               // a friend visible or it makes a type visible in a new module.
16606               // In either case, create a new declaration. We only do this if
16607               // the declaration would have meant the same thing if no prior
16608               // declaration were found, that is, if it was found in the same
16609               // scope where we would have injected a declaration.
16610               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16611                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16612                 return PrevTagDecl;
16613               // This is in the injected scope, create a new declaration in
16614               // that scope.
16615               S = getTagInjectionScope(S, getLangOpts());
16616             } else {
16617               return PrevTagDecl;
16618             }
16619           }
16620 
16621           // Diagnose attempts to redefine a tag.
16622           if (TUK == TUK_Definition) {
16623             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16624               // If we're defining a specialization and the previous definition
16625               // is from an implicit instantiation, don't emit an error
16626               // here; we'll catch this in the general case below.
16627               bool IsExplicitSpecializationAfterInstantiation = false;
16628               if (isMemberSpecialization) {
16629                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16630                   IsExplicitSpecializationAfterInstantiation =
16631                     RD->getTemplateSpecializationKind() !=
16632                     TSK_ExplicitSpecialization;
16633                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16634                   IsExplicitSpecializationAfterInstantiation =
16635                     ED->getTemplateSpecializationKind() !=
16636                     TSK_ExplicitSpecialization;
16637               }
16638 
16639               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16640               // not keep more that one definition around (merge them). However,
16641               // ensure the decl passes the structural compatibility check in
16642               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16643               NamedDecl *Hidden = nullptr;
16644               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16645                 // There is a definition of this tag, but it is not visible. We
16646                 // explicitly make use of C++'s one definition rule here, and
16647                 // assume that this definition is identical to the hidden one
16648                 // we already have. Make the existing definition visible and
16649                 // use it in place of this one.
16650                 if (!getLangOpts().CPlusPlus) {
16651                   // Postpone making the old definition visible until after we
16652                   // complete parsing the new one and do the structural
16653                   // comparison.
16654                   SkipBody->CheckSameAsPrevious = true;
16655                   SkipBody->New = createTagFromNewDecl();
16656                   SkipBody->Previous = Def;
16657                   return Def;
16658                 } else {
16659                   SkipBody->ShouldSkip = true;
16660                   SkipBody->Previous = Def;
16661                   makeMergedDefinitionVisible(Hidden);
16662                   // Carry on and handle it like a normal definition. We'll
16663                   // skip starting the definitiion later.
16664                 }
16665               } else if (!IsExplicitSpecializationAfterInstantiation) {
16666                 // A redeclaration in function prototype scope in C isn't
16667                 // visible elsewhere, so merely issue a warning.
16668                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16669                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16670                 else
16671                   Diag(NameLoc, diag::err_redefinition) << Name;
16672                 notePreviousDefinition(Def,
16673                                        NameLoc.isValid() ? NameLoc : KWLoc);
16674                 // If this is a redefinition, recover by making this
16675                 // struct be anonymous, which will make any later
16676                 // references get the previous definition.
16677                 Name = nullptr;
16678                 Previous.clear();
16679                 Invalid = true;
16680               }
16681             } else {
16682               // If the type is currently being defined, complain
16683               // about a nested redefinition.
16684               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16685               if (TD->isBeingDefined()) {
16686                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16687                 Diag(PrevTagDecl->getLocation(),
16688                      diag::note_previous_definition);
16689                 Name = nullptr;
16690                 Previous.clear();
16691                 Invalid = true;
16692               }
16693             }
16694 
16695             // Okay, this is definition of a previously declared or referenced
16696             // tag. We're going to create a new Decl for it.
16697           }
16698 
16699           // Okay, we're going to make a redeclaration.  If this is some kind
16700           // of reference, make sure we build the redeclaration in the same DC
16701           // as the original, and ignore the current access specifier.
16702           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16703             SearchDC = PrevTagDecl->getDeclContext();
16704             AS = AS_none;
16705           }
16706         }
16707         // If we get here we have (another) forward declaration or we
16708         // have a definition.  Just create a new decl.
16709 
16710       } else {
16711         // If we get here, this is a definition of a new tag type in a nested
16712         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16713         // new decl/type.  We set PrevDecl to NULL so that the entities
16714         // have distinct types.
16715         Previous.clear();
16716       }
16717       // If we get here, we're going to create a new Decl. If PrevDecl
16718       // is non-NULL, it's a definition of the tag declared by
16719       // PrevDecl. If it's NULL, we have a new definition.
16720 
16721     // Otherwise, PrevDecl is not a tag, but was found with tag
16722     // lookup.  This is only actually possible in C++, where a few
16723     // things like templates still live in the tag namespace.
16724     } else {
16725       // Use a better diagnostic if an elaborated-type-specifier
16726       // found the wrong kind of type on the first
16727       // (non-redeclaration) lookup.
16728       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16729           !Previous.isForRedeclaration()) {
16730         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16731         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16732                                                        << Kind;
16733         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16734         Invalid = true;
16735 
16736       // Otherwise, only diagnose if the declaration is in scope.
16737       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16738                                 SS.isNotEmpty() || isMemberSpecialization)) {
16739         // do nothing
16740 
16741       // Diagnose implicit declarations introduced by elaborated types.
16742       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16743         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16744         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16745         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16746         Invalid = true;
16747 
16748       // Otherwise it's a declaration.  Call out a particularly common
16749       // case here.
16750       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16751         unsigned Kind = 0;
16752         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16753         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16754           << Name << Kind << TND->getUnderlyingType();
16755         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16756         Invalid = true;
16757 
16758       // Otherwise, diagnose.
16759       } else {
16760         // The tag name clashes with something else in the target scope,
16761         // issue an error and recover by making this tag be anonymous.
16762         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16763         notePreviousDefinition(PrevDecl, NameLoc);
16764         Name = nullptr;
16765         Invalid = true;
16766       }
16767 
16768       // The existing declaration isn't relevant to us; we're in a
16769       // new scope, so clear out the previous declaration.
16770       Previous.clear();
16771     }
16772   }
16773 
16774 CreateNewDecl:
16775 
16776   TagDecl *PrevDecl = nullptr;
16777   if (Previous.isSingleResult())
16778     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16779 
16780   // If there is an identifier, use the location of the identifier as the
16781   // location of the decl, otherwise use the location of the struct/union
16782   // keyword.
16783   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16784 
16785   // Otherwise, create a new declaration. If there is a previous
16786   // declaration of the same entity, the two will be linked via
16787   // PrevDecl.
16788   TagDecl *New;
16789 
16790   if (Kind == TTK_Enum) {
16791     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16792     // enum X { A, B, C } D;    D should chain to X.
16793     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16794                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16795                            ScopedEnumUsesClassTag, IsFixed);
16796 
16797     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16798       StdAlignValT = cast<EnumDecl>(New);
16799 
16800     // If this is an undefined enum, warn.
16801     if (TUK != TUK_Definition && !Invalid) {
16802       TagDecl *Def;
16803       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16804         // C++0x: 7.2p2: opaque-enum-declaration.
16805         // Conflicts are diagnosed above. Do nothing.
16806       }
16807       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16808         Diag(Loc, diag::ext_forward_ref_enum_def)
16809           << New;
16810         Diag(Def->getLocation(), diag::note_previous_definition);
16811       } else {
16812         unsigned DiagID = diag::ext_forward_ref_enum;
16813         if (getLangOpts().MSVCCompat)
16814           DiagID = diag::ext_ms_forward_ref_enum;
16815         else if (getLangOpts().CPlusPlus)
16816           DiagID = diag::err_forward_ref_enum;
16817         Diag(Loc, DiagID);
16818       }
16819     }
16820 
16821     if (EnumUnderlying) {
16822       EnumDecl *ED = cast<EnumDecl>(New);
16823       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16824         ED->setIntegerTypeSourceInfo(TI);
16825       else
16826         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16827       ED->setPromotionType(ED->getIntegerType());
16828       assert(ED->isComplete() && "enum with type should be complete");
16829     }
16830   } else {
16831     // struct/union/class
16832 
16833     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16834     // struct X { int A; } D;    D should chain to X.
16835     if (getLangOpts().CPlusPlus) {
16836       // FIXME: Look for a way to use RecordDecl for simple structs.
16837       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16838                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16839 
16840       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16841         StdBadAlloc = cast<CXXRecordDecl>(New);
16842     } else
16843       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16844                                cast_or_null<RecordDecl>(PrevDecl));
16845   }
16846 
16847   // C++11 [dcl.type]p3:
16848   //   A type-specifier-seq shall not define a class or enumeration [...].
16849   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16850       TUK == TUK_Definition) {
16851     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16852       << Context.getTagDeclType(New);
16853     Invalid = true;
16854   }
16855 
16856   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16857       DC->getDeclKind() == Decl::Enum) {
16858     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16859       << Context.getTagDeclType(New);
16860     Invalid = true;
16861   }
16862 
16863   // Maybe add qualifier info.
16864   if (SS.isNotEmpty()) {
16865     if (SS.isSet()) {
16866       // If this is either a declaration or a definition, check the
16867       // nested-name-specifier against the current context.
16868       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16869           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16870                                        isMemberSpecialization))
16871         Invalid = true;
16872 
16873       New->setQualifierInfo(SS.getWithLocInContext(Context));
16874       if (TemplateParameterLists.size() > 0) {
16875         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16876       }
16877     }
16878     else
16879       Invalid = true;
16880   }
16881 
16882   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16883     // Add alignment attributes if necessary; these attributes are checked when
16884     // the ASTContext lays out the structure.
16885     //
16886     // It is important for implementing the correct semantics that this
16887     // happen here (in ActOnTag). The #pragma pack stack is
16888     // maintained as a result of parser callbacks which can occur at
16889     // many points during the parsing of a struct declaration (because
16890     // the #pragma tokens are effectively skipped over during the
16891     // parsing of the struct).
16892     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16893       AddAlignmentAttributesForRecord(RD);
16894       AddMsStructLayoutForRecord(RD);
16895     }
16896   }
16897 
16898   if (ModulePrivateLoc.isValid()) {
16899     if (isMemberSpecialization)
16900       Diag(New->getLocation(), diag::err_module_private_specialization)
16901         << 2
16902         << FixItHint::CreateRemoval(ModulePrivateLoc);
16903     // __module_private__ does not apply to local classes. However, we only
16904     // diagnose this as an error when the declaration specifiers are
16905     // freestanding. Here, we just ignore the __module_private__.
16906     else if (!SearchDC->isFunctionOrMethod())
16907       New->setModulePrivate();
16908   }
16909 
16910   // If this is a specialization of a member class (of a class template),
16911   // check the specialization.
16912   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16913     Invalid = true;
16914 
16915   // If we're declaring or defining a tag in function prototype scope in C,
16916   // note that this type can only be used within the function and add it to
16917   // the list of decls to inject into the function definition scope.
16918   if ((Name || Kind == TTK_Enum) &&
16919       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16920     if (getLangOpts().CPlusPlus) {
16921       // C++ [dcl.fct]p6:
16922       //   Types shall not be defined in return or parameter types.
16923       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16924         Diag(Loc, diag::err_type_defined_in_param_type)
16925             << Name;
16926         Invalid = true;
16927       }
16928     } else if (!PrevDecl) {
16929       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16930     }
16931   }
16932 
16933   if (Invalid)
16934     New->setInvalidDecl();
16935 
16936   // Set the lexical context. If the tag has a C++ scope specifier, the
16937   // lexical context will be different from the semantic context.
16938   New->setLexicalDeclContext(CurContext);
16939 
16940   // Mark this as a friend decl if applicable.
16941   // In Microsoft mode, a friend declaration also acts as a forward
16942   // declaration so we always pass true to setObjectOfFriendDecl to make
16943   // the tag name visible.
16944   if (TUK == TUK_Friend)
16945     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16946 
16947   // Set the access specifier.
16948   if (!Invalid && SearchDC->isRecord())
16949     SetMemberAccessSpecifier(New, PrevDecl, AS);
16950 
16951   if (PrevDecl)
16952     CheckRedeclarationInModule(New, PrevDecl);
16953 
16954   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16955     New->startDefinition();
16956 
16957   ProcessDeclAttributeList(S, New, Attrs);
16958   AddPragmaAttributes(S, New);
16959 
16960   // If this has an identifier, add it to the scope stack.
16961   if (TUK == TUK_Friend) {
16962     // We might be replacing an existing declaration in the lookup tables;
16963     // if so, borrow its access specifier.
16964     if (PrevDecl)
16965       New->setAccess(PrevDecl->getAccess());
16966 
16967     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16968     DC->makeDeclVisibleInContext(New);
16969     if (Name) // can be null along some error paths
16970       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16971         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16972   } else if (Name) {
16973     S = getNonFieldDeclScope(S);
16974     PushOnScopeChains(New, S, true);
16975   } else {
16976     CurContext->addDecl(New);
16977   }
16978 
16979   // If this is the C FILE type, notify the AST context.
16980   if (IdentifierInfo *II = New->getIdentifier())
16981     if (!New->isInvalidDecl() &&
16982         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16983         II->isStr("FILE"))
16984       Context.setFILEDecl(New);
16985 
16986   if (PrevDecl)
16987     mergeDeclAttributes(New, PrevDecl);
16988 
16989   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16990     inferGslOwnerPointerAttribute(CXXRD);
16991 
16992   // If there's a #pragma GCC visibility in scope, set the visibility of this
16993   // record.
16994   AddPushedVisibilityAttribute(New);
16995 
16996   if (isMemberSpecialization && !New->isInvalidDecl())
16997     CompleteMemberSpecialization(New, Previous);
16998 
16999   OwnedDecl = true;
17000   // In C++, don't return an invalid declaration. We can't recover well from
17001   // the cases where we make the type anonymous.
17002   if (Invalid && getLangOpts().CPlusPlus) {
17003     if (New->isBeingDefined())
17004       if (auto RD = dyn_cast<RecordDecl>(New))
17005         RD->completeDefinition();
17006     return nullptr;
17007   } else if (SkipBody && SkipBody->ShouldSkip) {
17008     return SkipBody->Previous;
17009   } else {
17010     return New;
17011   }
17012 }
17013 
17014 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17015   AdjustDeclIfTemplate(TagD);
17016   TagDecl *Tag = cast<TagDecl>(TagD);
17017 
17018   // Enter the tag context.
17019   PushDeclContext(S, Tag);
17020 
17021   ActOnDocumentableDecl(TagD);
17022 
17023   // If there's a #pragma GCC visibility in scope, set the visibility of this
17024   // record.
17025   AddPushedVisibilityAttribute(Tag);
17026 }
17027 
17028 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17029   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17030     return false;
17031 
17032   // Make the previous decl visible.
17033   makeMergedDefinitionVisible(SkipBody.Previous);
17034   return true;
17035 }
17036 
17037 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17038   assert(IDecl->getLexicalParent() == CurContext &&
17039       "The next DeclContext should be lexically contained in the current one.");
17040   CurContext = IDecl;
17041 }
17042 
17043 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17044                                            SourceLocation FinalLoc,
17045                                            bool IsFinalSpelledSealed,
17046                                            bool IsAbstract,
17047                                            SourceLocation LBraceLoc) {
17048   AdjustDeclIfTemplate(TagD);
17049   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17050 
17051   FieldCollector->StartClass();
17052 
17053   if (!Record->getIdentifier())
17054     return;
17055 
17056   if (IsAbstract)
17057     Record->markAbstract();
17058 
17059   if (FinalLoc.isValid()) {
17060     Record->addAttr(FinalAttr::Create(
17061         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17062         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17063   }
17064   // C++ [class]p2:
17065   //   [...] The class-name is also inserted into the scope of the
17066   //   class itself; this is known as the injected-class-name. For
17067   //   purposes of access checking, the injected-class-name is treated
17068   //   as if it were a public member name.
17069   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17070       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17071       Record->getLocation(), Record->getIdentifier(),
17072       /*PrevDecl=*/nullptr,
17073       /*DelayTypeCreation=*/true);
17074   Context.getTypeDeclType(InjectedClassName, Record);
17075   InjectedClassName->setImplicit();
17076   InjectedClassName->setAccess(AS_public);
17077   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17078       InjectedClassName->setDescribedClassTemplate(Template);
17079   PushOnScopeChains(InjectedClassName, S);
17080   assert(InjectedClassName->isInjectedClassName() &&
17081          "Broken injected-class-name");
17082 }
17083 
17084 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17085                                     SourceRange BraceRange) {
17086   AdjustDeclIfTemplate(TagD);
17087   TagDecl *Tag = cast<TagDecl>(TagD);
17088   Tag->setBraceRange(BraceRange);
17089 
17090   // Make sure we "complete" the definition even it is invalid.
17091   if (Tag->isBeingDefined()) {
17092     assert(Tag->isInvalidDecl() && "We should already have completed it");
17093     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17094       RD->completeDefinition();
17095   }
17096 
17097   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17098     FieldCollector->FinishClass();
17099     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17100       auto *Def = RD->getDefinition();
17101       assert(Def && "The record is expected to have a completed definition");
17102       unsigned NumInitMethods = 0;
17103       for (auto *Method : Def->methods()) {
17104         if (!Method->getIdentifier())
17105             continue;
17106         if (Method->getName() == "__init")
17107           NumInitMethods++;
17108       }
17109       if (NumInitMethods > 1 || !Def->hasInitMethod())
17110         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17111     }
17112   }
17113 
17114   // Exit this scope of this tag's definition.
17115   PopDeclContext();
17116 
17117   if (getCurLexicalContext()->isObjCContainer() &&
17118       Tag->getDeclContext()->isFileContext())
17119     Tag->setTopLevelDeclInObjCContainer();
17120 
17121   // Notify the consumer that we've defined a tag.
17122   if (!Tag->isInvalidDecl())
17123     Consumer.HandleTagDeclDefinition(Tag);
17124 
17125   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17126   // from XLs and instead matches the XL #pragma pack(1) behavior.
17127   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17128       AlignPackStack.hasValue()) {
17129     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17130     // Only diagnose #pragma align(packed).
17131     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17132       return;
17133     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17134     if (!RD)
17135       return;
17136     // Only warn if there is at least 1 bitfield member.
17137     if (llvm::any_of(RD->fields(),
17138                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17139       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17140   }
17141 }
17142 
17143 void Sema::ActOnObjCContainerFinishDefinition() {
17144   // Exit this scope of this interface definition.
17145   PopDeclContext();
17146 }
17147 
17148 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17149   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17150   OriginalLexicalContext = ObjCCtx;
17151   ActOnObjCContainerFinishDefinition();
17152 }
17153 
17154 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17155   ActOnObjCContainerStartDefinition(ObjCCtx);
17156   OriginalLexicalContext = nullptr;
17157 }
17158 
17159 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17160   AdjustDeclIfTemplate(TagD);
17161   TagDecl *Tag = cast<TagDecl>(TagD);
17162   Tag->setInvalidDecl();
17163 
17164   // Make sure we "complete" the definition even it is invalid.
17165   if (Tag->isBeingDefined()) {
17166     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17167       RD->completeDefinition();
17168   }
17169 
17170   // We're undoing ActOnTagStartDefinition here, not
17171   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17172   // the FieldCollector.
17173 
17174   PopDeclContext();
17175 }
17176 
17177 // Note that FieldName may be null for anonymous bitfields.
17178 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17179                                 IdentifierInfo *FieldName, QualType FieldTy,
17180                                 bool IsMsStruct, Expr *BitWidth) {
17181   assert(BitWidth);
17182   if (BitWidth->containsErrors())
17183     return ExprError();
17184 
17185   // C99 6.7.2.1p4 - verify the field type.
17186   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17187   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17188     // Handle incomplete and sizeless types with a specific error.
17189     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17190                                  diag::err_field_incomplete_or_sizeless))
17191       return ExprError();
17192     if (FieldName)
17193       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17194         << FieldName << FieldTy << BitWidth->getSourceRange();
17195     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17196       << FieldTy << BitWidth->getSourceRange();
17197   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17198                                              UPPC_BitFieldWidth))
17199     return ExprError();
17200 
17201   // If the bit-width is type- or value-dependent, don't try to check
17202   // it now.
17203   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17204     return BitWidth;
17205 
17206   llvm::APSInt Value;
17207   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17208   if (ICE.isInvalid())
17209     return ICE;
17210   BitWidth = ICE.get();
17211 
17212   // Zero-width bitfield is ok for anonymous field.
17213   if (Value == 0 && FieldName)
17214     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17215 
17216   if (Value.isSigned() && Value.isNegative()) {
17217     if (FieldName)
17218       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17219                << FieldName << toString(Value, 10);
17220     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17221       << toString(Value, 10);
17222   }
17223 
17224   // The size of the bit-field must not exceed our maximum permitted object
17225   // size.
17226   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17227     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17228            << !FieldName << FieldName << toString(Value, 10);
17229   }
17230 
17231   if (!FieldTy->isDependentType()) {
17232     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17233     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17234     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17235 
17236     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17237     // ABI.
17238     bool CStdConstraintViolation =
17239         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17240     bool MSBitfieldViolation =
17241         Value.ugt(TypeStorageSize) &&
17242         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17243     if (CStdConstraintViolation || MSBitfieldViolation) {
17244       unsigned DiagWidth =
17245           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17246       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17247              << (bool)FieldName << FieldName << toString(Value, 10)
17248              << !CStdConstraintViolation << DiagWidth;
17249     }
17250 
17251     // Warn on types where the user might conceivably expect to get all
17252     // specified bits as value bits: that's all integral types other than
17253     // 'bool'.
17254     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17255       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17256           << FieldName << toString(Value, 10)
17257           << (unsigned)TypeWidth;
17258     }
17259   }
17260 
17261   return BitWidth;
17262 }
17263 
17264 /// ActOnField - Each field of a C struct/union is passed into this in order
17265 /// to create a FieldDecl object for it.
17266 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17267                        Declarator &D, Expr *BitfieldWidth) {
17268   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17269                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17270                                /*InitStyle=*/ICIS_NoInit, AS_public);
17271   return Res;
17272 }
17273 
17274 /// HandleField - Analyze a field of a C struct or a C++ data member.
17275 ///
17276 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17277                              SourceLocation DeclStart,
17278                              Declarator &D, Expr *BitWidth,
17279                              InClassInitStyle InitStyle,
17280                              AccessSpecifier AS) {
17281   if (D.isDecompositionDeclarator()) {
17282     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17283     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17284       << Decomp.getSourceRange();
17285     return nullptr;
17286   }
17287 
17288   IdentifierInfo *II = D.getIdentifier();
17289   SourceLocation Loc = DeclStart;
17290   if (II) Loc = D.getIdentifierLoc();
17291 
17292   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17293   QualType T = TInfo->getType();
17294   if (getLangOpts().CPlusPlus) {
17295     CheckExtraCXXDefaultArguments(D);
17296 
17297     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17298                                         UPPC_DataMemberType)) {
17299       D.setInvalidType();
17300       T = Context.IntTy;
17301       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17302     }
17303   }
17304 
17305   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17306 
17307   if (D.getDeclSpec().isInlineSpecified())
17308     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17309         << getLangOpts().CPlusPlus17;
17310   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17311     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17312          diag::err_invalid_thread)
17313       << DeclSpec::getSpecifierName(TSCS);
17314 
17315   // Check to see if this name was declared as a member previously
17316   NamedDecl *PrevDecl = nullptr;
17317   LookupResult Previous(*this, II, Loc, LookupMemberName,
17318                         ForVisibleRedeclaration);
17319   LookupName(Previous, S);
17320   switch (Previous.getResultKind()) {
17321     case LookupResult::Found:
17322     case LookupResult::FoundUnresolvedValue:
17323       PrevDecl = Previous.getAsSingle<NamedDecl>();
17324       break;
17325 
17326     case LookupResult::FoundOverloaded:
17327       PrevDecl = Previous.getRepresentativeDecl();
17328       break;
17329 
17330     case LookupResult::NotFound:
17331     case LookupResult::NotFoundInCurrentInstantiation:
17332     case LookupResult::Ambiguous:
17333       break;
17334   }
17335   Previous.suppressDiagnostics();
17336 
17337   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17338     // Maybe we will complain about the shadowed template parameter.
17339     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17340     // Just pretend that we didn't see the previous declaration.
17341     PrevDecl = nullptr;
17342   }
17343 
17344   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17345     PrevDecl = nullptr;
17346 
17347   bool Mutable
17348     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17349   SourceLocation TSSL = D.getBeginLoc();
17350   FieldDecl *NewFD
17351     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17352                      TSSL, AS, PrevDecl, &D);
17353 
17354   if (NewFD->isInvalidDecl())
17355     Record->setInvalidDecl();
17356 
17357   if (D.getDeclSpec().isModulePrivateSpecified())
17358     NewFD->setModulePrivate();
17359 
17360   if (NewFD->isInvalidDecl() && PrevDecl) {
17361     // Don't introduce NewFD into scope; there's already something
17362     // with the same name in the same scope.
17363   } else if (II) {
17364     PushOnScopeChains(NewFD, S);
17365   } else
17366     Record->addDecl(NewFD);
17367 
17368   return NewFD;
17369 }
17370 
17371 /// Build a new FieldDecl and check its well-formedness.
17372 ///
17373 /// This routine builds a new FieldDecl given the fields name, type,
17374 /// record, etc. \p PrevDecl should refer to any previous declaration
17375 /// with the same name and in the same scope as the field to be
17376 /// created.
17377 ///
17378 /// \returns a new FieldDecl.
17379 ///
17380 /// \todo The Declarator argument is a hack. It will be removed once
17381 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17382                                 TypeSourceInfo *TInfo,
17383                                 RecordDecl *Record, SourceLocation Loc,
17384                                 bool Mutable, Expr *BitWidth,
17385                                 InClassInitStyle InitStyle,
17386                                 SourceLocation TSSL,
17387                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17388                                 Declarator *D) {
17389   IdentifierInfo *II = Name.getAsIdentifierInfo();
17390   bool InvalidDecl = false;
17391   if (D) InvalidDecl = D->isInvalidType();
17392 
17393   // If we receive a broken type, recover by assuming 'int' and
17394   // marking this declaration as invalid.
17395   if (T.isNull() || T->containsErrors()) {
17396     InvalidDecl = true;
17397     T = Context.IntTy;
17398   }
17399 
17400   QualType EltTy = Context.getBaseElementType(T);
17401   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17402     if (RequireCompleteSizedType(Loc, EltTy,
17403                                  diag::err_field_incomplete_or_sizeless)) {
17404       // Fields of incomplete type force their record to be invalid.
17405       Record->setInvalidDecl();
17406       InvalidDecl = true;
17407     } else {
17408       NamedDecl *Def;
17409       EltTy->isIncompleteType(&Def);
17410       if (Def && Def->isInvalidDecl()) {
17411         Record->setInvalidDecl();
17412         InvalidDecl = true;
17413       }
17414     }
17415   }
17416 
17417   // TR 18037 does not allow fields to be declared with address space
17418   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17419       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17420     Diag(Loc, diag::err_field_with_address_space);
17421     Record->setInvalidDecl();
17422     InvalidDecl = true;
17423   }
17424 
17425   if (LangOpts.OpenCL) {
17426     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17427     // used as structure or union field: image, sampler, event or block types.
17428     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17429         T->isBlockPointerType()) {
17430       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17431       Record->setInvalidDecl();
17432       InvalidDecl = true;
17433     }
17434     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17435     // is enabled.
17436     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17437                         "__cl_clang_bitfields", LangOpts)) {
17438       Diag(Loc, diag::err_opencl_bitfields);
17439       InvalidDecl = true;
17440     }
17441   }
17442 
17443   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17444   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17445       T.hasQualifiers()) {
17446     InvalidDecl = true;
17447     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17448   }
17449 
17450   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17451   // than a variably modified type.
17452   if (!InvalidDecl && T->isVariablyModifiedType()) {
17453     if (!tryToFixVariablyModifiedVarType(
17454             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17455       InvalidDecl = true;
17456   }
17457 
17458   // Fields can not have abstract class types
17459   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17460                                              diag::err_abstract_type_in_decl,
17461                                              AbstractFieldType))
17462     InvalidDecl = true;
17463 
17464   if (InvalidDecl)
17465     BitWidth = nullptr;
17466   // If this is declared as a bit-field, check the bit-field.
17467   if (BitWidth) {
17468     BitWidth =
17469         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17470     if (!BitWidth) {
17471       InvalidDecl = true;
17472       BitWidth = nullptr;
17473     }
17474   }
17475 
17476   // Check that 'mutable' is consistent with the type of the declaration.
17477   if (!InvalidDecl && Mutable) {
17478     unsigned DiagID = 0;
17479     if (T->isReferenceType())
17480       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17481                                         : diag::err_mutable_reference;
17482     else if (T.isConstQualified())
17483       DiagID = diag::err_mutable_const;
17484 
17485     if (DiagID) {
17486       SourceLocation ErrLoc = Loc;
17487       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17488         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17489       Diag(ErrLoc, DiagID);
17490       if (DiagID != diag::ext_mutable_reference) {
17491         Mutable = false;
17492         InvalidDecl = true;
17493       }
17494     }
17495   }
17496 
17497   // C++11 [class.union]p8 (DR1460):
17498   //   At most one variant member of a union may have a
17499   //   brace-or-equal-initializer.
17500   if (InitStyle != ICIS_NoInit)
17501     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17502 
17503   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17504                                        BitWidth, Mutable, InitStyle);
17505   if (InvalidDecl)
17506     NewFD->setInvalidDecl();
17507 
17508   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17509     Diag(Loc, diag::err_duplicate_member) << II;
17510     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17511     NewFD->setInvalidDecl();
17512   }
17513 
17514   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17515     if (Record->isUnion()) {
17516       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17517         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17518         if (RDecl->getDefinition()) {
17519           // C++ [class.union]p1: An object of a class with a non-trivial
17520           // constructor, a non-trivial copy constructor, a non-trivial
17521           // destructor, or a non-trivial copy assignment operator
17522           // cannot be a member of a union, nor can an array of such
17523           // objects.
17524           if (CheckNontrivialField(NewFD))
17525             NewFD->setInvalidDecl();
17526         }
17527       }
17528 
17529       // C++ [class.union]p1: If a union contains a member of reference type,
17530       // the program is ill-formed, except when compiling with MSVC extensions
17531       // enabled.
17532       if (EltTy->isReferenceType()) {
17533         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17534                                     diag::ext_union_member_of_reference_type :
17535                                     diag::err_union_member_of_reference_type)
17536           << NewFD->getDeclName() << EltTy;
17537         if (!getLangOpts().MicrosoftExt)
17538           NewFD->setInvalidDecl();
17539       }
17540     }
17541   }
17542 
17543   // FIXME: We need to pass in the attributes given an AST
17544   // representation, not a parser representation.
17545   if (D) {
17546     // FIXME: The current scope is almost... but not entirely... correct here.
17547     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17548 
17549     if (NewFD->hasAttrs())
17550       CheckAlignasUnderalignment(NewFD);
17551   }
17552 
17553   // In auto-retain/release, infer strong retension for fields of
17554   // retainable type.
17555   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17556     NewFD->setInvalidDecl();
17557 
17558   if (T.isObjCGCWeak())
17559     Diag(Loc, diag::warn_attribute_weak_on_field);
17560 
17561   // PPC MMA non-pointer types are not allowed as field types.
17562   if (Context.getTargetInfo().getTriple().isPPC64() &&
17563       CheckPPCMMAType(T, NewFD->getLocation()))
17564     NewFD->setInvalidDecl();
17565 
17566   NewFD->setAccess(AS);
17567   return NewFD;
17568 }
17569 
17570 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17571   assert(FD);
17572   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17573 
17574   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17575     return false;
17576 
17577   QualType EltTy = Context.getBaseElementType(FD->getType());
17578   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17579     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17580     if (RDecl->getDefinition()) {
17581       // We check for copy constructors before constructors
17582       // because otherwise we'll never get complaints about
17583       // copy constructors.
17584 
17585       CXXSpecialMember member = CXXInvalid;
17586       // We're required to check for any non-trivial constructors. Since the
17587       // implicit default constructor is suppressed if there are any
17588       // user-declared constructors, we just need to check that there is a
17589       // trivial default constructor and a trivial copy constructor. (We don't
17590       // worry about move constructors here, since this is a C++98 check.)
17591       if (RDecl->hasNonTrivialCopyConstructor())
17592         member = CXXCopyConstructor;
17593       else if (!RDecl->hasTrivialDefaultConstructor())
17594         member = CXXDefaultConstructor;
17595       else if (RDecl->hasNonTrivialCopyAssignment())
17596         member = CXXCopyAssignment;
17597       else if (RDecl->hasNonTrivialDestructor())
17598         member = CXXDestructor;
17599 
17600       if (member != CXXInvalid) {
17601         if (!getLangOpts().CPlusPlus11 &&
17602             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17603           // Objective-C++ ARC: it is an error to have a non-trivial field of
17604           // a union. However, system headers in Objective-C programs
17605           // occasionally have Objective-C lifetime objects within unions,
17606           // and rather than cause the program to fail, we make those
17607           // members unavailable.
17608           SourceLocation Loc = FD->getLocation();
17609           if (getSourceManager().isInSystemHeader(Loc)) {
17610             if (!FD->hasAttr<UnavailableAttr>())
17611               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17612                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17613             return false;
17614           }
17615         }
17616 
17617         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17618                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17619                diag::err_illegal_union_or_anon_struct_member)
17620           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17621         DiagnoseNontrivial(RDecl, member);
17622         return !getLangOpts().CPlusPlus11;
17623       }
17624     }
17625   }
17626 
17627   return false;
17628 }
17629 
17630 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17631 ///  AST enum value.
17632 static ObjCIvarDecl::AccessControl
17633 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17634   switch (ivarVisibility) {
17635   default: llvm_unreachable("Unknown visitibility kind");
17636   case tok::objc_private: return ObjCIvarDecl::Private;
17637   case tok::objc_public: return ObjCIvarDecl::Public;
17638   case tok::objc_protected: return ObjCIvarDecl::Protected;
17639   case tok::objc_package: return ObjCIvarDecl::Package;
17640   }
17641 }
17642 
17643 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17644 /// in order to create an IvarDecl object for it.
17645 Decl *Sema::ActOnIvar(Scope *S,
17646                                 SourceLocation DeclStart,
17647                                 Declarator &D, Expr *BitfieldWidth,
17648                                 tok::ObjCKeywordKind Visibility) {
17649 
17650   IdentifierInfo *II = D.getIdentifier();
17651   Expr *BitWidth = (Expr*)BitfieldWidth;
17652   SourceLocation Loc = DeclStart;
17653   if (II) Loc = D.getIdentifierLoc();
17654 
17655   // FIXME: Unnamed fields can be handled in various different ways, for
17656   // example, unnamed unions inject all members into the struct namespace!
17657 
17658   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17659   QualType T = TInfo->getType();
17660 
17661   if (BitWidth) {
17662     // 6.7.2.1p3, 6.7.2.1p4
17663     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17664     if (!BitWidth)
17665       D.setInvalidType();
17666   } else {
17667     // Not a bitfield.
17668 
17669     // validate II.
17670 
17671   }
17672   if (T->isReferenceType()) {
17673     Diag(Loc, diag::err_ivar_reference_type);
17674     D.setInvalidType();
17675   }
17676   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17677   // than a variably modified type.
17678   else if (T->isVariablyModifiedType()) {
17679     if (!tryToFixVariablyModifiedVarType(
17680             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17681       D.setInvalidType();
17682   }
17683 
17684   // Get the visibility (access control) for this ivar.
17685   ObjCIvarDecl::AccessControl ac =
17686     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17687                                         : ObjCIvarDecl::None;
17688   // Must set ivar's DeclContext to its enclosing interface.
17689   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17690   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17691     return nullptr;
17692   ObjCContainerDecl *EnclosingContext;
17693   if (ObjCImplementationDecl *IMPDecl =
17694       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17695     if (LangOpts.ObjCRuntime.isFragile()) {
17696     // Case of ivar declared in an implementation. Context is that of its class.
17697       EnclosingContext = IMPDecl->getClassInterface();
17698       assert(EnclosingContext && "Implementation has no class interface!");
17699     }
17700     else
17701       EnclosingContext = EnclosingDecl;
17702   } else {
17703     if (ObjCCategoryDecl *CDecl =
17704         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17705       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17706         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17707         return nullptr;
17708       }
17709     }
17710     EnclosingContext = EnclosingDecl;
17711   }
17712 
17713   // Construct the decl.
17714   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17715                                              DeclStart, Loc, II, T,
17716                                              TInfo, ac, (Expr *)BitfieldWidth);
17717 
17718   if (II) {
17719     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17720                                            ForVisibleRedeclaration);
17721     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17722         && !isa<TagDecl>(PrevDecl)) {
17723       Diag(Loc, diag::err_duplicate_member) << II;
17724       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17725       NewID->setInvalidDecl();
17726     }
17727   }
17728 
17729   // Process attributes attached to the ivar.
17730   ProcessDeclAttributes(S, NewID, D);
17731 
17732   if (D.isInvalidType())
17733     NewID->setInvalidDecl();
17734 
17735   // In ARC, infer 'retaining' for ivars of retainable type.
17736   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17737     NewID->setInvalidDecl();
17738 
17739   if (D.getDeclSpec().isModulePrivateSpecified())
17740     NewID->setModulePrivate();
17741 
17742   if (II) {
17743     // FIXME: When interfaces are DeclContexts, we'll need to add
17744     // these to the interface.
17745     S->AddDecl(NewID);
17746     IdResolver.AddDecl(NewID);
17747   }
17748 
17749   if (LangOpts.ObjCRuntime.isNonFragile() &&
17750       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17751     Diag(Loc, diag::warn_ivars_in_interface);
17752 
17753   return NewID;
17754 }
17755 
17756 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17757 /// class and class extensions. For every class \@interface and class
17758 /// extension \@interface, if the last ivar is a bitfield of any type,
17759 /// then add an implicit `char :0` ivar to the end of that interface.
17760 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17761                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17762   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17763     return;
17764 
17765   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17766   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17767 
17768   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17769     return;
17770   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17771   if (!ID) {
17772     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17773       if (!CD->IsClassExtension())
17774         return;
17775     }
17776     // No need to add this to end of @implementation.
17777     else
17778       return;
17779   }
17780   // All conditions are met. Add a new bitfield to the tail end of ivars.
17781   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17782   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17783 
17784   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17785                               DeclLoc, DeclLoc, nullptr,
17786                               Context.CharTy,
17787                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17788                                                                DeclLoc),
17789                               ObjCIvarDecl::Private, BW,
17790                               true);
17791   AllIvarDecls.push_back(Ivar);
17792 }
17793 
17794 namespace {
17795 /// [class.dtor]p4:
17796 ///   At the end of the definition of a class, overload resolution is
17797 ///   performed among the prospective destructors declared in that class with
17798 ///   an empty argument list to select the destructor for the class, also
17799 ///   known as the selected destructor.
17800 ///
17801 /// We do the overload resolution here, then mark the selected constructor in the AST.
17802 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17803 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17804   if (!Record->hasUserDeclaredDestructor()) {
17805     return;
17806   }
17807 
17808   SourceLocation Loc = Record->getLocation();
17809   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17810 
17811   for (auto *Decl : Record->decls()) {
17812     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17813       if (DD->isInvalidDecl())
17814         continue;
17815       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17816                              OCS);
17817       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17818     }
17819   }
17820 
17821   if (OCS.empty()) {
17822     return;
17823   }
17824   OverloadCandidateSet::iterator Best;
17825   unsigned Msg = 0;
17826   OverloadCandidateDisplayKind DisplayKind;
17827 
17828   switch (OCS.BestViableFunction(S, Loc, Best)) {
17829   case OR_Success:
17830   case OR_Deleted:
17831     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17832     break;
17833 
17834   case OR_Ambiguous:
17835     Msg = diag::err_ambiguous_destructor;
17836     DisplayKind = OCD_AmbiguousCandidates;
17837     break;
17838 
17839   case OR_No_Viable_Function:
17840     Msg = diag::err_no_viable_destructor;
17841     DisplayKind = OCD_AllCandidates;
17842     break;
17843   }
17844 
17845   if (Msg) {
17846     // OpenCL have got their own thing going with destructors. It's slightly broken,
17847     // but we allow it.
17848     if (!S.LangOpts.OpenCL) {
17849       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17850       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17851       Record->setInvalidDecl();
17852     }
17853     // It's a bit hacky: At this point we've raised an error but we want the
17854     // rest of the compiler to continue somehow working. However almost
17855     // everything we'll try to do with the class will depend on there being a
17856     // destructor. So let's pretend the first one is selected and hope for the
17857     // best.
17858     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17859   }
17860 }
17861 } // namespace
17862 
17863 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17864                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17865                        SourceLocation RBrac,
17866                        const ParsedAttributesView &Attrs) {
17867   assert(EnclosingDecl && "missing record or interface decl");
17868 
17869   // If this is an Objective-C @implementation or category and we have
17870   // new fields here we should reset the layout of the interface since
17871   // it will now change.
17872   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17873     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17874     switch (DC->getKind()) {
17875     default: break;
17876     case Decl::ObjCCategory:
17877       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17878       break;
17879     case Decl::ObjCImplementation:
17880       Context.
17881         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17882       break;
17883     }
17884   }
17885 
17886   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17887   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17888 
17889   if (CXXRecord && !CXXRecord->isDependentType())
17890     ComputeSelectedDestructor(*this, CXXRecord);
17891 
17892   // Start counting up the number of named members; make sure to include
17893   // members of anonymous structs and unions in the total.
17894   unsigned NumNamedMembers = 0;
17895   if (Record) {
17896     for (const auto *I : Record->decls()) {
17897       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17898         if (IFD->getDeclName())
17899           ++NumNamedMembers;
17900     }
17901   }
17902 
17903   // Verify that all the fields are okay.
17904   SmallVector<FieldDecl*, 32> RecFields;
17905 
17906   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17907        i != end; ++i) {
17908     FieldDecl *FD = cast<FieldDecl>(*i);
17909 
17910     // Get the type for the field.
17911     const Type *FDTy = FD->getType().getTypePtr();
17912 
17913     if (!FD->isAnonymousStructOrUnion()) {
17914       // Remember all fields written by the user.
17915       RecFields.push_back(FD);
17916     }
17917 
17918     // If the field is already invalid for some reason, don't emit more
17919     // diagnostics about it.
17920     if (FD->isInvalidDecl()) {
17921       EnclosingDecl->setInvalidDecl();
17922       continue;
17923     }
17924 
17925     // C99 6.7.2.1p2:
17926     //   A structure or union shall not contain a member with
17927     //   incomplete or function type (hence, a structure shall not
17928     //   contain an instance of itself, but may contain a pointer to
17929     //   an instance of itself), except that the last member of a
17930     //   structure with more than one named member may have incomplete
17931     //   array type; such a structure (and any union containing,
17932     //   possibly recursively, a member that is such a structure)
17933     //   shall not be a member of a structure or an element of an
17934     //   array.
17935     bool IsLastField = (i + 1 == Fields.end());
17936     if (FDTy->isFunctionType()) {
17937       // Field declared as a function.
17938       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17939         << FD->getDeclName();
17940       FD->setInvalidDecl();
17941       EnclosingDecl->setInvalidDecl();
17942       continue;
17943     } else if (FDTy->isIncompleteArrayType() &&
17944                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17945       if (Record) {
17946         // Flexible array member.
17947         // Microsoft and g++ is more permissive regarding flexible array.
17948         // It will accept flexible array in union and also
17949         // as the sole element of a struct/class.
17950         unsigned DiagID = 0;
17951         if (!Record->isUnion() && !IsLastField) {
17952           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17953             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17954           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17955           FD->setInvalidDecl();
17956           EnclosingDecl->setInvalidDecl();
17957           continue;
17958         } else if (Record->isUnion())
17959           DiagID = getLangOpts().MicrosoftExt
17960                        ? diag::ext_flexible_array_union_ms
17961                        : getLangOpts().CPlusPlus
17962                              ? diag::ext_flexible_array_union_gnu
17963                              : diag::err_flexible_array_union;
17964         else if (NumNamedMembers < 1)
17965           DiagID = getLangOpts().MicrosoftExt
17966                        ? diag::ext_flexible_array_empty_aggregate_ms
17967                        : getLangOpts().CPlusPlus
17968                              ? diag::ext_flexible_array_empty_aggregate_gnu
17969                              : diag::err_flexible_array_empty_aggregate;
17970 
17971         if (DiagID)
17972           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17973                                           << Record->getTagKind();
17974         // While the layout of types that contain virtual bases is not specified
17975         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17976         // virtual bases after the derived members.  This would make a flexible
17977         // array member declared at the end of an object not adjacent to the end
17978         // of the type.
17979         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17980           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17981               << FD->getDeclName() << Record->getTagKind();
17982         if (!getLangOpts().C99)
17983           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17984             << FD->getDeclName() << Record->getTagKind();
17985 
17986         // If the element type has a non-trivial destructor, we would not
17987         // implicitly destroy the elements, so disallow it for now.
17988         //
17989         // FIXME: GCC allows this. We should probably either implicitly delete
17990         // the destructor of the containing class, or just allow this.
17991         QualType BaseElem = Context.getBaseElementType(FD->getType());
17992         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17993           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17994             << FD->getDeclName() << FD->getType();
17995           FD->setInvalidDecl();
17996           EnclosingDecl->setInvalidDecl();
17997           continue;
17998         }
17999         // Okay, we have a legal flexible array member at the end of the struct.
18000         Record->setHasFlexibleArrayMember(true);
18001       } else {
18002         // In ObjCContainerDecl ivars with incomplete array type are accepted,
18003         // unless they are followed by another ivar. That check is done
18004         // elsewhere, after synthesized ivars are known.
18005       }
18006     } else if (!FDTy->isDependentType() &&
18007                RequireCompleteSizedType(
18008                    FD->getLocation(), FD->getType(),
18009                    diag::err_field_incomplete_or_sizeless)) {
18010       // Incomplete type
18011       FD->setInvalidDecl();
18012       EnclosingDecl->setInvalidDecl();
18013       continue;
18014     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18015       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18016         // A type which contains a flexible array member is considered to be a
18017         // flexible array member.
18018         Record->setHasFlexibleArrayMember(true);
18019         if (!Record->isUnion()) {
18020           // If this is a struct/class and this is not the last element, reject
18021           // it.  Note that GCC supports variable sized arrays in the middle of
18022           // structures.
18023           if (!IsLastField)
18024             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18025               << FD->getDeclName() << FD->getType();
18026           else {
18027             // We support flexible arrays at the end of structs in
18028             // other structs as an extension.
18029             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18030               << FD->getDeclName();
18031           }
18032         }
18033       }
18034       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18035           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18036                                  diag::err_abstract_type_in_decl,
18037                                  AbstractIvarType)) {
18038         // Ivars can not have abstract class types
18039         FD->setInvalidDecl();
18040       }
18041       if (Record && FDTTy->getDecl()->hasObjectMember())
18042         Record->setHasObjectMember(true);
18043       if (Record && FDTTy->getDecl()->hasVolatileMember())
18044         Record->setHasVolatileMember(true);
18045     } else if (FDTy->isObjCObjectType()) {
18046       /// A field cannot be an Objective-c object
18047       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18048         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18049       QualType T = Context.getObjCObjectPointerType(FD->getType());
18050       FD->setType(T);
18051     } else if (Record && Record->isUnion() &&
18052                FD->getType().hasNonTrivialObjCLifetime() &&
18053                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18054                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18055                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18056                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18057       // For backward compatibility, fields of C unions declared in system
18058       // headers that have non-trivial ObjC ownership qualifications are marked
18059       // as unavailable unless the qualifier is explicit and __strong. This can
18060       // break ABI compatibility between programs compiled with ARC and MRR, but
18061       // is a better option than rejecting programs using those unions under
18062       // ARC.
18063       FD->addAttr(UnavailableAttr::CreateImplicit(
18064           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18065           FD->getLocation()));
18066     } else if (getLangOpts().ObjC &&
18067                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18068                !Record->hasObjectMember()) {
18069       if (FD->getType()->isObjCObjectPointerType() ||
18070           FD->getType().isObjCGCStrong())
18071         Record->setHasObjectMember(true);
18072       else if (Context.getAsArrayType(FD->getType())) {
18073         QualType BaseType = Context.getBaseElementType(FD->getType());
18074         if (BaseType->isRecordType() &&
18075             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18076           Record->setHasObjectMember(true);
18077         else if (BaseType->isObjCObjectPointerType() ||
18078                  BaseType.isObjCGCStrong())
18079                Record->setHasObjectMember(true);
18080       }
18081     }
18082 
18083     if (Record && !getLangOpts().CPlusPlus &&
18084         !shouldIgnoreForRecordTriviality(FD)) {
18085       QualType FT = FD->getType();
18086       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18087         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18088         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18089             Record->isUnion())
18090           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18091       }
18092       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18093       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18094         Record->setNonTrivialToPrimitiveCopy(true);
18095         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18096           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18097       }
18098       if (FT.isDestructedType()) {
18099         Record->setNonTrivialToPrimitiveDestroy(true);
18100         Record->setParamDestroyedInCallee(true);
18101         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18102           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18103       }
18104 
18105       if (const auto *RT = FT->getAs<RecordType>()) {
18106         if (RT->getDecl()->getArgPassingRestrictions() ==
18107             RecordDecl::APK_CanNeverPassInRegs)
18108           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18109       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18110         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18111     }
18112 
18113     if (Record && FD->getType().isVolatileQualified())
18114       Record->setHasVolatileMember(true);
18115     // Keep track of the number of named members.
18116     if (FD->getIdentifier())
18117       ++NumNamedMembers;
18118   }
18119 
18120   // Okay, we successfully defined 'Record'.
18121   if (Record) {
18122     bool Completed = false;
18123     if (CXXRecord) {
18124       if (!CXXRecord->isInvalidDecl()) {
18125         // Set access bits correctly on the directly-declared conversions.
18126         for (CXXRecordDecl::conversion_iterator
18127                I = CXXRecord->conversion_begin(),
18128                E = CXXRecord->conversion_end(); I != E; ++I)
18129           I.setAccess((*I)->getAccess());
18130       }
18131 
18132       // Add any implicitly-declared members to this class.
18133       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18134 
18135       if (!CXXRecord->isDependentType()) {
18136         if (!CXXRecord->isInvalidDecl()) {
18137           // If we have virtual base classes, we may end up finding multiple
18138           // final overriders for a given virtual function. Check for this
18139           // problem now.
18140           if (CXXRecord->getNumVBases()) {
18141             CXXFinalOverriderMap FinalOverriders;
18142             CXXRecord->getFinalOverriders(FinalOverriders);
18143 
18144             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18145                                              MEnd = FinalOverriders.end();
18146                  M != MEnd; ++M) {
18147               for (OverridingMethods::iterator SO = M->second.begin(),
18148                                             SOEnd = M->second.end();
18149                    SO != SOEnd; ++SO) {
18150                 assert(SO->second.size() > 0 &&
18151                        "Virtual function without overriding functions?");
18152                 if (SO->second.size() == 1)
18153                   continue;
18154 
18155                 // C++ [class.virtual]p2:
18156                 //   In a derived class, if a virtual member function of a base
18157                 //   class subobject has more than one final overrider the
18158                 //   program is ill-formed.
18159                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18160                   << (const NamedDecl *)M->first << Record;
18161                 Diag(M->first->getLocation(),
18162                      diag::note_overridden_virtual_function);
18163                 for (OverridingMethods::overriding_iterator
18164                           OM = SO->second.begin(),
18165                        OMEnd = SO->second.end();
18166                      OM != OMEnd; ++OM)
18167                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18168                     << (const NamedDecl *)M->first << OM->Method->getParent();
18169 
18170                 Record->setInvalidDecl();
18171               }
18172             }
18173             CXXRecord->completeDefinition(&FinalOverriders);
18174             Completed = true;
18175           }
18176         }
18177       }
18178     }
18179 
18180     if (!Completed)
18181       Record->completeDefinition();
18182 
18183     // Handle attributes before checking the layout.
18184     ProcessDeclAttributeList(S, Record, Attrs);
18185 
18186     // Check to see if a FieldDecl is a pointer to a function.
18187     auto IsFunctionPointer = [&](const Decl *D) {
18188       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18189       if (!FD)
18190         return false;
18191       QualType FieldType = FD->getType().getDesugaredType(Context);
18192       if (isa<PointerType>(FieldType)) {
18193         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18194         return PointeeType.getDesugaredType(Context)->isFunctionType();
18195       }
18196       return false;
18197     };
18198 
18199     // Maybe randomize the record's decls. We automatically randomize a record
18200     // of function pointers, unless it has the "no_randomize_layout" attribute.
18201     if (!getLangOpts().CPlusPlus &&
18202         (Record->hasAttr<RandomizeLayoutAttr>() ||
18203          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18204           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18205         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18206         !Record->isRandomized()) {
18207       SmallVector<Decl *, 32> NewDeclOrdering;
18208       if (randstruct::randomizeStructureLayout(Context, Record,
18209                                                NewDeclOrdering))
18210         Record->reorderDecls(NewDeclOrdering);
18211     }
18212 
18213     // We may have deferred checking for a deleted destructor. Check now.
18214     if (CXXRecord) {
18215       auto *Dtor = CXXRecord->getDestructor();
18216       if (Dtor && Dtor->isImplicit() &&
18217           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18218         CXXRecord->setImplicitDestructorIsDeleted();
18219         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18220       }
18221     }
18222 
18223     if (Record->hasAttrs()) {
18224       CheckAlignasUnderalignment(Record);
18225 
18226       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18227         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18228                                            IA->getRange(), IA->getBestCase(),
18229                                            IA->getInheritanceModel());
18230     }
18231 
18232     // Check if the structure/union declaration is a type that can have zero
18233     // size in C. For C this is a language extension, for C++ it may cause
18234     // compatibility problems.
18235     bool CheckForZeroSize;
18236     if (!getLangOpts().CPlusPlus) {
18237       CheckForZeroSize = true;
18238     } else {
18239       // For C++ filter out types that cannot be referenced in C code.
18240       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18241       CheckForZeroSize =
18242           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18243           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18244           CXXRecord->isCLike();
18245     }
18246     if (CheckForZeroSize) {
18247       bool ZeroSize = true;
18248       bool IsEmpty = true;
18249       unsigned NonBitFields = 0;
18250       for (RecordDecl::field_iterator I = Record->field_begin(),
18251                                       E = Record->field_end();
18252            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18253         IsEmpty = false;
18254         if (I->isUnnamedBitfield()) {
18255           if (!I->isZeroLengthBitField(Context))
18256             ZeroSize = false;
18257         } else {
18258           ++NonBitFields;
18259           QualType FieldType = I->getType();
18260           if (FieldType->isIncompleteType() ||
18261               !Context.getTypeSizeInChars(FieldType).isZero())
18262             ZeroSize = false;
18263         }
18264       }
18265 
18266       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18267       // allowed in C++, but warn if its declaration is inside
18268       // extern "C" block.
18269       if (ZeroSize) {
18270         Diag(RecLoc, getLangOpts().CPlusPlus ?
18271                          diag::warn_zero_size_struct_union_in_extern_c :
18272                          diag::warn_zero_size_struct_union_compat)
18273           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18274       }
18275 
18276       // Structs without named members are extension in C (C99 6.7.2.1p7),
18277       // but are accepted by GCC.
18278       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18279         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18280                                diag::ext_no_named_members_in_struct_union)
18281           << Record->isUnion();
18282       }
18283     }
18284   } else {
18285     ObjCIvarDecl **ClsFields =
18286       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18287     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18288       ID->setEndOfDefinitionLoc(RBrac);
18289       // Add ivar's to class's DeclContext.
18290       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18291         ClsFields[i]->setLexicalDeclContext(ID);
18292         ID->addDecl(ClsFields[i]);
18293       }
18294       // Must enforce the rule that ivars in the base classes may not be
18295       // duplicates.
18296       if (ID->getSuperClass())
18297         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18298     } else if (ObjCImplementationDecl *IMPDecl =
18299                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18300       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18301       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18302         // Ivar declared in @implementation never belongs to the implementation.
18303         // Only it is in implementation's lexical context.
18304         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18305       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18306       IMPDecl->setIvarLBraceLoc(LBrac);
18307       IMPDecl->setIvarRBraceLoc(RBrac);
18308     } else if (ObjCCategoryDecl *CDecl =
18309                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18310       // case of ivars in class extension; all other cases have been
18311       // reported as errors elsewhere.
18312       // FIXME. Class extension does not have a LocEnd field.
18313       // CDecl->setLocEnd(RBrac);
18314       // Add ivar's to class extension's DeclContext.
18315       // Diagnose redeclaration of private ivars.
18316       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18317       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18318         if (IDecl) {
18319           if (const ObjCIvarDecl *ClsIvar =
18320               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18321             Diag(ClsFields[i]->getLocation(),
18322                  diag::err_duplicate_ivar_declaration);
18323             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18324             continue;
18325           }
18326           for (const auto *Ext : IDecl->known_extensions()) {
18327             if (const ObjCIvarDecl *ClsExtIvar
18328                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18329               Diag(ClsFields[i]->getLocation(),
18330                    diag::err_duplicate_ivar_declaration);
18331               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18332               continue;
18333             }
18334           }
18335         }
18336         ClsFields[i]->setLexicalDeclContext(CDecl);
18337         CDecl->addDecl(ClsFields[i]);
18338       }
18339       CDecl->setIvarLBraceLoc(LBrac);
18340       CDecl->setIvarRBraceLoc(RBrac);
18341     }
18342   }
18343 }
18344 
18345 /// Determine whether the given integral value is representable within
18346 /// the given type T.
18347 static bool isRepresentableIntegerValue(ASTContext &Context,
18348                                         llvm::APSInt &Value,
18349                                         QualType T) {
18350   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18351          "Integral type required!");
18352   unsigned BitWidth = Context.getIntWidth(T);
18353 
18354   if (Value.isUnsigned() || Value.isNonNegative()) {
18355     if (T->isSignedIntegerOrEnumerationType())
18356       --BitWidth;
18357     return Value.getActiveBits() <= BitWidth;
18358   }
18359   return Value.getMinSignedBits() <= BitWidth;
18360 }
18361 
18362 // Given an integral type, return the next larger integral type
18363 // (or a NULL type of no such type exists).
18364 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18365   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18366   // enum checking below.
18367   assert((T->isIntegralType(Context) ||
18368          T->isEnumeralType()) && "Integral type required!");
18369   const unsigned NumTypes = 4;
18370   QualType SignedIntegralTypes[NumTypes] = {
18371     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18372   };
18373   QualType UnsignedIntegralTypes[NumTypes] = {
18374     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18375     Context.UnsignedLongLongTy
18376   };
18377 
18378   unsigned BitWidth = Context.getTypeSize(T);
18379   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18380                                                         : UnsignedIntegralTypes;
18381   for (unsigned I = 0; I != NumTypes; ++I)
18382     if (Context.getTypeSize(Types[I]) > BitWidth)
18383       return Types[I];
18384 
18385   return QualType();
18386 }
18387 
18388 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18389                                           EnumConstantDecl *LastEnumConst,
18390                                           SourceLocation IdLoc,
18391                                           IdentifierInfo *Id,
18392                                           Expr *Val) {
18393   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18394   llvm::APSInt EnumVal(IntWidth);
18395   QualType EltTy;
18396 
18397   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18398     Val = nullptr;
18399 
18400   if (Val)
18401     Val = DefaultLvalueConversion(Val).get();
18402 
18403   if (Val) {
18404     if (Enum->isDependentType() || Val->isTypeDependent() ||
18405         Val->containsErrors())
18406       EltTy = Context.DependentTy;
18407     else {
18408       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18409       // underlying type, but do allow it in all other contexts.
18410       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18411         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18412         // constant-expression in the enumerator-definition shall be a converted
18413         // constant expression of the underlying type.
18414         EltTy = Enum->getIntegerType();
18415         ExprResult Converted =
18416           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18417                                            CCEK_Enumerator);
18418         if (Converted.isInvalid())
18419           Val = nullptr;
18420         else
18421           Val = Converted.get();
18422       } else if (!Val->isValueDependent() &&
18423                  !(Val =
18424                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18425                            .get())) {
18426         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18427       } else {
18428         if (Enum->isComplete()) {
18429           EltTy = Enum->getIntegerType();
18430 
18431           // In Obj-C and Microsoft mode, require the enumeration value to be
18432           // representable in the underlying type of the enumeration. In C++11,
18433           // we perform a non-narrowing conversion as part of converted constant
18434           // expression checking.
18435           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18436             if (Context.getTargetInfo()
18437                     .getTriple()
18438                     .isWindowsMSVCEnvironment()) {
18439               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18440             } else {
18441               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18442             }
18443           }
18444 
18445           // Cast to the underlying type.
18446           Val = ImpCastExprToType(Val, EltTy,
18447                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18448                                                          : CK_IntegralCast)
18449                     .get();
18450         } else if (getLangOpts().CPlusPlus) {
18451           // C++11 [dcl.enum]p5:
18452           //   If the underlying type is not fixed, the type of each enumerator
18453           //   is the type of its initializing value:
18454           //     - If an initializer is specified for an enumerator, the
18455           //       initializing value has the same type as the expression.
18456           EltTy = Val->getType();
18457         } else {
18458           // C99 6.7.2.2p2:
18459           //   The expression that defines the value of an enumeration constant
18460           //   shall be an integer constant expression that has a value
18461           //   representable as an int.
18462 
18463           // Complain if the value is not representable in an int.
18464           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18465             Diag(IdLoc, diag::ext_enum_value_not_int)
18466               << toString(EnumVal, 10) << Val->getSourceRange()
18467               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18468           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18469             // Force the type of the expression to 'int'.
18470             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18471           }
18472           EltTy = Val->getType();
18473         }
18474       }
18475     }
18476   }
18477 
18478   if (!Val) {
18479     if (Enum->isDependentType())
18480       EltTy = Context.DependentTy;
18481     else if (!LastEnumConst) {
18482       // C++0x [dcl.enum]p5:
18483       //   If the underlying type is not fixed, the type of each enumerator
18484       //   is the type of its initializing value:
18485       //     - If no initializer is specified for the first enumerator, the
18486       //       initializing value has an unspecified integral type.
18487       //
18488       // GCC uses 'int' for its unspecified integral type, as does
18489       // C99 6.7.2.2p3.
18490       if (Enum->isFixed()) {
18491         EltTy = Enum->getIntegerType();
18492       }
18493       else {
18494         EltTy = Context.IntTy;
18495       }
18496     } else {
18497       // Assign the last value + 1.
18498       EnumVal = LastEnumConst->getInitVal();
18499       ++EnumVal;
18500       EltTy = LastEnumConst->getType();
18501 
18502       // Check for overflow on increment.
18503       if (EnumVal < LastEnumConst->getInitVal()) {
18504         // C++0x [dcl.enum]p5:
18505         //   If the underlying type is not fixed, the type of each enumerator
18506         //   is the type of its initializing value:
18507         //
18508         //     - Otherwise the type of the initializing value is the same as
18509         //       the type of the initializing value of the preceding enumerator
18510         //       unless the incremented value is not representable in that type,
18511         //       in which case the type is an unspecified integral type
18512         //       sufficient to contain the incremented value. If no such type
18513         //       exists, the program is ill-formed.
18514         QualType T = getNextLargerIntegralType(Context, EltTy);
18515         if (T.isNull() || Enum->isFixed()) {
18516           // There is no integral type larger enough to represent this
18517           // value. Complain, then allow the value to wrap around.
18518           EnumVal = LastEnumConst->getInitVal();
18519           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18520           ++EnumVal;
18521           if (Enum->isFixed())
18522             // When the underlying type is fixed, this is ill-formed.
18523             Diag(IdLoc, diag::err_enumerator_wrapped)
18524               << toString(EnumVal, 10)
18525               << EltTy;
18526           else
18527             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18528               << toString(EnumVal, 10);
18529         } else {
18530           EltTy = T;
18531         }
18532 
18533         // Retrieve the last enumerator's value, extent that type to the
18534         // type that is supposed to be large enough to represent the incremented
18535         // value, then increment.
18536         EnumVal = LastEnumConst->getInitVal();
18537         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18538         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18539         ++EnumVal;
18540 
18541         // If we're not in C++, diagnose the overflow of enumerator values,
18542         // which in C99 means that the enumerator value is not representable in
18543         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18544         // permits enumerator values that are representable in some larger
18545         // integral type.
18546         if (!getLangOpts().CPlusPlus && !T.isNull())
18547           Diag(IdLoc, diag::warn_enum_value_overflow);
18548       } else if (!getLangOpts().CPlusPlus &&
18549                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18550         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18551         Diag(IdLoc, diag::ext_enum_value_not_int)
18552           << toString(EnumVal, 10) << 1;
18553       }
18554     }
18555   }
18556 
18557   if (!EltTy->isDependentType()) {
18558     // Make the enumerator value match the signedness and size of the
18559     // enumerator's type.
18560     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18561     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18562   }
18563 
18564   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18565                                   Val, EnumVal);
18566 }
18567 
18568 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18569                                                 SourceLocation IILoc) {
18570   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18571       !getLangOpts().CPlusPlus)
18572     return SkipBodyInfo();
18573 
18574   // We have an anonymous enum definition. Look up the first enumerator to
18575   // determine if we should merge the definition with an existing one and
18576   // skip the body.
18577   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18578                                          forRedeclarationInCurContext());
18579   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18580   if (!PrevECD)
18581     return SkipBodyInfo();
18582 
18583   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18584   NamedDecl *Hidden;
18585   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18586     SkipBodyInfo Skip;
18587     Skip.Previous = Hidden;
18588     return Skip;
18589   }
18590 
18591   return SkipBodyInfo();
18592 }
18593 
18594 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18595                               SourceLocation IdLoc, IdentifierInfo *Id,
18596                               const ParsedAttributesView &Attrs,
18597                               SourceLocation EqualLoc, Expr *Val) {
18598   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18599   EnumConstantDecl *LastEnumConst =
18600     cast_or_null<EnumConstantDecl>(lastEnumConst);
18601 
18602   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18603   // we find one that is.
18604   S = getNonFieldDeclScope(S);
18605 
18606   // Verify that there isn't already something declared with this name in this
18607   // scope.
18608   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18609   LookupName(R, S);
18610   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18611 
18612   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18613     // Maybe we will complain about the shadowed template parameter.
18614     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18615     // Just pretend that we didn't see the previous declaration.
18616     PrevDecl = nullptr;
18617   }
18618 
18619   // C++ [class.mem]p15:
18620   // If T is the name of a class, then each of the following shall have a name
18621   // different from T:
18622   // - every enumerator of every member of class T that is an unscoped
18623   // enumerated type
18624   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18625     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18626                             DeclarationNameInfo(Id, IdLoc));
18627 
18628   EnumConstantDecl *New =
18629     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18630   if (!New)
18631     return nullptr;
18632 
18633   if (PrevDecl) {
18634     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18635       // Check for other kinds of shadowing not already handled.
18636       CheckShadow(New, PrevDecl, R);
18637     }
18638 
18639     // When in C++, we may get a TagDecl with the same name; in this case the
18640     // enum constant will 'hide' the tag.
18641     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18642            "Received TagDecl when not in C++!");
18643     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18644       if (isa<EnumConstantDecl>(PrevDecl))
18645         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18646       else
18647         Diag(IdLoc, diag::err_redefinition) << Id;
18648       notePreviousDefinition(PrevDecl, IdLoc);
18649       return nullptr;
18650     }
18651   }
18652 
18653   // Process attributes.
18654   ProcessDeclAttributeList(S, New, Attrs);
18655   AddPragmaAttributes(S, New);
18656 
18657   // Register this decl in the current scope stack.
18658   New->setAccess(TheEnumDecl->getAccess());
18659   PushOnScopeChains(New, S);
18660 
18661   ActOnDocumentableDecl(New);
18662 
18663   return New;
18664 }
18665 
18666 // Returns true when the enum initial expression does not trigger the
18667 // duplicate enum warning.  A few common cases are exempted as follows:
18668 // Element2 = Element1
18669 // Element2 = Element1 + 1
18670 // Element2 = Element1 - 1
18671 // Where Element2 and Element1 are from the same enum.
18672 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18673   Expr *InitExpr = ECD->getInitExpr();
18674   if (!InitExpr)
18675     return true;
18676   InitExpr = InitExpr->IgnoreImpCasts();
18677 
18678   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18679     if (!BO->isAdditiveOp())
18680       return true;
18681     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18682     if (!IL)
18683       return true;
18684     if (IL->getValue() != 1)
18685       return true;
18686 
18687     InitExpr = BO->getLHS();
18688   }
18689 
18690   // This checks if the elements are from the same enum.
18691   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18692   if (!DRE)
18693     return true;
18694 
18695   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18696   if (!EnumConstant)
18697     return true;
18698 
18699   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18700       Enum)
18701     return true;
18702 
18703   return false;
18704 }
18705 
18706 // Emits a warning when an element is implicitly set a value that
18707 // a previous element has already been set to.
18708 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18709                                         EnumDecl *Enum, QualType EnumType) {
18710   // Avoid anonymous enums
18711   if (!Enum->getIdentifier())
18712     return;
18713 
18714   // Only check for small enums.
18715   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18716     return;
18717 
18718   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18719     return;
18720 
18721   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18722   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18723 
18724   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18725 
18726   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18727   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18728 
18729   // Use int64_t as a key to avoid needing special handling for map keys.
18730   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18731     llvm::APSInt Val = D->getInitVal();
18732     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18733   };
18734 
18735   DuplicatesVector DupVector;
18736   ValueToVectorMap EnumMap;
18737 
18738   // Populate the EnumMap with all values represented by enum constants without
18739   // an initializer.
18740   for (auto *Element : Elements) {
18741     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18742 
18743     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18744     // this constant.  Skip this enum since it may be ill-formed.
18745     if (!ECD) {
18746       return;
18747     }
18748 
18749     // Constants with initalizers are handled in the next loop.
18750     if (ECD->getInitExpr())
18751       continue;
18752 
18753     // Duplicate values are handled in the next loop.
18754     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18755   }
18756 
18757   if (EnumMap.size() == 0)
18758     return;
18759 
18760   // Create vectors for any values that has duplicates.
18761   for (auto *Element : Elements) {
18762     // The last loop returned if any constant was null.
18763     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18764     if (!ValidDuplicateEnum(ECD, Enum))
18765       continue;
18766 
18767     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18768     if (Iter == EnumMap.end())
18769       continue;
18770 
18771     DeclOrVector& Entry = Iter->second;
18772     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18773       // Ensure constants are different.
18774       if (D == ECD)
18775         continue;
18776 
18777       // Create new vector and push values onto it.
18778       auto Vec = std::make_unique<ECDVector>();
18779       Vec->push_back(D);
18780       Vec->push_back(ECD);
18781 
18782       // Update entry to point to the duplicates vector.
18783       Entry = Vec.get();
18784 
18785       // Store the vector somewhere we can consult later for quick emission of
18786       // diagnostics.
18787       DupVector.emplace_back(std::move(Vec));
18788       continue;
18789     }
18790 
18791     ECDVector *Vec = Entry.get<ECDVector*>();
18792     // Make sure constants are not added more than once.
18793     if (*Vec->begin() == ECD)
18794       continue;
18795 
18796     Vec->push_back(ECD);
18797   }
18798 
18799   // Emit diagnostics.
18800   for (const auto &Vec : DupVector) {
18801     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18802 
18803     // Emit warning for one enum constant.
18804     auto *FirstECD = Vec->front();
18805     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18806       << FirstECD << toString(FirstECD->getInitVal(), 10)
18807       << FirstECD->getSourceRange();
18808 
18809     // Emit one note for each of the remaining enum constants with
18810     // the same value.
18811     for (auto *ECD : llvm::drop_begin(*Vec))
18812       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18813         << ECD << toString(ECD->getInitVal(), 10)
18814         << ECD->getSourceRange();
18815   }
18816 }
18817 
18818 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18819                              bool AllowMask) const {
18820   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18821   assert(ED->isCompleteDefinition() && "expected enum definition");
18822 
18823   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18824   llvm::APInt &FlagBits = R.first->second;
18825 
18826   if (R.second) {
18827     for (auto *E : ED->enumerators()) {
18828       const auto &EVal = E->getInitVal();
18829       // Only single-bit enumerators introduce new flag values.
18830       if (EVal.isPowerOf2())
18831         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18832     }
18833   }
18834 
18835   // A value is in a flag enum if either its bits are a subset of the enum's
18836   // flag bits (the first condition) or we are allowing masks and the same is
18837   // true of its complement (the second condition). When masks are allowed, we
18838   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18839   //
18840   // While it's true that any value could be used as a mask, the assumption is
18841   // that a mask will have all of the insignificant bits set. Anything else is
18842   // likely a logic error.
18843   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18844   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18845 }
18846 
18847 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18848                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18849                          const ParsedAttributesView &Attrs) {
18850   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18851   QualType EnumType = Context.getTypeDeclType(Enum);
18852 
18853   ProcessDeclAttributeList(S, Enum, Attrs);
18854 
18855   if (Enum->isDependentType()) {
18856     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18857       EnumConstantDecl *ECD =
18858         cast_or_null<EnumConstantDecl>(Elements[i]);
18859       if (!ECD) continue;
18860 
18861       ECD->setType(EnumType);
18862     }
18863 
18864     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18865     return;
18866   }
18867 
18868   // TODO: If the result value doesn't fit in an int, it must be a long or long
18869   // long value.  ISO C does not support this, but GCC does as an extension,
18870   // emit a warning.
18871   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18872   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18873   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18874 
18875   // Verify that all the values are okay, compute the size of the values, and
18876   // reverse the list.
18877   unsigned NumNegativeBits = 0;
18878   unsigned NumPositiveBits = 0;
18879 
18880   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18881     EnumConstantDecl *ECD =
18882       cast_or_null<EnumConstantDecl>(Elements[i]);
18883     if (!ECD) continue;  // Already issued a diagnostic.
18884 
18885     const llvm::APSInt &InitVal = ECD->getInitVal();
18886 
18887     // Keep track of the size of positive and negative values.
18888     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18889       NumPositiveBits = std::max(NumPositiveBits,
18890                                  (unsigned)InitVal.getActiveBits());
18891     else
18892       NumNegativeBits = std::max(NumNegativeBits,
18893                                  (unsigned)InitVal.getMinSignedBits());
18894   }
18895 
18896   // Figure out the type that should be used for this enum.
18897   QualType BestType;
18898   unsigned BestWidth;
18899 
18900   // C++0x N3000 [conv.prom]p3:
18901   //   An rvalue of an unscoped enumeration type whose underlying
18902   //   type is not fixed can be converted to an rvalue of the first
18903   //   of the following types that can represent all the values of
18904   //   the enumeration: int, unsigned int, long int, unsigned long
18905   //   int, long long int, or unsigned long long int.
18906   // C99 6.4.4.3p2:
18907   //   An identifier declared as an enumeration constant has type int.
18908   // The C99 rule is modified by a gcc extension
18909   QualType BestPromotionType;
18910 
18911   bool Packed = Enum->hasAttr<PackedAttr>();
18912   // -fshort-enums is the equivalent to specifying the packed attribute on all
18913   // enum definitions.
18914   if (LangOpts.ShortEnums)
18915     Packed = true;
18916 
18917   // If the enum already has a type because it is fixed or dictated by the
18918   // target, promote that type instead of analyzing the enumerators.
18919   if (Enum->isComplete()) {
18920     BestType = Enum->getIntegerType();
18921     if (BestType->isPromotableIntegerType())
18922       BestPromotionType = Context.getPromotedIntegerType(BestType);
18923     else
18924       BestPromotionType = BestType;
18925 
18926     BestWidth = Context.getIntWidth(BestType);
18927   }
18928   else if (NumNegativeBits) {
18929     // If there is a negative value, figure out the smallest integer type (of
18930     // int/long/longlong) that fits.
18931     // If it's packed, check also if it fits a char or a short.
18932     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18933       BestType = Context.SignedCharTy;
18934       BestWidth = CharWidth;
18935     } else if (Packed && NumNegativeBits <= ShortWidth &&
18936                NumPositiveBits < ShortWidth) {
18937       BestType = Context.ShortTy;
18938       BestWidth = ShortWidth;
18939     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18940       BestType = Context.IntTy;
18941       BestWidth = IntWidth;
18942     } else {
18943       BestWidth = Context.getTargetInfo().getLongWidth();
18944 
18945       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18946         BestType = Context.LongTy;
18947       } else {
18948         BestWidth = Context.getTargetInfo().getLongLongWidth();
18949 
18950         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18951           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18952         BestType = Context.LongLongTy;
18953       }
18954     }
18955     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18956   } else {
18957     // If there is no negative value, figure out the smallest type that fits
18958     // all of the enumerator values.
18959     // If it's packed, check also if it fits a char or a short.
18960     if (Packed && NumPositiveBits <= CharWidth) {
18961       BestType = Context.UnsignedCharTy;
18962       BestPromotionType = Context.IntTy;
18963       BestWidth = CharWidth;
18964     } else if (Packed && NumPositiveBits <= ShortWidth) {
18965       BestType = Context.UnsignedShortTy;
18966       BestPromotionType = Context.IntTy;
18967       BestWidth = ShortWidth;
18968     } else if (NumPositiveBits <= IntWidth) {
18969       BestType = Context.UnsignedIntTy;
18970       BestWidth = IntWidth;
18971       BestPromotionType
18972         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18973                            ? Context.UnsignedIntTy : Context.IntTy;
18974     } else if (NumPositiveBits <=
18975                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18976       BestType = Context.UnsignedLongTy;
18977       BestPromotionType
18978         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18979                            ? Context.UnsignedLongTy : Context.LongTy;
18980     } else {
18981       BestWidth = Context.getTargetInfo().getLongLongWidth();
18982       assert(NumPositiveBits <= BestWidth &&
18983              "How could an initializer get larger than ULL?");
18984       BestType = Context.UnsignedLongLongTy;
18985       BestPromotionType
18986         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18987                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18988     }
18989   }
18990 
18991   // Loop over all of the enumerator constants, changing their types to match
18992   // the type of the enum if needed.
18993   for (auto *D : Elements) {
18994     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18995     if (!ECD) continue;  // Already issued a diagnostic.
18996 
18997     // Standard C says the enumerators have int type, but we allow, as an
18998     // extension, the enumerators to be larger than int size.  If each
18999     // enumerator value fits in an int, type it as an int, otherwise type it the
19000     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
19001     // that X has type 'int', not 'unsigned'.
19002 
19003     // Determine whether the value fits into an int.
19004     llvm::APSInt InitVal = ECD->getInitVal();
19005 
19006     // If it fits into an integer type, force it.  Otherwise force it to match
19007     // the enum decl type.
19008     QualType NewTy;
19009     unsigned NewWidth;
19010     bool NewSign;
19011     if (!getLangOpts().CPlusPlus &&
19012         !Enum->isFixed() &&
19013         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19014       NewTy = Context.IntTy;
19015       NewWidth = IntWidth;
19016       NewSign = true;
19017     } else if (ECD->getType() == BestType) {
19018       // Already the right type!
19019       if (getLangOpts().CPlusPlus)
19020         // C++ [dcl.enum]p4: Following the closing brace of an
19021         // enum-specifier, each enumerator has the type of its
19022         // enumeration.
19023         ECD->setType(EnumType);
19024       continue;
19025     } else {
19026       NewTy = BestType;
19027       NewWidth = BestWidth;
19028       NewSign = BestType->isSignedIntegerOrEnumerationType();
19029     }
19030 
19031     // Adjust the APSInt value.
19032     InitVal = InitVal.extOrTrunc(NewWidth);
19033     InitVal.setIsSigned(NewSign);
19034     ECD->setInitVal(InitVal);
19035 
19036     // Adjust the Expr initializer and type.
19037     if (ECD->getInitExpr() &&
19038         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19039       ECD->setInitExpr(ImplicitCastExpr::Create(
19040           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19041           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19042     if (getLangOpts().CPlusPlus)
19043       // C++ [dcl.enum]p4: Following the closing brace of an
19044       // enum-specifier, each enumerator has the type of its
19045       // enumeration.
19046       ECD->setType(EnumType);
19047     else
19048       ECD->setType(NewTy);
19049   }
19050 
19051   Enum->completeDefinition(BestType, BestPromotionType,
19052                            NumPositiveBits, NumNegativeBits);
19053 
19054   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19055 
19056   if (Enum->isClosedFlag()) {
19057     for (Decl *D : Elements) {
19058       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19059       if (!ECD) continue;  // Already issued a diagnostic.
19060 
19061       llvm::APSInt InitVal = ECD->getInitVal();
19062       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19063           !IsValueInFlagEnum(Enum, InitVal, true))
19064         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19065           << ECD << Enum;
19066     }
19067   }
19068 
19069   // Now that the enum type is defined, ensure it's not been underaligned.
19070   if (Enum->hasAttrs())
19071     CheckAlignasUnderalignment(Enum);
19072 }
19073 
19074 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19075                                   SourceLocation StartLoc,
19076                                   SourceLocation EndLoc) {
19077   StringLiteral *AsmString = cast<StringLiteral>(expr);
19078 
19079   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19080                                                    AsmString, StartLoc,
19081                                                    EndLoc);
19082   CurContext->addDecl(New);
19083   return New;
19084 }
19085 
19086 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19087                                       IdentifierInfo* AliasName,
19088                                       SourceLocation PragmaLoc,
19089                                       SourceLocation NameLoc,
19090                                       SourceLocation AliasNameLoc) {
19091   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19092                                          LookupOrdinaryName);
19093   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19094                            AttributeCommonInfo::AS_Pragma);
19095   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19096       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19097 
19098   // If a declaration that:
19099   // 1) declares a function or a variable
19100   // 2) has external linkage
19101   // already exists, add a label attribute to it.
19102   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19103     if (isDeclExternC(PrevDecl))
19104       PrevDecl->addAttr(Attr);
19105     else
19106       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19107           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19108   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19109   } else
19110     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19111 }
19112 
19113 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19114                              SourceLocation PragmaLoc,
19115                              SourceLocation NameLoc) {
19116   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19117 
19118   if (PrevDecl) {
19119     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19120   } else {
19121     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19122   }
19123 }
19124 
19125 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19126                                 IdentifierInfo* AliasName,
19127                                 SourceLocation PragmaLoc,
19128                                 SourceLocation NameLoc,
19129                                 SourceLocation AliasNameLoc) {
19130   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19131                                     LookupOrdinaryName);
19132   WeakInfo W = WeakInfo(Name, NameLoc);
19133 
19134   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19135     if (!PrevDecl->hasAttr<AliasAttr>())
19136       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19137         DeclApplyPragmaWeak(TUScope, ND, W);
19138   } else {
19139     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19140   }
19141 }
19142 
19143 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19144   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19145 }
19146 
19147 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19148                                                      bool Final) {
19149   assert(FD && "Expected non-null FunctionDecl");
19150 
19151   // SYCL functions can be template, so we check if they have appropriate
19152   // attribute prior to checking if it is a template.
19153   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19154     return FunctionEmissionStatus::Emitted;
19155 
19156   // Templates are emitted when they're instantiated.
19157   if (FD->isDependentContext())
19158     return FunctionEmissionStatus::TemplateDiscarded;
19159 
19160   // Check whether this function is an externally visible definition.
19161   auto IsEmittedForExternalSymbol = [this, FD]() {
19162     // We have to check the GVA linkage of the function's *definition* -- if we
19163     // only have a declaration, we don't know whether or not the function will
19164     // be emitted, because (say) the definition could include "inline".
19165     FunctionDecl *Def = FD->getDefinition();
19166 
19167     return Def && !isDiscardableGVALinkage(
19168                       getASTContext().GetGVALinkageForFunction(Def));
19169   };
19170 
19171   if (LangOpts.OpenMPIsDevice) {
19172     // In OpenMP device mode we will not emit host only functions, or functions
19173     // we don't need due to their linkage.
19174     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19175         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19176     // DevTy may be changed later by
19177     //  #pragma omp declare target to(*) device_type(*).
19178     // Therefore DevTy having no value does not imply host. The emission status
19179     // will be checked again at the end of compilation unit with Final = true.
19180     if (DevTy)
19181       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19182         return FunctionEmissionStatus::OMPDiscarded;
19183     // If we have an explicit value for the device type, or we are in a target
19184     // declare context, we need to emit all extern and used symbols.
19185     if (isInOpenMPDeclareTargetContext() || DevTy)
19186       if (IsEmittedForExternalSymbol())
19187         return FunctionEmissionStatus::Emitted;
19188     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19189     // we'll omit it.
19190     if (Final)
19191       return FunctionEmissionStatus::OMPDiscarded;
19192   } else if (LangOpts.OpenMP > 45) {
19193     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19194     // function. In 5.0, no_host was introduced which might cause a function to
19195     // be ommitted.
19196     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19197         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19198     if (DevTy)
19199       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19200         return FunctionEmissionStatus::OMPDiscarded;
19201   }
19202 
19203   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19204     return FunctionEmissionStatus::Emitted;
19205 
19206   if (LangOpts.CUDA) {
19207     // When compiling for device, host functions are never emitted.  Similarly,
19208     // when compiling for host, device and global functions are never emitted.
19209     // (Technically, we do emit a host-side stub for global functions, but this
19210     // doesn't count for our purposes here.)
19211     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19212     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19213       return FunctionEmissionStatus::CUDADiscarded;
19214     if (!LangOpts.CUDAIsDevice &&
19215         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19216       return FunctionEmissionStatus::CUDADiscarded;
19217 
19218     if (IsEmittedForExternalSymbol())
19219       return FunctionEmissionStatus::Emitted;
19220   }
19221 
19222   // Otherwise, the function is known-emitted if it's in our set of
19223   // known-emitted functions.
19224   return FunctionEmissionStatus::Unknown;
19225 }
19226 
19227 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19228   // Host-side references to a __global__ function refer to the stub, so the
19229   // function itself is never emitted and therefore should not be marked.
19230   // If we have host fn calls kernel fn calls host+device, the HD function
19231   // does not get instantiated on the host. We model this by omitting at the
19232   // call to the kernel from the callgraph. This ensures that, when compiling
19233   // for host, only HD functions actually called from the host get marked as
19234   // known-emitted.
19235   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19236          IdentifyCUDATarget(Callee) == CFT_Global;
19237 }
19238