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 
3241   // Don't try to compare dependent sized array
3242   if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3243     return true;
3244   }
3245 
3246   return Old == New;
3247 }
3248 
3249 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3250                                 const ParmVarDecl *OldParam,
3251                                 Sema &S) {
3252   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3253     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3254       if (*Oldnullability != *Newnullability) {
3255         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3256           << DiagNullabilityKind(
3257                *Newnullability,
3258                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3259                 != 0))
3260           << DiagNullabilityKind(
3261                *Oldnullability,
3262                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3263                 != 0));
3264         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3265       }
3266     } else {
3267       QualType NewT = NewParam->getType();
3268       NewT = S.Context.getAttributedType(
3269                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3270                          NewT, NewT);
3271       NewParam->setType(NewT);
3272     }
3273   }
3274   const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3275   const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3276   if (OldParamDT && NewParamDT &&
3277       OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3278     QualType OldParamOT = OldParamDT->getOriginalType();
3279     QualType NewParamOT = NewParamDT->getOriginalType();
3280     if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3281       S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3282           << NewParam << NewParamOT;
3283       S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3284           << OldParamOT;
3285     }
3286   }
3287 }
3288 
3289 namespace {
3290 
3291 /// Used in MergeFunctionDecl to keep track of function parameters in
3292 /// C.
3293 struct GNUCompatibleParamWarning {
3294   ParmVarDecl *OldParm;
3295   ParmVarDecl *NewParm;
3296   QualType PromotedType;
3297 };
3298 
3299 } // end anonymous namespace
3300 
3301 // Determine whether the previous declaration was a definition, implicit
3302 // declaration, or a declaration.
3303 template <typename T>
3304 static std::pair<diag::kind, SourceLocation>
3305 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3306   diag::kind PrevDiag;
3307   SourceLocation OldLocation = Old->getLocation();
3308   if (Old->isThisDeclarationADefinition())
3309     PrevDiag = diag::note_previous_definition;
3310   else if (Old->isImplicit()) {
3311     PrevDiag = diag::note_previous_implicit_declaration;
3312     if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3313       if (FD->getBuiltinID())
3314         PrevDiag = diag::note_previous_builtin_declaration;
3315     }
3316     if (OldLocation.isInvalid())
3317       OldLocation = New->getLocation();
3318   } else
3319     PrevDiag = diag::note_previous_declaration;
3320   return std::make_pair(PrevDiag, OldLocation);
3321 }
3322 
3323 /// canRedefineFunction - checks if a function can be redefined. Currently,
3324 /// only extern inline functions can be redefined, and even then only in
3325 /// GNU89 mode.
3326 static bool canRedefineFunction(const FunctionDecl *FD,
3327                                 const LangOptions& LangOpts) {
3328   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3329           !LangOpts.CPlusPlus &&
3330           FD->isInlineSpecified() &&
3331           FD->getStorageClass() == SC_Extern);
3332 }
3333 
3334 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3335   const AttributedType *AT = T->getAs<AttributedType>();
3336   while (AT && !AT->isCallingConv())
3337     AT = AT->getModifiedType()->getAs<AttributedType>();
3338   return AT;
3339 }
3340 
3341 template <typename T>
3342 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3343   const DeclContext *DC = Old->getDeclContext();
3344   if (DC->isRecord())
3345     return false;
3346 
3347   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3348   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3349     return true;
3350   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3351     return true;
3352   return false;
3353 }
3354 
3355 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3356 static bool isExternC(VarTemplateDecl *) { return false; }
3357 static bool isExternC(FunctionTemplateDecl *) { return false; }
3358 
3359 /// Check whether a redeclaration of an entity introduced by a
3360 /// using-declaration is valid, given that we know it's not an overload
3361 /// (nor a hidden tag declaration).
3362 template<typename ExpectedDecl>
3363 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3364                                    ExpectedDecl *New) {
3365   // C++11 [basic.scope.declarative]p4:
3366   //   Given a set of declarations in a single declarative region, each of
3367   //   which specifies the same unqualified name,
3368   //   -- they shall all refer to the same entity, or all refer to functions
3369   //      and function templates; or
3370   //   -- exactly one declaration shall declare a class name or enumeration
3371   //      name that is not a typedef name and the other declarations shall all
3372   //      refer to the same variable or enumerator, or all refer to functions
3373   //      and function templates; in this case the class name or enumeration
3374   //      name is hidden (3.3.10).
3375 
3376   // C++11 [namespace.udecl]p14:
3377   //   If a function declaration in namespace scope or block scope has the
3378   //   same name and the same parameter-type-list as a function introduced
3379   //   by a using-declaration, and the declarations do not declare the same
3380   //   function, the program is ill-formed.
3381 
3382   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3383   if (Old &&
3384       !Old->getDeclContext()->getRedeclContext()->Equals(
3385           New->getDeclContext()->getRedeclContext()) &&
3386       !(isExternC(Old) && isExternC(New)))
3387     Old = nullptr;
3388 
3389   if (!Old) {
3390     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3391     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3392     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3393     return true;
3394   }
3395   return false;
3396 }
3397 
3398 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3399                                             const FunctionDecl *B) {
3400   assert(A->getNumParams() == B->getNumParams());
3401 
3402   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3403     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3404     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3405     if (AttrA == AttrB)
3406       return true;
3407     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3408            AttrA->isDynamic() == AttrB->isDynamic();
3409   };
3410 
3411   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3412 }
3413 
3414 /// If necessary, adjust the semantic declaration context for a qualified
3415 /// declaration to name the correct inline namespace within the qualifier.
3416 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3417                                                DeclaratorDecl *OldD) {
3418   // The only case where we need to update the DeclContext is when
3419   // redeclaration lookup for a qualified name finds a declaration
3420   // in an inline namespace within the context named by the qualifier:
3421   //
3422   //   inline namespace N { int f(); }
3423   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3424   //
3425   // For unqualified declarations, the semantic context *can* change
3426   // along the redeclaration chain (for local extern declarations,
3427   // extern "C" declarations, and friend declarations in particular).
3428   if (!NewD->getQualifier())
3429     return;
3430 
3431   // NewD is probably already in the right context.
3432   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3433   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3434   if (NamedDC->Equals(SemaDC))
3435     return;
3436 
3437   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3438           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3439          "unexpected context for redeclaration");
3440 
3441   auto *LexDC = NewD->getLexicalDeclContext();
3442   auto FixSemaDC = [=](NamedDecl *D) {
3443     if (!D)
3444       return;
3445     D->setDeclContext(SemaDC);
3446     D->setLexicalDeclContext(LexDC);
3447   };
3448 
3449   FixSemaDC(NewD);
3450   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3451     FixSemaDC(FD->getDescribedFunctionTemplate());
3452   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3453     FixSemaDC(VD->getDescribedVarTemplate());
3454 }
3455 
3456 /// MergeFunctionDecl - We just parsed a function 'New' from
3457 /// declarator D which has the same name and scope as a previous
3458 /// declaration 'Old'.  Figure out how to resolve this situation,
3459 /// merging decls or emitting diagnostics as appropriate.
3460 ///
3461 /// In C++, New and Old must be declarations that are not
3462 /// overloaded. Use IsOverload to determine whether New and Old are
3463 /// overloaded, and to select the Old declaration that New should be
3464 /// merged with.
3465 ///
3466 /// Returns true if there was an error, false otherwise.
3467 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3468                              bool MergeTypeWithOld, bool NewDeclIsDefn) {
3469   // Verify the old decl was also a function.
3470   FunctionDecl *Old = OldD->getAsFunction();
3471   if (!Old) {
3472     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3473       if (New->getFriendObjectKind()) {
3474         Diag(New->getLocation(), diag::err_using_decl_friend);
3475         Diag(Shadow->getTargetDecl()->getLocation(),
3476              diag::note_using_decl_target);
3477         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3478             << 0;
3479         return true;
3480       }
3481 
3482       // Check whether the two declarations might declare the same function or
3483       // function template.
3484       if (FunctionTemplateDecl *NewTemplate =
3485               New->getDescribedFunctionTemplate()) {
3486         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3487                                                          NewTemplate))
3488           return true;
3489         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3490                          ->getAsFunction();
3491       } else {
3492         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3493           return true;
3494         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3495       }
3496     } else {
3497       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3498         << New->getDeclName();
3499       notePreviousDefinition(OldD, New->getLocation());
3500       return true;
3501     }
3502   }
3503 
3504   // If the old declaration was found in an inline namespace and the new
3505   // declaration was qualified, update the DeclContext to match.
3506   adjustDeclContextForDeclaratorDecl(New, Old);
3507 
3508   // If the old declaration is invalid, just give up here.
3509   if (Old->isInvalidDecl())
3510     return true;
3511 
3512   // Disallow redeclaration of some builtins.
3513   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3514     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3515     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3516         << Old << Old->getType();
3517     return true;
3518   }
3519 
3520   diag::kind PrevDiag;
3521   SourceLocation OldLocation;
3522   std::tie(PrevDiag, OldLocation) =
3523       getNoteDiagForInvalidRedeclaration(Old, New);
3524 
3525   // Don't complain about this if we're in GNU89 mode and the old function
3526   // is an extern inline function.
3527   // Don't complain about specializations. They are not supposed to have
3528   // storage classes.
3529   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3530       New->getStorageClass() == SC_Static &&
3531       Old->hasExternalFormalLinkage() &&
3532       !New->getTemplateSpecializationInfo() &&
3533       !canRedefineFunction(Old, getLangOpts())) {
3534     if (getLangOpts().MicrosoftExt) {
3535       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3536       Diag(OldLocation, PrevDiag);
3537     } else {
3538       Diag(New->getLocation(), diag::err_static_non_static) << New;
3539       Diag(OldLocation, PrevDiag);
3540       return true;
3541     }
3542   }
3543 
3544   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3545     if (!Old->hasAttr<InternalLinkageAttr>()) {
3546       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3547           << ILA;
3548       Diag(Old->getLocation(), diag::note_previous_declaration);
3549       New->dropAttr<InternalLinkageAttr>();
3550     }
3551 
3552   if (auto *EA = New->getAttr<ErrorAttr>()) {
3553     if (!Old->hasAttr<ErrorAttr>()) {
3554       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3555       Diag(Old->getLocation(), diag::note_previous_declaration);
3556       New->dropAttr<ErrorAttr>();
3557     }
3558   }
3559 
3560   if (CheckRedeclarationInModule(New, Old))
3561     return true;
3562 
3563   if (!getLangOpts().CPlusPlus) {
3564     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3565     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3566       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3567         << New << OldOvl;
3568 
3569       // Try our best to find a decl that actually has the overloadable
3570       // attribute for the note. In most cases (e.g. programs with only one
3571       // broken declaration/definition), this won't matter.
3572       //
3573       // FIXME: We could do this if we juggled some extra state in
3574       // OverloadableAttr, rather than just removing it.
3575       const Decl *DiagOld = Old;
3576       if (OldOvl) {
3577         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3578           const auto *A = D->getAttr<OverloadableAttr>();
3579           return A && !A->isImplicit();
3580         });
3581         // If we've implicitly added *all* of the overloadable attrs to this
3582         // chain, emitting a "previous redecl" note is pointless.
3583         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3584       }
3585 
3586       if (DiagOld)
3587         Diag(DiagOld->getLocation(),
3588              diag::note_attribute_overloadable_prev_overload)
3589           << OldOvl;
3590 
3591       if (OldOvl)
3592         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3593       else
3594         New->dropAttr<OverloadableAttr>();
3595     }
3596   }
3597 
3598   // If a function is first declared with a calling convention, but is later
3599   // declared or defined without one, all following decls assume the calling
3600   // convention of the first.
3601   //
3602   // It's OK if a function is first declared without a calling convention,
3603   // but is later declared or defined with the default calling convention.
3604   //
3605   // To test if either decl has an explicit calling convention, we look for
3606   // AttributedType sugar nodes on the type as written.  If they are missing or
3607   // were canonicalized away, we assume the calling convention was implicit.
3608   //
3609   // Note also that we DO NOT return at this point, because we still have
3610   // other tests to run.
3611   QualType OldQType = Context.getCanonicalType(Old->getType());
3612   QualType NewQType = Context.getCanonicalType(New->getType());
3613   const FunctionType *OldType = cast<FunctionType>(OldQType);
3614   const FunctionType *NewType = cast<FunctionType>(NewQType);
3615   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3616   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3617   bool RequiresAdjustment = false;
3618 
3619   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3620     FunctionDecl *First = Old->getFirstDecl();
3621     const FunctionType *FT =
3622         First->getType().getCanonicalType()->castAs<FunctionType>();
3623     FunctionType::ExtInfo FI = FT->getExtInfo();
3624     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3625     if (!NewCCExplicit) {
3626       // Inherit the CC from the previous declaration if it was specified
3627       // there but not here.
3628       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3629       RequiresAdjustment = true;
3630     } else if (Old->getBuiltinID()) {
3631       // Builtin attribute isn't propagated to the new one yet at this point,
3632       // so we check if the old one is a builtin.
3633 
3634       // Calling Conventions on a Builtin aren't really useful and setting a
3635       // default calling convention and cdecl'ing some builtin redeclarations is
3636       // common, so warn and ignore the calling convention on the redeclaration.
3637       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3638           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3639           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3640       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3641       RequiresAdjustment = true;
3642     } else {
3643       // Calling conventions aren't compatible, so complain.
3644       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3645       Diag(New->getLocation(), diag::err_cconv_change)
3646         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3647         << !FirstCCExplicit
3648         << (!FirstCCExplicit ? "" :
3649             FunctionType::getNameForCallConv(FI.getCC()));
3650 
3651       // Put the note on the first decl, since it is the one that matters.
3652       Diag(First->getLocation(), diag::note_previous_declaration);
3653       return true;
3654     }
3655   }
3656 
3657   // FIXME: diagnose the other way around?
3658   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3659     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3660     RequiresAdjustment = true;
3661   }
3662 
3663   // Merge regparm attribute.
3664   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3665       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3666     if (NewTypeInfo.getHasRegParm()) {
3667       Diag(New->getLocation(), diag::err_regparm_mismatch)
3668         << NewType->getRegParmType()
3669         << OldType->getRegParmType();
3670       Diag(OldLocation, diag::note_previous_declaration);
3671       return true;
3672     }
3673 
3674     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3675     RequiresAdjustment = true;
3676   }
3677 
3678   // Merge ns_returns_retained attribute.
3679   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3680     if (NewTypeInfo.getProducesResult()) {
3681       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3682           << "'ns_returns_retained'";
3683       Diag(OldLocation, diag::note_previous_declaration);
3684       return true;
3685     }
3686 
3687     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3688     RequiresAdjustment = true;
3689   }
3690 
3691   if (OldTypeInfo.getNoCallerSavedRegs() !=
3692       NewTypeInfo.getNoCallerSavedRegs()) {
3693     if (NewTypeInfo.getNoCallerSavedRegs()) {
3694       AnyX86NoCallerSavedRegistersAttr *Attr =
3695         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3696       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3697       Diag(OldLocation, diag::note_previous_declaration);
3698       return true;
3699     }
3700 
3701     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3702     RequiresAdjustment = true;
3703   }
3704 
3705   if (RequiresAdjustment) {
3706     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3707     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3708     New->setType(QualType(AdjustedType, 0));
3709     NewQType = Context.getCanonicalType(New->getType());
3710   }
3711 
3712   // If this redeclaration makes the function inline, we may need to add it to
3713   // UndefinedButUsed.
3714   if (!Old->isInlined() && New->isInlined() &&
3715       !New->hasAttr<GNUInlineAttr>() &&
3716       !getLangOpts().GNUInline &&
3717       Old->isUsed(false) &&
3718       !Old->isDefined() && !New->isThisDeclarationADefinition())
3719     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3720                                            SourceLocation()));
3721 
3722   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3723   // about it.
3724   if (New->hasAttr<GNUInlineAttr>() &&
3725       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3726     UndefinedButUsed.erase(Old->getCanonicalDecl());
3727   }
3728 
3729   // If pass_object_size params don't match up perfectly, this isn't a valid
3730   // redeclaration.
3731   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3732       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3733     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3734         << New->getDeclName();
3735     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3736     return true;
3737   }
3738 
3739   if (getLangOpts().CPlusPlus) {
3740     // C++1z [over.load]p2
3741     //   Certain function declarations cannot be overloaded:
3742     //     -- Function declarations that differ only in the return type,
3743     //        the exception specification, or both cannot be overloaded.
3744 
3745     // Check the exception specifications match. This may recompute the type of
3746     // both Old and New if it resolved exception specifications, so grab the
3747     // types again after this. Because this updates the type, we do this before
3748     // any of the other checks below, which may update the "de facto" NewQType
3749     // but do not necessarily update the type of New.
3750     if (CheckEquivalentExceptionSpec(Old, New))
3751       return true;
3752     OldQType = Context.getCanonicalType(Old->getType());
3753     NewQType = Context.getCanonicalType(New->getType());
3754 
3755     // Go back to the type source info to compare the declared return types,
3756     // per C++1y [dcl.type.auto]p13:
3757     //   Redeclarations or specializations of a function or function template
3758     //   with a declared return type that uses a placeholder type shall also
3759     //   use that placeholder, not a deduced type.
3760     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3761     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3762     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3763         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3764                                        OldDeclaredReturnType)) {
3765       QualType ResQT;
3766       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3767           OldDeclaredReturnType->isObjCObjectPointerType())
3768         // FIXME: This does the wrong thing for a deduced return type.
3769         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3770       if (ResQT.isNull()) {
3771         if (New->isCXXClassMember() && New->isOutOfLine())
3772           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3773               << New << New->getReturnTypeSourceRange();
3774         else
3775           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3776               << New->getReturnTypeSourceRange();
3777         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3778                                     << Old->getReturnTypeSourceRange();
3779         return true;
3780       }
3781       else
3782         NewQType = ResQT;
3783     }
3784 
3785     QualType OldReturnType = OldType->getReturnType();
3786     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3787     if (OldReturnType != NewReturnType) {
3788       // If this function has a deduced return type and has already been
3789       // defined, copy the deduced value from the old declaration.
3790       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3791       if (OldAT && OldAT->isDeduced()) {
3792         QualType DT = OldAT->getDeducedType();
3793         if (DT.isNull()) {
3794           New->setType(SubstAutoTypeDependent(New->getType()));
3795           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3796         } else {
3797           New->setType(SubstAutoType(New->getType(), DT));
3798           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3799         }
3800       }
3801     }
3802 
3803     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3804     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3805     if (OldMethod && NewMethod) {
3806       // Preserve triviality.
3807       NewMethod->setTrivial(OldMethod->isTrivial());
3808 
3809       // MSVC allows explicit template specialization at class scope:
3810       // 2 CXXMethodDecls referring to the same function will be injected.
3811       // We don't want a redeclaration error.
3812       bool IsClassScopeExplicitSpecialization =
3813                               OldMethod->isFunctionTemplateSpecialization() &&
3814                               NewMethod->isFunctionTemplateSpecialization();
3815       bool isFriend = NewMethod->getFriendObjectKind();
3816 
3817       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3818           !IsClassScopeExplicitSpecialization) {
3819         //    -- Member function declarations with the same name and the
3820         //       same parameter types cannot be overloaded if any of them
3821         //       is a static member function declaration.
3822         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3823           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3824           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3825           return true;
3826         }
3827 
3828         // C++ [class.mem]p1:
3829         //   [...] A member shall not be declared twice in the
3830         //   member-specification, except that a nested class or member
3831         //   class template can be declared and then later defined.
3832         if (!inTemplateInstantiation()) {
3833           unsigned NewDiag;
3834           if (isa<CXXConstructorDecl>(OldMethod))
3835             NewDiag = diag::err_constructor_redeclared;
3836           else if (isa<CXXDestructorDecl>(NewMethod))
3837             NewDiag = diag::err_destructor_redeclared;
3838           else if (isa<CXXConversionDecl>(NewMethod))
3839             NewDiag = diag::err_conv_function_redeclared;
3840           else
3841             NewDiag = diag::err_member_redeclared;
3842 
3843           Diag(New->getLocation(), NewDiag);
3844         } else {
3845           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3846             << New << New->getType();
3847         }
3848         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3849         return true;
3850 
3851       // Complain if this is an explicit declaration of a special
3852       // member that was initially declared implicitly.
3853       //
3854       // As an exception, it's okay to befriend such methods in order
3855       // to permit the implicit constructor/destructor/operator calls.
3856       } else if (OldMethod->isImplicit()) {
3857         if (isFriend) {
3858           NewMethod->setImplicit();
3859         } else {
3860           Diag(NewMethod->getLocation(),
3861                diag::err_definition_of_implicitly_declared_member)
3862             << New << getSpecialMember(OldMethod);
3863           return true;
3864         }
3865       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3866         Diag(NewMethod->getLocation(),
3867              diag::err_definition_of_explicitly_defaulted_member)
3868           << getSpecialMember(OldMethod);
3869         return true;
3870       }
3871     }
3872 
3873     // C++11 [dcl.attr.noreturn]p1:
3874     //   The first declaration of a function shall specify the noreturn
3875     //   attribute if any declaration of that function specifies the noreturn
3876     //   attribute.
3877     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3878       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3879         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3880             << NRA;
3881         Diag(Old->getLocation(), diag::note_previous_declaration);
3882       }
3883 
3884     // C++11 [dcl.attr.depend]p2:
3885     //   The first declaration of a function shall specify the
3886     //   carries_dependency attribute for its declarator-id if any declaration
3887     //   of the function specifies the carries_dependency attribute.
3888     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3889     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3890       Diag(CDA->getLocation(),
3891            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3892       Diag(Old->getFirstDecl()->getLocation(),
3893            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3894     }
3895 
3896     // (C++98 8.3.5p3):
3897     //   All declarations for a function shall agree exactly in both the
3898     //   return type and the parameter-type-list.
3899     // We also want to respect all the extended bits except noreturn.
3900 
3901     // noreturn should now match unless the old type info didn't have it.
3902     QualType OldQTypeForComparison = OldQType;
3903     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3904       auto *OldType = OldQType->castAs<FunctionProtoType>();
3905       const FunctionType *OldTypeForComparison
3906         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3907       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3908       assert(OldQTypeForComparison.isCanonical());
3909     }
3910 
3911     if (haveIncompatibleLanguageLinkages(Old, New)) {
3912       // As a special case, retain the language linkage from previous
3913       // declarations of a friend function as an extension.
3914       //
3915       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3916       // and is useful because there's otherwise no way to specify language
3917       // linkage within class scope.
3918       //
3919       // Check cautiously as the friend object kind isn't yet complete.
3920       if (New->getFriendObjectKind() != Decl::FOK_None) {
3921         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3922         Diag(OldLocation, PrevDiag);
3923       } else {
3924         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3925         Diag(OldLocation, PrevDiag);
3926         return true;
3927       }
3928     }
3929 
3930     // If the function types are compatible, merge the declarations. Ignore the
3931     // exception specifier because it was already checked above in
3932     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3933     // about incompatible types under -fms-compatibility.
3934     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3935                                                          NewQType))
3936       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3937 
3938     // If the types are imprecise (due to dependent constructs in friends or
3939     // local extern declarations), it's OK if they differ. We'll check again
3940     // during instantiation.
3941     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3942       return false;
3943 
3944     // Fall through for conflicting redeclarations and redefinitions.
3945   }
3946 
3947   // C: Function types need to be compatible, not identical. This handles
3948   // duplicate function decls like "void f(int); void f(enum X);" properly.
3949   if (!getLangOpts().CPlusPlus) {
3950     // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
3951     // type is specified by a function definition that contains a (possibly
3952     // empty) identifier list, both shall agree in the number of parameters
3953     // and the type of each parameter shall be compatible with the type that
3954     // results from the application of default argument promotions to the
3955     // type of the corresponding identifier. ...
3956     // This cannot be handled by ASTContext::typesAreCompatible() because that
3957     // doesn't know whether the function type is for a definition or not when
3958     // eventually calling ASTContext::mergeFunctionTypes(). The only situation
3959     // we need to cover here is that the number of arguments agree as the
3960     // default argument promotion rules were already checked by
3961     // ASTContext::typesAreCompatible().
3962     if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
3963         Old->getNumParams() != New->getNumParams()) {
3964       if (Old->hasInheritedPrototype())
3965         Old = Old->getCanonicalDecl();
3966       Diag(New->getLocation(), diag::err_conflicting_types) << New;
3967       Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
3968       return true;
3969     }
3970 
3971     // If we are merging two functions where only one of them has a prototype,
3972     // we may have enough information to decide to issue a diagnostic that the
3973     // function without a protoype will change behavior in C2x. This handles
3974     // cases like:
3975     //   void i(); void i(int j);
3976     //   void i(int j); void i();
3977     //   void i(); void i(int j) {}
3978     // See ActOnFinishFunctionBody() for other cases of the behavior change
3979     // diagnostic. See GetFullTypeForDeclarator() for handling of a function
3980     // type without a prototype.
3981     if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
3982         !New->isImplicit() && !Old->isImplicit()) {
3983       const FunctionDecl *WithProto, *WithoutProto;
3984       if (New->hasWrittenPrototype()) {
3985         WithProto = New;
3986         WithoutProto = Old;
3987       } else {
3988         WithProto = Old;
3989         WithoutProto = New;
3990       }
3991 
3992       if (WithProto->getNumParams() != 0) {
3993         if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
3994           // The one without the prototype will be changing behavior in C2x, so
3995           // warn about that one so long as it's a user-visible declaration.
3996           bool IsWithoutProtoADef = false, IsWithProtoADef = false;
3997           if (WithoutProto == New)
3998             IsWithoutProtoADef = NewDeclIsDefn;
3999           else
4000             IsWithProtoADef = NewDeclIsDefn;
4001           Diag(WithoutProto->getLocation(),
4002                diag::warn_non_prototype_changes_behavior)
4003               << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4004               << (WithoutProto == Old) << IsWithProtoADef;
4005 
4006           // The reason the one without the prototype will be changing behavior
4007           // is because of the one with the prototype, so note that so long as
4008           // it's a user-visible declaration. There is one exception to this:
4009           // when the new declaration is a definition without a prototype, the
4010           // old declaration with a prototype is not the cause of the issue,
4011           // and that does not need to be noted because the one with a
4012           // prototype will not change behavior in C2x.
4013           if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4014               !IsWithoutProtoADef)
4015             Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4016         }
4017       }
4018     }
4019 
4020     if (Context.typesAreCompatible(OldQType, NewQType)) {
4021       const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4022       const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4023       const FunctionProtoType *OldProto = nullptr;
4024       if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4025           (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4026         // The old declaration provided a function prototype, but the
4027         // new declaration does not. Merge in the prototype.
4028         assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4029         SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
4030         NewQType =
4031             Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
4032                                     OldProto->getExtProtoInfo());
4033         New->setType(NewQType);
4034         New->setHasInheritedPrototype();
4035 
4036         // Synthesize parameters with the same types.
4037         SmallVector<ParmVarDecl *, 16> Params;
4038         for (const auto &ParamType : OldProto->param_types()) {
4039           ParmVarDecl *Param = ParmVarDecl::Create(
4040               Context, New, SourceLocation(), SourceLocation(), nullptr,
4041               ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4042           Param->setScopeInfo(0, Params.size());
4043           Param->setImplicit();
4044           Params.push_back(Param);
4045         }
4046 
4047         New->setParams(Params);
4048       }
4049 
4050       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4051     }
4052   }
4053 
4054   // Check if the function types are compatible when pointer size address
4055   // spaces are ignored.
4056   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4057     return false;
4058 
4059   // GNU C permits a K&R definition to follow a prototype declaration
4060   // if the declared types of the parameters in the K&R definition
4061   // match the types in the prototype declaration, even when the
4062   // promoted types of the parameters from the K&R definition differ
4063   // from the types in the prototype. GCC then keeps the types from
4064   // the prototype.
4065   //
4066   // If a variadic prototype is followed by a non-variadic K&R definition,
4067   // the K&R definition becomes variadic.  This is sort of an edge case, but
4068   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4069   // C99 6.9.1p8.
4070   if (!getLangOpts().CPlusPlus &&
4071       Old->hasPrototype() && !New->hasPrototype() &&
4072       New->getType()->getAs<FunctionProtoType>() &&
4073       Old->getNumParams() == New->getNumParams()) {
4074     SmallVector<QualType, 16> ArgTypes;
4075     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4076     const FunctionProtoType *OldProto
4077       = Old->getType()->getAs<FunctionProtoType>();
4078     const FunctionProtoType *NewProto
4079       = New->getType()->getAs<FunctionProtoType>();
4080 
4081     // Determine whether this is the GNU C extension.
4082     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4083                                                NewProto->getReturnType());
4084     bool LooseCompatible = !MergedReturn.isNull();
4085     for (unsigned Idx = 0, End = Old->getNumParams();
4086          LooseCompatible && Idx != End; ++Idx) {
4087       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4088       ParmVarDecl *NewParm = New->getParamDecl(Idx);
4089       if (Context.typesAreCompatible(OldParm->getType(),
4090                                      NewProto->getParamType(Idx))) {
4091         ArgTypes.push_back(NewParm->getType());
4092       } else if (Context.typesAreCompatible(OldParm->getType(),
4093                                             NewParm->getType(),
4094                                             /*CompareUnqualified=*/true)) {
4095         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4096                                            NewProto->getParamType(Idx) };
4097         Warnings.push_back(Warn);
4098         ArgTypes.push_back(NewParm->getType());
4099       } else
4100         LooseCompatible = false;
4101     }
4102 
4103     if (LooseCompatible) {
4104       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4105         Diag(Warnings[Warn].NewParm->getLocation(),
4106              diag::ext_param_promoted_not_compatible_with_prototype)
4107           << Warnings[Warn].PromotedType
4108           << Warnings[Warn].OldParm->getType();
4109         if (Warnings[Warn].OldParm->getLocation().isValid())
4110           Diag(Warnings[Warn].OldParm->getLocation(),
4111                diag::note_previous_declaration);
4112       }
4113 
4114       if (MergeTypeWithOld)
4115         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4116                                              OldProto->getExtProtoInfo()));
4117       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4118     }
4119 
4120     // Fall through to diagnose conflicting types.
4121   }
4122 
4123   // A function that has already been declared has been redeclared or
4124   // defined with a different type; show an appropriate diagnostic.
4125 
4126   // If the previous declaration was an implicitly-generated builtin
4127   // declaration, then at the very least we should use a specialized note.
4128   unsigned BuiltinID;
4129   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4130     // If it's actually a library-defined builtin function like 'malloc'
4131     // or 'printf', just warn about the incompatible redeclaration.
4132     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4133       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4134       Diag(OldLocation, diag::note_previous_builtin_declaration)
4135         << Old << Old->getType();
4136       return false;
4137     }
4138 
4139     PrevDiag = diag::note_previous_builtin_declaration;
4140   }
4141 
4142   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4143   Diag(OldLocation, PrevDiag) << Old << Old->getType();
4144   return true;
4145 }
4146 
4147 /// Completes the merge of two function declarations that are
4148 /// known to be compatible.
4149 ///
4150 /// This routine handles the merging of attributes and other
4151 /// properties of function declarations from the old declaration to
4152 /// the new declaration, once we know that New is in fact a
4153 /// redeclaration of Old.
4154 ///
4155 /// \returns false
4156 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4157                                         Scope *S, bool MergeTypeWithOld) {
4158   // Merge the attributes
4159   mergeDeclAttributes(New, Old);
4160 
4161   // Merge "pure" flag.
4162   if (Old->isPure())
4163     New->setPure();
4164 
4165   // Merge "used" flag.
4166   if (Old->getMostRecentDecl()->isUsed(false))
4167     New->setIsUsed();
4168 
4169   // Merge attributes from the parameters.  These can mismatch with K&R
4170   // declarations.
4171   if (New->getNumParams() == Old->getNumParams())
4172       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4173         ParmVarDecl *NewParam = New->getParamDecl(i);
4174         ParmVarDecl *OldParam = Old->getParamDecl(i);
4175         mergeParamDeclAttributes(NewParam, OldParam, *this);
4176         mergeParamDeclTypes(NewParam, OldParam, *this);
4177       }
4178 
4179   if (getLangOpts().CPlusPlus)
4180     return MergeCXXFunctionDecl(New, Old, S);
4181 
4182   // Merge the function types so the we get the composite types for the return
4183   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4184   // was visible.
4185   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4186   if (!Merged.isNull() && MergeTypeWithOld)
4187     New->setType(Merged);
4188 
4189   return false;
4190 }
4191 
4192 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4193                                 ObjCMethodDecl *oldMethod) {
4194   // Merge the attributes, including deprecated/unavailable
4195   AvailabilityMergeKind MergeKind =
4196       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4197           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4198                                      : AMK_ProtocolImplementation)
4199           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4200                                                            : AMK_Override;
4201 
4202   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4203 
4204   // Merge attributes from the parameters.
4205   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4206                                        oe = oldMethod->param_end();
4207   for (ObjCMethodDecl::param_iterator
4208          ni = newMethod->param_begin(), ne = newMethod->param_end();
4209        ni != ne && oi != oe; ++ni, ++oi)
4210     mergeParamDeclAttributes(*ni, *oi, *this);
4211 
4212   CheckObjCMethodOverride(newMethod, oldMethod);
4213 }
4214 
4215 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4216   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4217 
4218   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4219          ? diag::err_redefinition_different_type
4220          : diag::err_redeclaration_different_type)
4221     << New->getDeclName() << New->getType() << Old->getType();
4222 
4223   diag::kind PrevDiag;
4224   SourceLocation OldLocation;
4225   std::tie(PrevDiag, OldLocation)
4226     = getNoteDiagForInvalidRedeclaration(Old, New);
4227   S.Diag(OldLocation, PrevDiag);
4228   New->setInvalidDecl();
4229 }
4230 
4231 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4232 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
4233 /// emitting diagnostics as appropriate.
4234 ///
4235 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4236 /// to here in AddInitializerToDecl. We can't check them before the initializer
4237 /// is attached.
4238 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4239                              bool MergeTypeWithOld) {
4240   if (New->isInvalidDecl() || Old->isInvalidDecl())
4241     return;
4242 
4243   QualType MergedT;
4244   if (getLangOpts().CPlusPlus) {
4245     if (New->getType()->isUndeducedType()) {
4246       // We don't know what the new type is until the initializer is attached.
4247       return;
4248     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4249       // These could still be something that needs exception specs checked.
4250       return MergeVarDeclExceptionSpecs(New, Old);
4251     }
4252     // C++ [basic.link]p10:
4253     //   [...] the types specified by all declarations referring to a given
4254     //   object or function shall be identical, except that declarations for an
4255     //   array object can specify array types that differ by the presence or
4256     //   absence of a major array bound (8.3.4).
4257     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4258       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4259       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4260 
4261       // We are merging a variable declaration New into Old. If it has an array
4262       // bound, and that bound differs from Old's bound, we should diagnose the
4263       // mismatch.
4264       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4265         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4266              PrevVD = PrevVD->getPreviousDecl()) {
4267           QualType PrevVDTy = PrevVD->getType();
4268           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4269             continue;
4270 
4271           if (!Context.hasSameType(New->getType(), PrevVDTy))
4272             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4273         }
4274       }
4275 
4276       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4277         if (Context.hasSameType(OldArray->getElementType(),
4278                                 NewArray->getElementType()))
4279           MergedT = New->getType();
4280       }
4281       // FIXME: Check visibility. New is hidden but has a complete type. If New
4282       // has no array bound, it should not inherit one from Old, if Old is not
4283       // visible.
4284       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4285         if (Context.hasSameType(OldArray->getElementType(),
4286                                 NewArray->getElementType()))
4287           MergedT = Old->getType();
4288       }
4289     }
4290     else if (New->getType()->isObjCObjectPointerType() &&
4291                Old->getType()->isObjCObjectPointerType()) {
4292       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4293                                               Old->getType());
4294     }
4295   } else {
4296     // C 6.2.7p2:
4297     //   All declarations that refer to the same object or function shall have
4298     //   compatible type.
4299     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4300   }
4301   if (MergedT.isNull()) {
4302     // It's OK if we couldn't merge types if either type is dependent, for a
4303     // block-scope variable. In other cases (static data members of class
4304     // templates, variable templates, ...), we require the types to be
4305     // equivalent.
4306     // FIXME: The C++ standard doesn't say anything about this.
4307     if ((New->getType()->isDependentType() ||
4308          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4309       // If the old type was dependent, we can't merge with it, so the new type
4310       // becomes dependent for now. We'll reproduce the original type when we
4311       // instantiate the TypeSourceInfo for the variable.
4312       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4313         New->setType(Context.DependentTy);
4314       return;
4315     }
4316     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4317   }
4318 
4319   // Don't actually update the type on the new declaration if the old
4320   // declaration was an extern declaration in a different scope.
4321   if (MergeTypeWithOld)
4322     New->setType(MergedT);
4323 }
4324 
4325 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4326                                   LookupResult &Previous) {
4327   // C11 6.2.7p4:
4328   //   For an identifier with internal or external linkage declared
4329   //   in a scope in which a prior declaration of that identifier is
4330   //   visible, if the prior declaration specifies internal or
4331   //   external linkage, the type of the identifier at the later
4332   //   declaration becomes the composite type.
4333   //
4334   // If the variable isn't visible, we do not merge with its type.
4335   if (Previous.isShadowed())
4336     return false;
4337 
4338   if (S.getLangOpts().CPlusPlus) {
4339     // C++11 [dcl.array]p3:
4340     //   If there is a preceding declaration of the entity in the same
4341     //   scope in which the bound was specified, an omitted array bound
4342     //   is taken to be the same as in that earlier declaration.
4343     return NewVD->isPreviousDeclInSameBlockScope() ||
4344            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4345             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4346   } else {
4347     // If the old declaration was function-local, don't merge with its
4348     // type unless we're in the same function.
4349     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4350            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4351   }
4352 }
4353 
4354 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4355 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4356 /// situation, merging decls or emitting diagnostics as appropriate.
4357 ///
4358 /// Tentative definition rules (C99 6.9.2p2) are checked by
4359 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4360 /// definitions here, since the initializer hasn't been attached.
4361 ///
4362 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4363   // If the new decl is already invalid, don't do any other checking.
4364   if (New->isInvalidDecl())
4365     return;
4366 
4367   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4368     return;
4369 
4370   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4371 
4372   // Verify the old decl was also a variable or variable template.
4373   VarDecl *Old = nullptr;
4374   VarTemplateDecl *OldTemplate = nullptr;
4375   if (Previous.isSingleResult()) {
4376     if (NewTemplate) {
4377       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4378       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4379 
4380       if (auto *Shadow =
4381               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4382         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4383           return New->setInvalidDecl();
4384     } else {
4385       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4386 
4387       if (auto *Shadow =
4388               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4389         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4390           return New->setInvalidDecl();
4391     }
4392   }
4393   if (!Old) {
4394     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4395         << New->getDeclName();
4396     notePreviousDefinition(Previous.getRepresentativeDecl(),
4397                            New->getLocation());
4398     return New->setInvalidDecl();
4399   }
4400 
4401   // If the old declaration was found in an inline namespace and the new
4402   // declaration was qualified, update the DeclContext to match.
4403   adjustDeclContextForDeclaratorDecl(New, Old);
4404 
4405   // Ensure the template parameters are compatible.
4406   if (NewTemplate &&
4407       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4408                                       OldTemplate->getTemplateParameters(),
4409                                       /*Complain=*/true, TPL_TemplateMatch))
4410     return New->setInvalidDecl();
4411 
4412   // C++ [class.mem]p1:
4413   //   A member shall not be declared twice in the member-specification [...]
4414   //
4415   // Here, we need only consider static data members.
4416   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4417     Diag(New->getLocation(), diag::err_duplicate_member)
4418       << New->getIdentifier();
4419     Diag(Old->getLocation(), diag::note_previous_declaration);
4420     New->setInvalidDecl();
4421   }
4422 
4423   mergeDeclAttributes(New, Old);
4424   // Warn if an already-declared variable is made a weak_import in a subsequent
4425   // declaration
4426   if (New->hasAttr<WeakImportAttr>() &&
4427       Old->getStorageClass() == SC_None &&
4428       !Old->hasAttr<WeakImportAttr>()) {
4429     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4430     Diag(Old->getLocation(), diag::note_previous_declaration);
4431     // Remove weak_import attribute on new declaration.
4432     New->dropAttr<WeakImportAttr>();
4433   }
4434 
4435   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4436     if (!Old->hasAttr<InternalLinkageAttr>()) {
4437       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4438           << ILA;
4439       Diag(Old->getLocation(), diag::note_previous_declaration);
4440       New->dropAttr<InternalLinkageAttr>();
4441     }
4442 
4443   // Merge the types.
4444   VarDecl *MostRecent = Old->getMostRecentDecl();
4445   if (MostRecent != Old) {
4446     MergeVarDeclTypes(New, MostRecent,
4447                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4448     if (New->isInvalidDecl())
4449       return;
4450   }
4451 
4452   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4453   if (New->isInvalidDecl())
4454     return;
4455 
4456   diag::kind PrevDiag;
4457   SourceLocation OldLocation;
4458   std::tie(PrevDiag, OldLocation) =
4459       getNoteDiagForInvalidRedeclaration(Old, New);
4460 
4461   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4462   if (New->getStorageClass() == SC_Static &&
4463       !New->isStaticDataMember() &&
4464       Old->hasExternalFormalLinkage()) {
4465     if (getLangOpts().MicrosoftExt) {
4466       Diag(New->getLocation(), diag::ext_static_non_static)
4467           << New->getDeclName();
4468       Diag(OldLocation, PrevDiag);
4469     } else {
4470       Diag(New->getLocation(), diag::err_static_non_static)
4471           << New->getDeclName();
4472       Diag(OldLocation, PrevDiag);
4473       return New->setInvalidDecl();
4474     }
4475   }
4476   // C99 6.2.2p4:
4477   //   For an identifier declared with the storage-class specifier
4478   //   extern in a scope in which a prior declaration of that
4479   //   identifier is visible,23) if the prior declaration specifies
4480   //   internal or external linkage, the linkage of the identifier at
4481   //   the later declaration is the same as the linkage specified at
4482   //   the prior declaration. If no prior declaration is visible, or
4483   //   if the prior declaration specifies no linkage, then the
4484   //   identifier has external linkage.
4485   if (New->hasExternalStorage() && Old->hasLinkage())
4486     /* Okay */;
4487   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4488            !New->isStaticDataMember() &&
4489            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4490     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4491     Diag(OldLocation, PrevDiag);
4492     return New->setInvalidDecl();
4493   }
4494 
4495   // Check if extern is followed by non-extern and vice-versa.
4496   if (New->hasExternalStorage() &&
4497       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4498     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4499     Diag(OldLocation, PrevDiag);
4500     return New->setInvalidDecl();
4501   }
4502   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4503       !New->hasExternalStorage()) {
4504     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4505     Diag(OldLocation, PrevDiag);
4506     return New->setInvalidDecl();
4507   }
4508 
4509   if (CheckRedeclarationInModule(New, Old))
4510     return;
4511 
4512   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4513 
4514   // FIXME: The test for external storage here seems wrong? We still
4515   // need to check for mismatches.
4516   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4517       // Don't complain about out-of-line definitions of static members.
4518       !(Old->getLexicalDeclContext()->isRecord() &&
4519         !New->getLexicalDeclContext()->isRecord())) {
4520     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4521     Diag(OldLocation, PrevDiag);
4522     return New->setInvalidDecl();
4523   }
4524 
4525   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4526     if (VarDecl *Def = Old->getDefinition()) {
4527       // C++1z [dcl.fcn.spec]p4:
4528       //   If the definition of a variable appears in a translation unit before
4529       //   its first declaration as inline, the program is ill-formed.
4530       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4531       Diag(Def->getLocation(), diag::note_previous_definition);
4532     }
4533   }
4534 
4535   // If this redeclaration makes the variable inline, we may need to add it to
4536   // UndefinedButUsed.
4537   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4538       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4539     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4540                                            SourceLocation()));
4541 
4542   if (New->getTLSKind() != Old->getTLSKind()) {
4543     if (!Old->getTLSKind()) {
4544       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4545       Diag(OldLocation, PrevDiag);
4546     } else if (!New->getTLSKind()) {
4547       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4548       Diag(OldLocation, PrevDiag);
4549     } else {
4550       // Do not allow redeclaration to change the variable between requiring
4551       // static and dynamic initialization.
4552       // FIXME: GCC allows this, but uses the TLS keyword on the first
4553       // declaration to determine the kind. Do we need to be compatible here?
4554       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4555         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4556       Diag(OldLocation, PrevDiag);
4557     }
4558   }
4559 
4560   // C++ doesn't have tentative definitions, so go right ahead and check here.
4561   if (getLangOpts().CPlusPlus) {
4562     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4563         Old->getCanonicalDecl()->isConstexpr()) {
4564       // This definition won't be a definition any more once it's been merged.
4565       Diag(New->getLocation(),
4566            diag::warn_deprecated_redundant_constexpr_static_def);
4567     } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4568       VarDecl *Def = Old->getDefinition();
4569       if (Def && checkVarDeclRedefinition(Def, New))
4570         return;
4571     }
4572   }
4573 
4574   if (haveIncompatibleLanguageLinkages(Old, New)) {
4575     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4576     Diag(OldLocation, PrevDiag);
4577     New->setInvalidDecl();
4578     return;
4579   }
4580 
4581   // Merge "used" flag.
4582   if (Old->getMostRecentDecl()->isUsed(false))
4583     New->setIsUsed();
4584 
4585   // Keep a chain of previous declarations.
4586   New->setPreviousDecl(Old);
4587   if (NewTemplate)
4588     NewTemplate->setPreviousDecl(OldTemplate);
4589 
4590   // Inherit access appropriately.
4591   New->setAccess(Old->getAccess());
4592   if (NewTemplate)
4593     NewTemplate->setAccess(New->getAccess());
4594 
4595   if (Old->isInline())
4596     New->setImplicitlyInline();
4597 }
4598 
4599 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4600   SourceManager &SrcMgr = getSourceManager();
4601   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4602   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4603   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4604   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4605   auto &HSI = PP.getHeaderSearchInfo();
4606   StringRef HdrFilename =
4607       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4608 
4609   auto noteFromModuleOrInclude = [&](Module *Mod,
4610                                      SourceLocation IncLoc) -> bool {
4611     // Redefinition errors with modules are common with non modular mapped
4612     // headers, example: a non-modular header H in module A that also gets
4613     // included directly in a TU. Pointing twice to the same header/definition
4614     // is confusing, try to get better diagnostics when modules is on.
4615     if (IncLoc.isValid()) {
4616       if (Mod) {
4617         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4618             << HdrFilename.str() << Mod->getFullModuleName();
4619         if (!Mod->DefinitionLoc.isInvalid())
4620           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4621               << Mod->getFullModuleName();
4622       } else {
4623         Diag(IncLoc, diag::note_redefinition_include_same_file)
4624             << HdrFilename.str();
4625       }
4626       return true;
4627     }
4628 
4629     return false;
4630   };
4631 
4632   // Is it the same file and same offset? Provide more information on why
4633   // this leads to a redefinition error.
4634   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4635     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4636     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4637     bool EmittedDiag =
4638         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4639     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4640 
4641     // If the header has no guards, emit a note suggesting one.
4642     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4643       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4644 
4645     if (EmittedDiag)
4646       return;
4647   }
4648 
4649   // Redefinition coming from different files or couldn't do better above.
4650   if (Old->getLocation().isValid())
4651     Diag(Old->getLocation(), diag::note_previous_definition);
4652 }
4653 
4654 /// We've just determined that \p Old and \p New both appear to be definitions
4655 /// of the same variable. Either diagnose or fix the problem.
4656 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4657   if (!hasVisibleDefinition(Old) &&
4658       (New->getFormalLinkage() == InternalLinkage ||
4659        New->isInline() ||
4660        New->getDescribedVarTemplate() ||
4661        New->getNumTemplateParameterLists() ||
4662        New->getDeclContext()->isDependentContext())) {
4663     // The previous definition is hidden, and multiple definitions are
4664     // permitted (in separate TUs). Demote this to a declaration.
4665     New->demoteThisDefinitionToDeclaration();
4666 
4667     // Make the canonical definition visible.
4668     if (auto *OldTD = Old->getDescribedVarTemplate())
4669       makeMergedDefinitionVisible(OldTD);
4670     makeMergedDefinitionVisible(Old);
4671     return false;
4672   } else {
4673     Diag(New->getLocation(), diag::err_redefinition) << New;
4674     notePreviousDefinition(Old, New->getLocation());
4675     New->setInvalidDecl();
4676     return true;
4677   }
4678 }
4679 
4680 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4681 /// no declarator (e.g. "struct foo;") is parsed.
4682 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4683                                        DeclSpec &DS,
4684                                        const ParsedAttributesView &DeclAttrs,
4685                                        RecordDecl *&AnonRecord) {
4686   return ParsedFreeStandingDeclSpec(
4687       S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4688 }
4689 
4690 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4691 // disambiguate entities defined in different scopes.
4692 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4693 // compatibility.
4694 // We will pick our mangling number depending on which version of MSVC is being
4695 // targeted.
4696 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4697   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4698              ? S->getMSCurManglingNumber()
4699              : S->getMSLastManglingNumber();
4700 }
4701 
4702 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4703   if (!Context.getLangOpts().CPlusPlus)
4704     return;
4705 
4706   if (isa<CXXRecordDecl>(Tag->getParent())) {
4707     // If this tag is the direct child of a class, number it if
4708     // it is anonymous.
4709     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4710       return;
4711     MangleNumberingContext &MCtx =
4712         Context.getManglingNumberContext(Tag->getParent());
4713     Context.setManglingNumber(
4714         Tag, MCtx.getManglingNumber(
4715                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4716     return;
4717   }
4718 
4719   // If this tag isn't a direct child of a class, number it if it is local.
4720   MangleNumberingContext *MCtx;
4721   Decl *ManglingContextDecl;
4722   std::tie(MCtx, ManglingContextDecl) =
4723       getCurrentMangleNumberContext(Tag->getDeclContext());
4724   if (MCtx) {
4725     Context.setManglingNumber(
4726         Tag, MCtx->getManglingNumber(
4727                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4728   }
4729 }
4730 
4731 namespace {
4732 struct NonCLikeKind {
4733   enum {
4734     None,
4735     BaseClass,
4736     DefaultMemberInit,
4737     Lambda,
4738     Friend,
4739     OtherMember,
4740     Invalid,
4741   } Kind = None;
4742   SourceRange Range;
4743 
4744   explicit operator bool() { return Kind != None; }
4745 };
4746 }
4747 
4748 /// Determine whether a class is C-like, according to the rules of C++
4749 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4750 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4751   if (RD->isInvalidDecl())
4752     return {NonCLikeKind::Invalid, {}};
4753 
4754   // C++ [dcl.typedef]p9: [P1766R1]
4755   //   An unnamed class with a typedef name for linkage purposes shall not
4756   //
4757   //    -- have any base classes
4758   if (RD->getNumBases())
4759     return {NonCLikeKind::BaseClass,
4760             SourceRange(RD->bases_begin()->getBeginLoc(),
4761                         RD->bases_end()[-1].getEndLoc())};
4762   bool Invalid = false;
4763   for (Decl *D : RD->decls()) {
4764     // Don't complain about things we already diagnosed.
4765     if (D->isInvalidDecl()) {
4766       Invalid = true;
4767       continue;
4768     }
4769 
4770     //  -- have any [...] default member initializers
4771     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4772       if (FD->hasInClassInitializer()) {
4773         auto *Init = FD->getInClassInitializer();
4774         return {NonCLikeKind::DefaultMemberInit,
4775                 Init ? Init->getSourceRange() : D->getSourceRange()};
4776       }
4777       continue;
4778     }
4779 
4780     // FIXME: We don't allow friend declarations. This violates the wording of
4781     // P1766, but not the intent.
4782     if (isa<FriendDecl>(D))
4783       return {NonCLikeKind::Friend, D->getSourceRange()};
4784 
4785     //  -- declare any members other than non-static data members, member
4786     //     enumerations, or member classes,
4787     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4788         isa<EnumDecl>(D))
4789       continue;
4790     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4791     if (!MemberRD) {
4792       if (D->isImplicit())
4793         continue;
4794       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4795     }
4796 
4797     //  -- contain a lambda-expression,
4798     if (MemberRD->isLambda())
4799       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4800 
4801     //  and all member classes shall also satisfy these requirements
4802     //  (recursively).
4803     if (MemberRD->isThisDeclarationADefinition()) {
4804       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4805         return Kind;
4806     }
4807   }
4808 
4809   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4810 }
4811 
4812 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4813                                         TypedefNameDecl *NewTD) {
4814   if (TagFromDeclSpec->isInvalidDecl())
4815     return;
4816 
4817   // Do nothing if the tag already has a name for linkage purposes.
4818   if (TagFromDeclSpec->hasNameForLinkage())
4819     return;
4820 
4821   // A well-formed anonymous tag must always be a TUK_Definition.
4822   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4823 
4824   // The type must match the tag exactly;  no qualifiers allowed.
4825   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4826                            Context.getTagDeclType(TagFromDeclSpec))) {
4827     if (getLangOpts().CPlusPlus)
4828       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4829     return;
4830   }
4831 
4832   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4833   //   An unnamed class with a typedef name for linkage purposes shall [be
4834   //   C-like].
4835   //
4836   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4837   // shouldn't happen, but there are constructs that the language rule doesn't
4838   // disallow for which we can't reasonably avoid computing linkage early.
4839   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4840   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4841                              : NonCLikeKind();
4842   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4843   if (NonCLike || ChangesLinkage) {
4844     if (NonCLike.Kind == NonCLikeKind::Invalid)
4845       return;
4846 
4847     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4848     if (ChangesLinkage) {
4849       // If the linkage changes, we can't accept this as an extension.
4850       if (NonCLike.Kind == NonCLikeKind::None)
4851         DiagID = diag::err_typedef_changes_linkage;
4852       else
4853         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4854     }
4855 
4856     SourceLocation FixitLoc =
4857         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4858     llvm::SmallString<40> TextToInsert;
4859     TextToInsert += ' ';
4860     TextToInsert += NewTD->getIdentifier()->getName();
4861 
4862     Diag(FixitLoc, DiagID)
4863       << isa<TypeAliasDecl>(NewTD)
4864       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4865     if (NonCLike.Kind != NonCLikeKind::None) {
4866       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4867         << NonCLike.Kind - 1 << NonCLike.Range;
4868     }
4869     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4870       << NewTD << isa<TypeAliasDecl>(NewTD);
4871 
4872     if (ChangesLinkage)
4873       return;
4874   }
4875 
4876   // Otherwise, set this as the anon-decl typedef for the tag.
4877   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4878 }
4879 
4880 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4881   switch (T) {
4882   case DeclSpec::TST_class:
4883     return 0;
4884   case DeclSpec::TST_struct:
4885     return 1;
4886   case DeclSpec::TST_interface:
4887     return 2;
4888   case DeclSpec::TST_union:
4889     return 3;
4890   case DeclSpec::TST_enum:
4891     return 4;
4892   default:
4893     llvm_unreachable("unexpected type specifier");
4894   }
4895 }
4896 
4897 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4898 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4899 /// parameters to cope with template friend declarations.
4900 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4901                                        DeclSpec &DS,
4902                                        const ParsedAttributesView &DeclAttrs,
4903                                        MultiTemplateParamsArg TemplateParams,
4904                                        bool IsExplicitInstantiation,
4905                                        RecordDecl *&AnonRecord) {
4906   Decl *TagD = nullptr;
4907   TagDecl *Tag = nullptr;
4908   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4909       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4910       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4911       DS.getTypeSpecType() == DeclSpec::TST_union ||
4912       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4913     TagD = DS.getRepAsDecl();
4914 
4915     if (!TagD) // We probably had an error
4916       return nullptr;
4917 
4918     // Note that the above type specs guarantee that the
4919     // type rep is a Decl, whereas in many of the others
4920     // it's a Type.
4921     if (isa<TagDecl>(TagD))
4922       Tag = cast<TagDecl>(TagD);
4923     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4924       Tag = CTD->getTemplatedDecl();
4925   }
4926 
4927   if (Tag) {
4928     handleTagNumbering(Tag, S);
4929     Tag->setFreeStanding();
4930     if (Tag->isInvalidDecl())
4931       return Tag;
4932   }
4933 
4934   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4935     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4936     // or incomplete types shall not be restrict-qualified."
4937     if (TypeQuals & DeclSpec::TQ_restrict)
4938       Diag(DS.getRestrictSpecLoc(),
4939            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4940            << DS.getSourceRange();
4941   }
4942 
4943   if (DS.isInlineSpecified())
4944     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4945         << getLangOpts().CPlusPlus17;
4946 
4947   if (DS.hasConstexprSpecifier()) {
4948     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4949     // and definitions of functions and variables.
4950     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4951     // the declaration of a function or function template
4952     if (Tag)
4953       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4954           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4955           << static_cast<int>(DS.getConstexprSpecifier());
4956     else
4957       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4958           << static_cast<int>(DS.getConstexprSpecifier());
4959     // Don't emit warnings after this error.
4960     return TagD;
4961   }
4962 
4963   DiagnoseFunctionSpecifiers(DS);
4964 
4965   if (DS.isFriendSpecified()) {
4966     // If we're dealing with a decl but not a TagDecl, assume that
4967     // whatever routines created it handled the friendship aspect.
4968     if (TagD && !Tag)
4969       return nullptr;
4970     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4971   }
4972 
4973   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4974   bool IsExplicitSpecialization =
4975     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4976   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4977       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4978       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4979     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4980     // nested-name-specifier unless it is an explicit instantiation
4981     // or an explicit specialization.
4982     //
4983     // FIXME: We allow class template partial specializations here too, per the
4984     // obvious intent of DR1819.
4985     //
4986     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4987     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4988         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4989     return nullptr;
4990   }
4991 
4992   // Track whether this decl-specifier declares anything.
4993   bool DeclaresAnything = true;
4994 
4995   // Handle anonymous struct definitions.
4996   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4997     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4998         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4999       if (getLangOpts().CPlusPlus ||
5000           Record->getDeclContext()->isRecord()) {
5001         // If CurContext is a DeclContext that can contain statements,
5002         // RecursiveASTVisitor won't visit the decls that
5003         // BuildAnonymousStructOrUnion() will put into CurContext.
5004         // Also store them here so that they can be part of the
5005         // DeclStmt that gets created in this case.
5006         // FIXME: Also return the IndirectFieldDecls created by
5007         // BuildAnonymousStructOr union, for the same reason?
5008         if (CurContext->isFunctionOrMethod())
5009           AnonRecord = Record;
5010         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5011                                            Context.getPrintingPolicy());
5012       }
5013 
5014       DeclaresAnything = false;
5015     }
5016   }
5017 
5018   // C11 6.7.2.1p2:
5019   //   A struct-declaration that does not declare an anonymous structure or
5020   //   anonymous union shall contain a struct-declarator-list.
5021   //
5022   // This rule also existed in C89 and C99; the grammar for struct-declaration
5023   // did not permit a struct-declaration without a struct-declarator-list.
5024   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5025       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5026     // Check for Microsoft C extension: anonymous struct/union member.
5027     // Handle 2 kinds of anonymous struct/union:
5028     //   struct STRUCT;
5029     //   union UNION;
5030     // and
5031     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
5032     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
5033     if ((Tag && Tag->getDeclName()) ||
5034         DS.getTypeSpecType() == DeclSpec::TST_typename) {
5035       RecordDecl *Record = nullptr;
5036       if (Tag)
5037         Record = dyn_cast<RecordDecl>(Tag);
5038       else if (const RecordType *RT =
5039                    DS.getRepAsType().get()->getAsStructureType())
5040         Record = RT->getDecl();
5041       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5042         Record = UT->getDecl();
5043 
5044       if (Record && getLangOpts().MicrosoftExt) {
5045         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5046             << Record->isUnion() << DS.getSourceRange();
5047         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5048       }
5049 
5050       DeclaresAnything = false;
5051     }
5052   }
5053 
5054   // Skip all the checks below if we have a type error.
5055   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5056       (TagD && TagD->isInvalidDecl()))
5057     return TagD;
5058 
5059   if (getLangOpts().CPlusPlus &&
5060       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5061     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5062       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5063           !Enum->getIdentifier() && !Enum->isInvalidDecl())
5064         DeclaresAnything = false;
5065 
5066   if (!DS.isMissingDeclaratorOk()) {
5067     // Customize diagnostic for a typedef missing a name.
5068     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5069       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5070           << DS.getSourceRange();
5071     else
5072       DeclaresAnything = false;
5073   }
5074 
5075   if (DS.isModulePrivateSpecified() &&
5076       Tag && Tag->getDeclContext()->isFunctionOrMethod())
5077     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5078       << Tag->getTagKind()
5079       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5080 
5081   ActOnDocumentableDecl(TagD);
5082 
5083   // C 6.7/2:
5084   //   A declaration [...] shall declare at least a declarator [...], a tag,
5085   //   or the members of an enumeration.
5086   // C++ [dcl.dcl]p3:
5087   //   [If there are no declarators], and except for the declaration of an
5088   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5089   //   names into the program, or shall redeclare a name introduced by a
5090   //   previous declaration.
5091   if (!DeclaresAnything) {
5092     // In C, we allow this as a (popular) extension / bug. Don't bother
5093     // producing further diagnostics for redundant qualifiers after this.
5094     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5095                                ? diag::err_no_declarators
5096                                : diag::ext_no_declarators)
5097         << DS.getSourceRange();
5098     return TagD;
5099   }
5100 
5101   // C++ [dcl.stc]p1:
5102   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5103   //   init-declarator-list of the declaration shall not be empty.
5104   // C++ [dcl.fct.spec]p1:
5105   //   If a cv-qualifier appears in a decl-specifier-seq, the
5106   //   init-declarator-list of the declaration shall not be empty.
5107   //
5108   // Spurious qualifiers here appear to be valid in C.
5109   unsigned DiagID = diag::warn_standalone_specifier;
5110   if (getLangOpts().CPlusPlus)
5111     DiagID = diag::ext_standalone_specifier;
5112 
5113   // Note that a linkage-specification sets a storage class, but
5114   // 'extern "C" struct foo;' is actually valid and not theoretically
5115   // useless.
5116   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5117     if (SCS == DeclSpec::SCS_mutable)
5118       // Since mutable is not a viable storage class specifier in C, there is
5119       // no reason to treat it as an extension. Instead, diagnose as an error.
5120       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5121     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5122       Diag(DS.getStorageClassSpecLoc(), DiagID)
5123         << DeclSpec::getSpecifierName(SCS);
5124   }
5125 
5126   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5127     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5128       << DeclSpec::getSpecifierName(TSCS);
5129   if (DS.getTypeQualifiers()) {
5130     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5131       Diag(DS.getConstSpecLoc(), DiagID) << "const";
5132     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5133       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5134     // Restrict is covered above.
5135     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5136       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5137     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5138       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5139   }
5140 
5141   // Warn about ignored type attributes, for example:
5142   // __attribute__((aligned)) struct A;
5143   // Attributes should be placed after tag to apply to type declaration.
5144   if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5145     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5146     if (TypeSpecType == DeclSpec::TST_class ||
5147         TypeSpecType == DeclSpec::TST_struct ||
5148         TypeSpecType == DeclSpec::TST_interface ||
5149         TypeSpecType == DeclSpec::TST_union ||
5150         TypeSpecType == DeclSpec::TST_enum) {
5151       for (const ParsedAttr &AL : DS.getAttributes())
5152         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5153             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5154       for (const ParsedAttr &AL : DeclAttrs)
5155         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5156             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5157     }
5158   }
5159 
5160   return TagD;
5161 }
5162 
5163 /// We are trying to inject an anonymous member into the given scope;
5164 /// check if there's an existing declaration that can't be overloaded.
5165 ///
5166 /// \return true if this is a forbidden redeclaration
5167 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5168                                          Scope *S,
5169                                          DeclContext *Owner,
5170                                          DeclarationName Name,
5171                                          SourceLocation NameLoc,
5172                                          bool IsUnion) {
5173   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5174                  Sema::ForVisibleRedeclaration);
5175   if (!SemaRef.LookupName(R, S)) return false;
5176 
5177   // Pick a representative declaration.
5178   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5179   assert(PrevDecl && "Expected a non-null Decl");
5180 
5181   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5182     return false;
5183 
5184   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5185     << IsUnion << Name;
5186   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5187 
5188   return true;
5189 }
5190 
5191 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5192 /// anonymous struct or union AnonRecord into the owning context Owner
5193 /// and scope S. This routine will be invoked just after we realize
5194 /// that an unnamed union or struct is actually an anonymous union or
5195 /// struct, e.g.,
5196 ///
5197 /// @code
5198 /// union {
5199 ///   int i;
5200 ///   float f;
5201 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5202 ///    // f into the surrounding scope.x
5203 /// @endcode
5204 ///
5205 /// This routine is recursive, injecting the names of nested anonymous
5206 /// structs/unions into the owning context and scope as well.
5207 static bool
5208 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5209                                     RecordDecl *AnonRecord, AccessSpecifier AS,
5210                                     SmallVectorImpl<NamedDecl *> &Chaining) {
5211   bool Invalid = false;
5212 
5213   // Look every FieldDecl and IndirectFieldDecl with a name.
5214   for (auto *D : AnonRecord->decls()) {
5215     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5216         cast<NamedDecl>(D)->getDeclName()) {
5217       ValueDecl *VD = cast<ValueDecl>(D);
5218       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5219                                        VD->getLocation(),
5220                                        AnonRecord->isUnion())) {
5221         // C++ [class.union]p2:
5222         //   The names of the members of an anonymous union shall be
5223         //   distinct from the names of any other entity in the
5224         //   scope in which the anonymous union is declared.
5225         Invalid = true;
5226       } else {
5227         // C++ [class.union]p2:
5228         //   For the purpose of name lookup, after the anonymous union
5229         //   definition, the members of the anonymous union are
5230         //   considered to have been defined in the scope in which the
5231         //   anonymous union is declared.
5232         unsigned OldChainingSize = Chaining.size();
5233         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5234           Chaining.append(IF->chain_begin(), IF->chain_end());
5235         else
5236           Chaining.push_back(VD);
5237 
5238         assert(Chaining.size() >= 2);
5239         NamedDecl **NamedChain =
5240           new (SemaRef.Context)NamedDecl*[Chaining.size()];
5241         for (unsigned i = 0; i < Chaining.size(); i++)
5242           NamedChain[i] = Chaining[i];
5243 
5244         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5245             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5246             VD->getType(), {NamedChain, Chaining.size()});
5247 
5248         for (const auto *Attr : VD->attrs())
5249           IndirectField->addAttr(Attr->clone(SemaRef.Context));
5250 
5251         IndirectField->setAccess(AS);
5252         IndirectField->setImplicit();
5253         SemaRef.PushOnScopeChains(IndirectField, S);
5254 
5255         // That includes picking up the appropriate access specifier.
5256         if (AS != AS_none) IndirectField->setAccess(AS);
5257 
5258         Chaining.resize(OldChainingSize);
5259       }
5260     }
5261   }
5262 
5263   return Invalid;
5264 }
5265 
5266 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5267 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5268 /// illegal input values are mapped to SC_None.
5269 static StorageClass
5270 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5271   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5272   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5273          "Parser allowed 'typedef' as storage class VarDecl.");
5274   switch (StorageClassSpec) {
5275   case DeclSpec::SCS_unspecified:    return SC_None;
5276   case DeclSpec::SCS_extern:
5277     if (DS.isExternInLinkageSpec())
5278       return SC_None;
5279     return SC_Extern;
5280   case DeclSpec::SCS_static:         return SC_Static;
5281   case DeclSpec::SCS_auto:           return SC_Auto;
5282   case DeclSpec::SCS_register:       return SC_Register;
5283   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5284     // Illegal SCSs map to None: error reporting is up to the caller.
5285   case DeclSpec::SCS_mutable:        // Fall through.
5286   case DeclSpec::SCS_typedef:        return SC_None;
5287   }
5288   llvm_unreachable("unknown storage class specifier");
5289 }
5290 
5291 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5292   assert(Record->hasInClassInitializer());
5293 
5294   for (const auto *I : Record->decls()) {
5295     const auto *FD = dyn_cast<FieldDecl>(I);
5296     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5297       FD = IFD->getAnonField();
5298     if (FD && FD->hasInClassInitializer())
5299       return FD->getLocation();
5300   }
5301 
5302   llvm_unreachable("couldn't find in-class initializer");
5303 }
5304 
5305 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5306                                       SourceLocation DefaultInitLoc) {
5307   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5308     return;
5309 
5310   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5311   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5312 }
5313 
5314 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5315                                       CXXRecordDecl *AnonUnion) {
5316   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5317     return;
5318 
5319   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5320 }
5321 
5322 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5323 /// anonymous structure or union. Anonymous unions are a C++ feature
5324 /// (C++ [class.union]) and a C11 feature; anonymous structures
5325 /// are a C11 feature and GNU C++ extension.
5326 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5327                                         AccessSpecifier AS,
5328                                         RecordDecl *Record,
5329                                         const PrintingPolicy &Policy) {
5330   DeclContext *Owner = Record->getDeclContext();
5331 
5332   // Diagnose whether this anonymous struct/union is an extension.
5333   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5334     Diag(Record->getLocation(), diag::ext_anonymous_union);
5335   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5336     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5337   else if (!Record->isUnion() && !getLangOpts().C11)
5338     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5339 
5340   // C and C++ require different kinds of checks for anonymous
5341   // structs/unions.
5342   bool Invalid = false;
5343   if (getLangOpts().CPlusPlus) {
5344     const char *PrevSpec = nullptr;
5345     if (Record->isUnion()) {
5346       // C++ [class.union]p6:
5347       // C++17 [class.union.anon]p2:
5348       //   Anonymous unions declared in a named namespace or in the
5349       //   global namespace shall be declared static.
5350       unsigned DiagID;
5351       DeclContext *OwnerScope = Owner->getRedeclContext();
5352       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5353           (OwnerScope->isTranslationUnit() ||
5354            (OwnerScope->isNamespace() &&
5355             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5356         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5357           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5358 
5359         // Recover by adding 'static'.
5360         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5361                                PrevSpec, DiagID, Policy);
5362       }
5363       // C++ [class.union]p6:
5364       //   A storage class is not allowed in a declaration of an
5365       //   anonymous union in a class scope.
5366       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5367                isa<RecordDecl>(Owner)) {
5368         Diag(DS.getStorageClassSpecLoc(),
5369              diag::err_anonymous_union_with_storage_spec)
5370           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5371 
5372         // Recover by removing the storage specifier.
5373         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5374                                SourceLocation(),
5375                                PrevSpec, DiagID, Context.getPrintingPolicy());
5376       }
5377     }
5378 
5379     // Ignore const/volatile/restrict qualifiers.
5380     if (DS.getTypeQualifiers()) {
5381       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5382         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5383           << Record->isUnion() << "const"
5384           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5385       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5386         Diag(DS.getVolatileSpecLoc(),
5387              diag::ext_anonymous_struct_union_qualified)
5388           << Record->isUnion() << "volatile"
5389           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5390       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5391         Diag(DS.getRestrictSpecLoc(),
5392              diag::ext_anonymous_struct_union_qualified)
5393           << Record->isUnion() << "restrict"
5394           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5395       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5396         Diag(DS.getAtomicSpecLoc(),
5397              diag::ext_anonymous_struct_union_qualified)
5398           << Record->isUnion() << "_Atomic"
5399           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5400       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5401         Diag(DS.getUnalignedSpecLoc(),
5402              diag::ext_anonymous_struct_union_qualified)
5403           << Record->isUnion() << "__unaligned"
5404           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5405 
5406       DS.ClearTypeQualifiers();
5407     }
5408 
5409     // C++ [class.union]p2:
5410     //   The member-specification of an anonymous union shall only
5411     //   define non-static data members. [Note: nested types and
5412     //   functions cannot be declared within an anonymous union. ]
5413     for (auto *Mem : Record->decls()) {
5414       // Ignore invalid declarations; we already diagnosed them.
5415       if (Mem->isInvalidDecl())
5416         continue;
5417 
5418       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5419         // C++ [class.union]p3:
5420         //   An anonymous union shall not have private or protected
5421         //   members (clause 11).
5422         assert(FD->getAccess() != AS_none);
5423         if (FD->getAccess() != AS_public) {
5424           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5425             << Record->isUnion() << (FD->getAccess() == AS_protected);
5426           Invalid = true;
5427         }
5428 
5429         // C++ [class.union]p1
5430         //   An object of a class with a non-trivial constructor, a non-trivial
5431         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5432         //   assignment operator cannot be a member of a union, nor can an
5433         //   array of such objects.
5434         if (CheckNontrivialField(FD))
5435           Invalid = true;
5436       } else if (Mem->isImplicit()) {
5437         // Any implicit members are fine.
5438       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5439         // This is a type that showed up in an
5440         // elaborated-type-specifier inside the anonymous struct or
5441         // union, but which actually declares a type outside of the
5442         // anonymous struct or union. It's okay.
5443       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5444         if (!MemRecord->isAnonymousStructOrUnion() &&
5445             MemRecord->getDeclName()) {
5446           // Visual C++ allows type definition in anonymous struct or union.
5447           if (getLangOpts().MicrosoftExt)
5448             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5449               << Record->isUnion();
5450           else {
5451             // This is a nested type declaration.
5452             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5453               << Record->isUnion();
5454             Invalid = true;
5455           }
5456         } else {
5457           // This is an anonymous type definition within another anonymous type.
5458           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5459           // not part of standard C++.
5460           Diag(MemRecord->getLocation(),
5461                diag::ext_anonymous_record_with_anonymous_type)
5462             << Record->isUnion();
5463         }
5464       } else if (isa<AccessSpecDecl>(Mem)) {
5465         // Any access specifier is fine.
5466       } else if (isa<StaticAssertDecl>(Mem)) {
5467         // In C++1z, static_assert declarations are also fine.
5468       } else {
5469         // We have something that isn't a non-static data
5470         // member. Complain about it.
5471         unsigned DK = diag::err_anonymous_record_bad_member;
5472         if (isa<TypeDecl>(Mem))
5473           DK = diag::err_anonymous_record_with_type;
5474         else if (isa<FunctionDecl>(Mem))
5475           DK = diag::err_anonymous_record_with_function;
5476         else if (isa<VarDecl>(Mem))
5477           DK = diag::err_anonymous_record_with_static;
5478 
5479         // Visual C++ allows type definition in anonymous struct or union.
5480         if (getLangOpts().MicrosoftExt &&
5481             DK == diag::err_anonymous_record_with_type)
5482           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5483             << Record->isUnion();
5484         else {
5485           Diag(Mem->getLocation(), DK) << Record->isUnion();
5486           Invalid = true;
5487         }
5488       }
5489     }
5490 
5491     // C++11 [class.union]p8 (DR1460):
5492     //   At most one variant member of a union may have a
5493     //   brace-or-equal-initializer.
5494     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5495         Owner->isRecord())
5496       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5497                                 cast<CXXRecordDecl>(Record));
5498   }
5499 
5500   if (!Record->isUnion() && !Owner->isRecord()) {
5501     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5502       << getLangOpts().CPlusPlus;
5503     Invalid = true;
5504   }
5505 
5506   // C++ [dcl.dcl]p3:
5507   //   [If there are no declarators], and except for the declaration of an
5508   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5509   //   names into the program
5510   // C++ [class.mem]p2:
5511   //   each such member-declaration shall either declare at least one member
5512   //   name of the class or declare at least one unnamed bit-field
5513   //
5514   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5515   if (getLangOpts().CPlusPlus && Record->field_empty())
5516     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5517 
5518   // Mock up a declarator.
5519   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5520   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5521   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5522 
5523   // Create a declaration for this anonymous struct/union.
5524   NamedDecl *Anon = nullptr;
5525   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5526     Anon = FieldDecl::Create(
5527         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5528         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5529         /*BitWidth=*/nullptr, /*Mutable=*/false,
5530         /*InitStyle=*/ICIS_NoInit);
5531     Anon->setAccess(AS);
5532     ProcessDeclAttributes(S, Anon, Dc);
5533 
5534     if (getLangOpts().CPlusPlus)
5535       FieldCollector->Add(cast<FieldDecl>(Anon));
5536   } else {
5537     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5538     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5539     if (SCSpec == DeclSpec::SCS_mutable) {
5540       // mutable can only appear on non-static class members, so it's always
5541       // an error here
5542       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5543       Invalid = true;
5544       SC = SC_None;
5545     }
5546 
5547     assert(DS.getAttributes().empty() && "No attribute expected");
5548     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5549                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5550                            Context.getTypeDeclType(Record), TInfo, SC);
5551 
5552     // Default-initialize the implicit variable. This initialization will be
5553     // trivial in almost all cases, except if a union member has an in-class
5554     // initializer:
5555     //   union { int n = 0; };
5556     ActOnUninitializedDecl(Anon);
5557   }
5558   Anon->setImplicit();
5559 
5560   // Mark this as an anonymous struct/union type.
5561   Record->setAnonymousStructOrUnion(true);
5562 
5563   // Add the anonymous struct/union object to the current
5564   // context. We'll be referencing this object when we refer to one of
5565   // its members.
5566   Owner->addDecl(Anon);
5567 
5568   // Inject the members of the anonymous struct/union into the owning
5569   // context and into the identifier resolver chain for name lookup
5570   // purposes.
5571   SmallVector<NamedDecl*, 2> Chain;
5572   Chain.push_back(Anon);
5573 
5574   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5575     Invalid = true;
5576 
5577   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5578     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5579       MangleNumberingContext *MCtx;
5580       Decl *ManglingContextDecl;
5581       std::tie(MCtx, ManglingContextDecl) =
5582           getCurrentMangleNumberContext(NewVD->getDeclContext());
5583       if (MCtx) {
5584         Context.setManglingNumber(
5585             NewVD, MCtx->getManglingNumber(
5586                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5587         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5588       }
5589     }
5590   }
5591 
5592   if (Invalid)
5593     Anon->setInvalidDecl();
5594 
5595   return Anon;
5596 }
5597 
5598 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5599 /// Microsoft C anonymous structure.
5600 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5601 /// Example:
5602 ///
5603 /// struct A { int a; };
5604 /// struct B { struct A; int b; };
5605 ///
5606 /// void foo() {
5607 ///   B var;
5608 ///   var.a = 3;
5609 /// }
5610 ///
5611 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5612                                            RecordDecl *Record) {
5613   assert(Record && "expected a record!");
5614 
5615   // Mock up a declarator.
5616   Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5617   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5618   assert(TInfo && "couldn't build declarator info for anonymous struct");
5619 
5620   auto *ParentDecl = cast<RecordDecl>(CurContext);
5621   QualType RecTy = Context.getTypeDeclType(Record);
5622 
5623   // Create a declaration for this anonymous struct.
5624   NamedDecl *Anon =
5625       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5626                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5627                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5628                         /*InitStyle=*/ICIS_NoInit);
5629   Anon->setImplicit();
5630 
5631   // Add the anonymous struct object to the current context.
5632   CurContext->addDecl(Anon);
5633 
5634   // Inject the members of the anonymous struct into the current
5635   // context and into the identifier resolver chain for name lookup
5636   // purposes.
5637   SmallVector<NamedDecl*, 2> Chain;
5638   Chain.push_back(Anon);
5639 
5640   RecordDecl *RecordDef = Record->getDefinition();
5641   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5642                                diag::err_field_incomplete_or_sizeless) ||
5643       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5644                                           AS_none, Chain)) {
5645     Anon->setInvalidDecl();
5646     ParentDecl->setInvalidDecl();
5647   }
5648 
5649   return Anon;
5650 }
5651 
5652 /// GetNameForDeclarator - Determine the full declaration name for the
5653 /// given Declarator.
5654 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5655   return GetNameFromUnqualifiedId(D.getName());
5656 }
5657 
5658 /// Retrieves the declaration name from a parsed unqualified-id.
5659 DeclarationNameInfo
5660 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5661   DeclarationNameInfo NameInfo;
5662   NameInfo.setLoc(Name.StartLocation);
5663 
5664   switch (Name.getKind()) {
5665 
5666   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5667   case UnqualifiedIdKind::IK_Identifier:
5668     NameInfo.setName(Name.Identifier);
5669     return NameInfo;
5670 
5671   case UnqualifiedIdKind::IK_DeductionGuideName: {
5672     // C++ [temp.deduct.guide]p3:
5673     //   The simple-template-id shall name a class template specialization.
5674     //   The template-name shall be the same identifier as the template-name
5675     //   of the simple-template-id.
5676     // These together intend to imply that the template-name shall name a
5677     // class template.
5678     // FIXME: template<typename T> struct X {};
5679     //        template<typename T> using Y = X<T>;
5680     //        Y(int) -> Y<int>;
5681     //   satisfies these rules but does not name a class template.
5682     TemplateName TN = Name.TemplateName.get().get();
5683     auto *Template = TN.getAsTemplateDecl();
5684     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5685       Diag(Name.StartLocation,
5686            diag::err_deduction_guide_name_not_class_template)
5687         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5688       if (Template)
5689         Diag(Template->getLocation(), diag::note_template_decl_here);
5690       return DeclarationNameInfo();
5691     }
5692 
5693     NameInfo.setName(
5694         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5695     return NameInfo;
5696   }
5697 
5698   case UnqualifiedIdKind::IK_OperatorFunctionId:
5699     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5700                                            Name.OperatorFunctionId.Operator));
5701     NameInfo.setCXXOperatorNameRange(SourceRange(
5702         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5703     return NameInfo;
5704 
5705   case UnqualifiedIdKind::IK_LiteralOperatorId:
5706     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5707                                                            Name.Identifier));
5708     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5709     return NameInfo;
5710 
5711   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5712     TypeSourceInfo *TInfo;
5713     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5714     if (Ty.isNull())
5715       return DeclarationNameInfo();
5716     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5717                                                Context.getCanonicalType(Ty)));
5718     NameInfo.setNamedTypeInfo(TInfo);
5719     return NameInfo;
5720   }
5721 
5722   case UnqualifiedIdKind::IK_ConstructorName: {
5723     TypeSourceInfo *TInfo;
5724     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5725     if (Ty.isNull())
5726       return DeclarationNameInfo();
5727     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5728                                               Context.getCanonicalType(Ty)));
5729     NameInfo.setNamedTypeInfo(TInfo);
5730     return NameInfo;
5731   }
5732 
5733   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5734     // In well-formed code, we can only have a constructor
5735     // template-id that refers to the current context, so go there
5736     // to find the actual type being constructed.
5737     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5738     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5739       return DeclarationNameInfo();
5740 
5741     // Determine the type of the class being constructed.
5742     QualType CurClassType = Context.getTypeDeclType(CurClass);
5743 
5744     // FIXME: Check two things: that the template-id names the same type as
5745     // CurClassType, and that the template-id does not occur when the name
5746     // was qualified.
5747 
5748     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5749                                     Context.getCanonicalType(CurClassType)));
5750     // FIXME: should we retrieve TypeSourceInfo?
5751     NameInfo.setNamedTypeInfo(nullptr);
5752     return NameInfo;
5753   }
5754 
5755   case UnqualifiedIdKind::IK_DestructorName: {
5756     TypeSourceInfo *TInfo;
5757     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5758     if (Ty.isNull())
5759       return DeclarationNameInfo();
5760     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5761                                               Context.getCanonicalType(Ty)));
5762     NameInfo.setNamedTypeInfo(TInfo);
5763     return NameInfo;
5764   }
5765 
5766   case UnqualifiedIdKind::IK_TemplateId: {
5767     TemplateName TName = Name.TemplateId->Template.get();
5768     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5769     return Context.getNameForTemplate(TName, TNameLoc);
5770   }
5771 
5772   } // switch (Name.getKind())
5773 
5774   llvm_unreachable("Unknown name kind");
5775 }
5776 
5777 static QualType getCoreType(QualType Ty) {
5778   do {
5779     if (Ty->isPointerType() || Ty->isReferenceType())
5780       Ty = Ty->getPointeeType();
5781     else if (Ty->isArrayType())
5782       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5783     else
5784       return Ty.withoutLocalFastQualifiers();
5785   } while (true);
5786 }
5787 
5788 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5789 /// and Definition have "nearly" matching parameters. This heuristic is
5790 /// used to improve diagnostics in the case where an out-of-line function
5791 /// definition doesn't match any declaration within the class or namespace.
5792 /// Also sets Params to the list of indices to the parameters that differ
5793 /// between the declaration and the definition. If hasSimilarParameters
5794 /// returns true and Params is empty, then all of the parameters match.
5795 static bool hasSimilarParameters(ASTContext &Context,
5796                                      FunctionDecl *Declaration,
5797                                      FunctionDecl *Definition,
5798                                      SmallVectorImpl<unsigned> &Params) {
5799   Params.clear();
5800   if (Declaration->param_size() != Definition->param_size())
5801     return false;
5802   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5803     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5804     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5805 
5806     // The parameter types are identical
5807     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5808       continue;
5809 
5810     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5811     QualType DefParamBaseTy = getCoreType(DefParamTy);
5812     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5813     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5814 
5815     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5816         (DeclTyName && DeclTyName == DefTyName))
5817       Params.push_back(Idx);
5818     else  // The two parameters aren't even close
5819       return false;
5820   }
5821 
5822   return true;
5823 }
5824 
5825 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5826 /// declarator needs to be rebuilt in the current instantiation.
5827 /// Any bits of declarator which appear before the name are valid for
5828 /// consideration here.  That's specifically the type in the decl spec
5829 /// and the base type in any member-pointer chunks.
5830 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5831                                                     DeclarationName Name) {
5832   // The types we specifically need to rebuild are:
5833   //   - typenames, typeofs, and decltypes
5834   //   - types which will become injected class names
5835   // Of course, we also need to rebuild any type referencing such a
5836   // type.  It's safest to just say "dependent", but we call out a
5837   // few cases here.
5838 
5839   DeclSpec &DS = D.getMutableDeclSpec();
5840   switch (DS.getTypeSpecType()) {
5841   case DeclSpec::TST_typename:
5842   case DeclSpec::TST_typeofType:
5843   case DeclSpec::TST_underlyingType:
5844   case DeclSpec::TST_atomic: {
5845     // Grab the type from the parser.
5846     TypeSourceInfo *TSI = nullptr;
5847     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5848     if (T.isNull() || !T->isInstantiationDependentType()) break;
5849 
5850     // Make sure there's a type source info.  This isn't really much
5851     // of a waste; most dependent types should have type source info
5852     // attached already.
5853     if (!TSI)
5854       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5855 
5856     // Rebuild the type in the current instantiation.
5857     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5858     if (!TSI) return true;
5859 
5860     // Store the new type back in the decl spec.
5861     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5862     DS.UpdateTypeRep(LocType);
5863     break;
5864   }
5865 
5866   case DeclSpec::TST_decltype:
5867   case DeclSpec::TST_typeofExpr: {
5868     Expr *E = DS.getRepAsExpr();
5869     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5870     if (Result.isInvalid()) return true;
5871     DS.UpdateExprRep(Result.get());
5872     break;
5873   }
5874 
5875   default:
5876     // Nothing to do for these decl specs.
5877     break;
5878   }
5879 
5880   // It doesn't matter what order we do this in.
5881   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5882     DeclaratorChunk &Chunk = D.getTypeObject(I);
5883 
5884     // The only type information in the declarator which can come
5885     // before the declaration name is the base type of a member
5886     // pointer.
5887     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5888       continue;
5889 
5890     // Rebuild the scope specifier in-place.
5891     CXXScopeSpec &SS = Chunk.Mem.Scope();
5892     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5893       return true;
5894   }
5895 
5896   return false;
5897 }
5898 
5899 /// Returns true if the declaration is declared in a system header or from a
5900 /// system macro.
5901 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5902   return SM.isInSystemHeader(D->getLocation()) ||
5903          SM.isInSystemMacro(D->getLocation());
5904 }
5905 
5906 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5907   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5908   // of system decl.
5909   if (D->getPreviousDecl() || D->isImplicit())
5910     return;
5911   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5912   if (Status != ReservedIdentifierStatus::NotReserved &&
5913       !isFromSystemHeader(Context.getSourceManager(), D)) {
5914     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5915         << D << static_cast<int>(Status);
5916   }
5917 }
5918 
5919 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5920   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5921 
5922   // Check if we are in an `omp begin/end declare variant` scope. Handle this
5923   // declaration only if the `bind_to_declaration` extension is set.
5924   SmallVector<FunctionDecl *, 4> Bases;
5925   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
5926     if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
5927               implementation_extension_bind_to_declaration))
5928     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
5929         S, D, MultiTemplateParamsArg(), Bases);
5930 
5931   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5932 
5933   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5934       Dcl && Dcl->getDeclContext()->isFileContext())
5935     Dcl->setTopLevelDeclInObjCContainer();
5936 
5937   if (!Bases.empty())
5938     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
5939 
5940   return Dcl;
5941 }
5942 
5943 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5944 ///   If T is the name of a class, then each of the following shall have a
5945 ///   name different from T:
5946 ///     - every static data member of class T;
5947 ///     - every member function of class T
5948 ///     - every member of class T that is itself a type;
5949 /// \returns true if the declaration name violates these rules.
5950 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5951                                    DeclarationNameInfo NameInfo) {
5952   DeclarationName Name = NameInfo.getName();
5953 
5954   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5955   while (Record && Record->isAnonymousStructOrUnion())
5956     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5957   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5958     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5959     return true;
5960   }
5961 
5962   return false;
5963 }
5964 
5965 /// Diagnose a declaration whose declarator-id has the given
5966 /// nested-name-specifier.
5967 ///
5968 /// \param SS The nested-name-specifier of the declarator-id.
5969 ///
5970 /// \param DC The declaration context to which the nested-name-specifier
5971 /// resolves.
5972 ///
5973 /// \param Name The name of the entity being declared.
5974 ///
5975 /// \param Loc The location of the name of the entity being declared.
5976 ///
5977 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5978 /// we're declaring an explicit / partial specialization / instantiation.
5979 ///
5980 /// \returns true if we cannot safely recover from this error, false otherwise.
5981 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5982                                         DeclarationName Name,
5983                                         SourceLocation Loc, bool IsTemplateId) {
5984   DeclContext *Cur = CurContext;
5985   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5986     Cur = Cur->getParent();
5987 
5988   // If the user provided a superfluous scope specifier that refers back to the
5989   // class in which the entity is already declared, diagnose and ignore it.
5990   //
5991   // class X {
5992   //   void X::f();
5993   // };
5994   //
5995   // Note, it was once ill-formed to give redundant qualification in all
5996   // contexts, but that rule was removed by DR482.
5997   if (Cur->Equals(DC)) {
5998     if (Cur->isRecord()) {
5999       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6000                                       : diag::err_member_extra_qualification)
6001         << Name << FixItHint::CreateRemoval(SS.getRange());
6002       SS.clear();
6003     } else {
6004       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6005     }
6006     return false;
6007   }
6008 
6009   // Check whether the qualifying scope encloses the scope of the original
6010   // declaration. For a template-id, we perform the checks in
6011   // CheckTemplateSpecializationScope.
6012   if (!Cur->Encloses(DC) && !IsTemplateId) {
6013     if (Cur->isRecord())
6014       Diag(Loc, diag::err_member_qualification)
6015         << Name << SS.getRange();
6016     else if (isa<TranslationUnitDecl>(DC))
6017       Diag(Loc, diag::err_invalid_declarator_global_scope)
6018         << Name << SS.getRange();
6019     else if (isa<FunctionDecl>(Cur))
6020       Diag(Loc, diag::err_invalid_declarator_in_function)
6021         << Name << SS.getRange();
6022     else if (isa<BlockDecl>(Cur))
6023       Diag(Loc, diag::err_invalid_declarator_in_block)
6024         << Name << SS.getRange();
6025     else if (isa<ExportDecl>(Cur)) {
6026       if (!isa<NamespaceDecl>(DC))
6027         Diag(Loc, diag::err_export_non_namespace_scope_name)
6028             << Name << SS.getRange();
6029       else
6030         // The cases that DC is not NamespaceDecl should be handled in
6031         // CheckRedeclarationExported.
6032         return false;
6033     } else
6034       Diag(Loc, diag::err_invalid_declarator_scope)
6035       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6036 
6037     return true;
6038   }
6039 
6040   if (Cur->isRecord()) {
6041     // Cannot qualify members within a class.
6042     Diag(Loc, diag::err_member_qualification)
6043       << Name << SS.getRange();
6044     SS.clear();
6045 
6046     // C++ constructors and destructors with incorrect scopes can break
6047     // our AST invariants by having the wrong underlying types. If
6048     // that's the case, then drop this declaration entirely.
6049     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6050          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6051         !Context.hasSameType(Name.getCXXNameType(),
6052                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6053       return true;
6054 
6055     return false;
6056   }
6057 
6058   // C++11 [dcl.meaning]p1:
6059   //   [...] "The nested-name-specifier of the qualified declarator-id shall
6060   //   not begin with a decltype-specifer"
6061   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6062   while (SpecLoc.getPrefix())
6063     SpecLoc = SpecLoc.getPrefix();
6064   if (isa_and_nonnull<DecltypeType>(
6065           SpecLoc.getNestedNameSpecifier()->getAsType()))
6066     Diag(Loc, diag::err_decltype_in_declarator)
6067       << SpecLoc.getTypeLoc().getSourceRange();
6068 
6069   return false;
6070 }
6071 
6072 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6073                                   MultiTemplateParamsArg TemplateParamLists) {
6074   // TODO: consider using NameInfo for diagnostic.
6075   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6076   DeclarationName Name = NameInfo.getName();
6077 
6078   // All of these full declarators require an identifier.  If it doesn't have
6079   // one, the ParsedFreeStandingDeclSpec action should be used.
6080   if (D.isDecompositionDeclarator()) {
6081     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6082   } else if (!Name) {
6083     if (!D.isInvalidType())  // Reject this if we think it is valid.
6084       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6085           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6086     return nullptr;
6087   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6088     return nullptr;
6089 
6090   // The scope passed in may not be a decl scope.  Zip up the scope tree until
6091   // we find one that is.
6092   while ((S->getFlags() & Scope::DeclScope) == 0 ||
6093          (S->getFlags() & Scope::TemplateParamScope) != 0)
6094     S = S->getParent();
6095 
6096   DeclContext *DC = CurContext;
6097   if (D.getCXXScopeSpec().isInvalid())
6098     D.setInvalidType();
6099   else if (D.getCXXScopeSpec().isSet()) {
6100     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6101                                         UPPC_DeclarationQualifier))
6102       return nullptr;
6103 
6104     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6105     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6106     if (!DC || isa<EnumDecl>(DC)) {
6107       // If we could not compute the declaration context, it's because the
6108       // declaration context is dependent but does not refer to a class,
6109       // class template, or class template partial specialization. Complain
6110       // and return early, to avoid the coming semantic disaster.
6111       Diag(D.getIdentifierLoc(),
6112            diag::err_template_qualified_declarator_no_match)
6113         << D.getCXXScopeSpec().getScopeRep()
6114         << D.getCXXScopeSpec().getRange();
6115       return nullptr;
6116     }
6117     bool IsDependentContext = DC->isDependentContext();
6118 
6119     if (!IsDependentContext &&
6120         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6121       return nullptr;
6122 
6123     // If a class is incomplete, do not parse entities inside it.
6124     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6125       Diag(D.getIdentifierLoc(),
6126            diag::err_member_def_undefined_record)
6127         << Name << DC << D.getCXXScopeSpec().getRange();
6128       return nullptr;
6129     }
6130     if (!D.getDeclSpec().isFriendSpecified()) {
6131       if (diagnoseQualifiedDeclaration(
6132               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6133               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6134         if (DC->isRecord())
6135           return nullptr;
6136 
6137         D.setInvalidType();
6138       }
6139     }
6140 
6141     // Check whether we need to rebuild the type of the given
6142     // declaration in the current instantiation.
6143     if (EnteringContext && IsDependentContext &&
6144         TemplateParamLists.size() != 0) {
6145       ContextRAII SavedContext(*this, DC);
6146       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6147         D.setInvalidType();
6148     }
6149   }
6150 
6151   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6152   QualType R = TInfo->getType();
6153 
6154   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6155                                       UPPC_DeclarationType))
6156     D.setInvalidType();
6157 
6158   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6159                         forRedeclarationInCurContext());
6160 
6161   // See if this is a redefinition of a variable in the same scope.
6162   if (!D.getCXXScopeSpec().isSet()) {
6163     bool IsLinkageLookup = false;
6164     bool CreateBuiltins = false;
6165 
6166     // If the declaration we're planning to build will be a function
6167     // or object with linkage, then look for another declaration with
6168     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6169     //
6170     // If the declaration we're planning to build will be declared with
6171     // external linkage in the translation unit, create any builtin with
6172     // the same name.
6173     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6174       /* Do nothing*/;
6175     else if (CurContext->isFunctionOrMethod() &&
6176              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6177               R->isFunctionType())) {
6178       IsLinkageLookup = true;
6179       CreateBuiltins =
6180           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6181     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6182                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6183       CreateBuiltins = true;
6184 
6185     if (IsLinkageLookup) {
6186       Previous.clear(LookupRedeclarationWithLinkage);
6187       Previous.setRedeclarationKind(ForExternalRedeclaration);
6188     }
6189 
6190     LookupName(Previous, S, CreateBuiltins);
6191   } else { // Something like "int foo::x;"
6192     LookupQualifiedName(Previous, DC);
6193 
6194     // C++ [dcl.meaning]p1:
6195     //   When the declarator-id is qualified, the declaration shall refer to a
6196     //  previously declared member of the class or namespace to which the
6197     //  qualifier refers (or, in the case of a namespace, of an element of the
6198     //  inline namespace set of that namespace (7.3.1)) or to a specialization
6199     //  thereof; [...]
6200     //
6201     // Note that we already checked the context above, and that we do not have
6202     // enough information to make sure that Previous contains the declaration
6203     // we want to match. For example, given:
6204     //
6205     //   class X {
6206     //     void f();
6207     //     void f(float);
6208     //   };
6209     //
6210     //   void X::f(int) { } // ill-formed
6211     //
6212     // In this case, Previous will point to the overload set
6213     // containing the two f's declared in X, but neither of them
6214     // matches.
6215 
6216     // C++ [dcl.meaning]p1:
6217     //   [...] the member shall not merely have been introduced by a
6218     //   using-declaration in the scope of the class or namespace nominated by
6219     //   the nested-name-specifier of the declarator-id.
6220     RemoveUsingDecls(Previous);
6221   }
6222 
6223   if (Previous.isSingleResult() &&
6224       Previous.getFoundDecl()->isTemplateParameter()) {
6225     // Maybe we will complain about the shadowed template parameter.
6226     if (!D.isInvalidType())
6227       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6228                                       Previous.getFoundDecl());
6229 
6230     // Just pretend that we didn't see the previous declaration.
6231     Previous.clear();
6232   }
6233 
6234   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6235     // Forget that the previous declaration is the injected-class-name.
6236     Previous.clear();
6237 
6238   // In C++, the previous declaration we find might be a tag type
6239   // (class or enum). In this case, the new declaration will hide the
6240   // tag type. Note that this applies to functions, function templates, and
6241   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6242   if (Previous.isSingleTagDecl() &&
6243       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6244       (TemplateParamLists.size() == 0 || R->isFunctionType()))
6245     Previous.clear();
6246 
6247   // Check that there are no default arguments other than in the parameters
6248   // of a function declaration (C++ only).
6249   if (getLangOpts().CPlusPlus)
6250     CheckExtraCXXDefaultArguments(D);
6251 
6252   NamedDecl *New;
6253 
6254   bool AddToScope = true;
6255   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6256     if (TemplateParamLists.size()) {
6257       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6258       return nullptr;
6259     }
6260 
6261     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6262   } else if (R->isFunctionType()) {
6263     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6264                                   TemplateParamLists,
6265                                   AddToScope);
6266   } else {
6267     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6268                                   AddToScope);
6269   }
6270 
6271   if (!New)
6272     return nullptr;
6273 
6274   // If this has an identifier and is not a function template specialization,
6275   // add it to the scope stack.
6276   if (New->getDeclName() && AddToScope)
6277     PushOnScopeChains(New, S);
6278 
6279   if (isInOpenMPDeclareTargetContext())
6280     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6281 
6282   return New;
6283 }
6284 
6285 /// Helper method to turn variable array types into constant array
6286 /// types in certain situations which would otherwise be errors (for
6287 /// GCC compatibility).
6288 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6289                                                     ASTContext &Context,
6290                                                     bool &SizeIsNegative,
6291                                                     llvm::APSInt &Oversized) {
6292   // This method tries to turn a variable array into a constant
6293   // array even when the size isn't an ICE.  This is necessary
6294   // for compatibility with code that depends on gcc's buggy
6295   // constant expression folding, like struct {char x[(int)(char*)2];}
6296   SizeIsNegative = false;
6297   Oversized = 0;
6298 
6299   if (T->isDependentType())
6300     return QualType();
6301 
6302   QualifierCollector Qs;
6303   const Type *Ty = Qs.strip(T);
6304 
6305   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6306     QualType Pointee = PTy->getPointeeType();
6307     QualType FixedType =
6308         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6309                                             Oversized);
6310     if (FixedType.isNull()) return FixedType;
6311     FixedType = Context.getPointerType(FixedType);
6312     return Qs.apply(Context, FixedType);
6313   }
6314   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6315     QualType Inner = PTy->getInnerType();
6316     QualType FixedType =
6317         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6318                                             Oversized);
6319     if (FixedType.isNull()) return FixedType;
6320     FixedType = Context.getParenType(FixedType);
6321     return Qs.apply(Context, FixedType);
6322   }
6323 
6324   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6325   if (!VLATy)
6326     return QualType();
6327 
6328   QualType ElemTy = VLATy->getElementType();
6329   if (ElemTy->isVariablyModifiedType()) {
6330     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6331                                                  SizeIsNegative, Oversized);
6332     if (ElemTy.isNull())
6333       return QualType();
6334   }
6335 
6336   Expr::EvalResult Result;
6337   if (!VLATy->getSizeExpr() ||
6338       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6339     return QualType();
6340 
6341   llvm::APSInt Res = Result.Val.getInt();
6342 
6343   // Check whether the array size is negative.
6344   if (Res.isSigned() && Res.isNegative()) {
6345     SizeIsNegative = true;
6346     return QualType();
6347   }
6348 
6349   // Check whether the array is too large to be addressed.
6350   unsigned ActiveSizeBits =
6351       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6352        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6353           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6354           : Res.getActiveBits();
6355   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6356     Oversized = Res;
6357     return QualType();
6358   }
6359 
6360   QualType FoldedArrayType = Context.getConstantArrayType(
6361       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6362   return Qs.apply(Context, FoldedArrayType);
6363 }
6364 
6365 static void
6366 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6367   SrcTL = SrcTL.getUnqualifiedLoc();
6368   DstTL = DstTL.getUnqualifiedLoc();
6369   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6370     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6371     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6372                                       DstPTL.getPointeeLoc());
6373     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6374     return;
6375   }
6376   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6377     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6378     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6379                                       DstPTL.getInnerLoc());
6380     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6381     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6382     return;
6383   }
6384   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6385   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6386   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6387   TypeLoc DstElemTL = DstATL.getElementLoc();
6388   if (VariableArrayTypeLoc SrcElemATL =
6389           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6390     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6391     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6392   } else {
6393     DstElemTL.initializeFullCopy(SrcElemTL);
6394   }
6395   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6396   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6397   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6398 }
6399 
6400 /// Helper method to turn variable array types into constant array
6401 /// types in certain situations which would otherwise be errors (for
6402 /// GCC compatibility).
6403 static TypeSourceInfo*
6404 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6405                                               ASTContext &Context,
6406                                               bool &SizeIsNegative,
6407                                               llvm::APSInt &Oversized) {
6408   QualType FixedTy
6409     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6410                                           SizeIsNegative, Oversized);
6411   if (FixedTy.isNull())
6412     return nullptr;
6413   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6414   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6415                                     FixedTInfo->getTypeLoc());
6416   return FixedTInfo;
6417 }
6418 
6419 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6420 /// true if we were successful.
6421 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6422                                            QualType &T, SourceLocation Loc,
6423                                            unsigned FailedFoldDiagID) {
6424   bool SizeIsNegative;
6425   llvm::APSInt Oversized;
6426   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6427       TInfo, Context, SizeIsNegative, Oversized);
6428   if (FixedTInfo) {
6429     Diag(Loc, diag::ext_vla_folded_to_constant);
6430     TInfo = FixedTInfo;
6431     T = FixedTInfo->getType();
6432     return true;
6433   }
6434 
6435   if (SizeIsNegative)
6436     Diag(Loc, diag::err_typecheck_negative_array_size);
6437   else if (Oversized.getBoolValue())
6438     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6439   else if (FailedFoldDiagID)
6440     Diag(Loc, FailedFoldDiagID);
6441   return false;
6442 }
6443 
6444 /// Register the given locally-scoped extern "C" declaration so
6445 /// that it can be found later for redeclarations. We include any extern "C"
6446 /// declaration that is not visible in the translation unit here, not just
6447 /// function-scope declarations.
6448 void
6449 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6450   if (!getLangOpts().CPlusPlus &&
6451       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6452     // Don't need to track declarations in the TU in C.
6453     return;
6454 
6455   // Note that we have a locally-scoped external with this name.
6456   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6457 }
6458 
6459 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6460   // FIXME: We can have multiple results via __attribute__((overloadable)).
6461   auto Result = Context.getExternCContextDecl()->lookup(Name);
6462   return Result.empty() ? nullptr : *Result.begin();
6463 }
6464 
6465 /// Diagnose function specifiers on a declaration of an identifier that
6466 /// does not identify a function.
6467 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6468   // FIXME: We should probably indicate the identifier in question to avoid
6469   // confusion for constructs like "virtual int a(), b;"
6470   if (DS.isVirtualSpecified())
6471     Diag(DS.getVirtualSpecLoc(),
6472          diag::err_virtual_non_function);
6473 
6474   if (DS.hasExplicitSpecifier())
6475     Diag(DS.getExplicitSpecLoc(),
6476          diag::err_explicit_non_function);
6477 
6478   if (DS.isNoreturnSpecified())
6479     Diag(DS.getNoreturnSpecLoc(),
6480          diag::err_noreturn_non_function);
6481 }
6482 
6483 NamedDecl*
6484 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6485                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6486   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6487   if (D.getCXXScopeSpec().isSet()) {
6488     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6489       << D.getCXXScopeSpec().getRange();
6490     D.setInvalidType();
6491     // Pretend we didn't see the scope specifier.
6492     DC = CurContext;
6493     Previous.clear();
6494   }
6495 
6496   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6497 
6498   if (D.getDeclSpec().isInlineSpecified())
6499     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6500         << getLangOpts().CPlusPlus17;
6501   if (D.getDeclSpec().hasConstexprSpecifier())
6502     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6503         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6504 
6505   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6506     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6507       Diag(D.getName().StartLocation,
6508            diag::err_deduction_guide_invalid_specifier)
6509           << "typedef";
6510     else
6511       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6512           << D.getName().getSourceRange();
6513     return nullptr;
6514   }
6515 
6516   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6517   if (!NewTD) return nullptr;
6518 
6519   // Handle attributes prior to checking for duplicates in MergeVarDecl
6520   ProcessDeclAttributes(S, NewTD, D);
6521 
6522   CheckTypedefForVariablyModifiedType(S, NewTD);
6523 
6524   bool Redeclaration = D.isRedeclaration();
6525   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6526   D.setRedeclaration(Redeclaration);
6527   return ND;
6528 }
6529 
6530 void
6531 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6532   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6533   // then it shall have block scope.
6534   // Note that variably modified types must be fixed before merging the decl so
6535   // that redeclarations will match.
6536   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6537   QualType T = TInfo->getType();
6538   if (T->isVariablyModifiedType()) {
6539     setFunctionHasBranchProtectedScope();
6540 
6541     if (S->getFnParent() == nullptr) {
6542       bool SizeIsNegative;
6543       llvm::APSInt Oversized;
6544       TypeSourceInfo *FixedTInfo =
6545         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6546                                                       SizeIsNegative,
6547                                                       Oversized);
6548       if (FixedTInfo) {
6549         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6550         NewTD->setTypeSourceInfo(FixedTInfo);
6551       } else {
6552         if (SizeIsNegative)
6553           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6554         else if (T->isVariableArrayType())
6555           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6556         else if (Oversized.getBoolValue())
6557           Diag(NewTD->getLocation(), diag::err_array_too_large)
6558             << toString(Oversized, 10);
6559         else
6560           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6561         NewTD->setInvalidDecl();
6562       }
6563     }
6564   }
6565 }
6566 
6567 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6568 /// declares a typedef-name, either using the 'typedef' type specifier or via
6569 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6570 NamedDecl*
6571 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6572                            LookupResult &Previous, bool &Redeclaration) {
6573 
6574   // Find the shadowed declaration before filtering for scope.
6575   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6576 
6577   // Merge the decl with the existing one if appropriate. If the decl is
6578   // in an outer scope, it isn't the same thing.
6579   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6580                        /*AllowInlineNamespace*/false);
6581   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6582   if (!Previous.empty()) {
6583     Redeclaration = true;
6584     MergeTypedefNameDecl(S, NewTD, Previous);
6585   } else {
6586     inferGslPointerAttribute(NewTD);
6587   }
6588 
6589   if (ShadowedDecl && !Redeclaration)
6590     CheckShadow(NewTD, ShadowedDecl, Previous);
6591 
6592   // If this is the C FILE type, notify the AST context.
6593   if (IdentifierInfo *II = NewTD->getIdentifier())
6594     if (!NewTD->isInvalidDecl() &&
6595         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6596       if (II->isStr("FILE"))
6597         Context.setFILEDecl(NewTD);
6598       else if (II->isStr("jmp_buf"))
6599         Context.setjmp_bufDecl(NewTD);
6600       else if (II->isStr("sigjmp_buf"))
6601         Context.setsigjmp_bufDecl(NewTD);
6602       else if (II->isStr("ucontext_t"))
6603         Context.setucontext_tDecl(NewTD);
6604     }
6605 
6606   return NewTD;
6607 }
6608 
6609 /// Determines whether the given declaration is an out-of-scope
6610 /// previous declaration.
6611 ///
6612 /// This routine should be invoked when name lookup has found a
6613 /// previous declaration (PrevDecl) that is not in the scope where a
6614 /// new declaration by the same name is being introduced. If the new
6615 /// declaration occurs in a local scope, previous declarations with
6616 /// linkage may still be considered previous declarations (C99
6617 /// 6.2.2p4-5, C++ [basic.link]p6).
6618 ///
6619 /// \param PrevDecl the previous declaration found by name
6620 /// lookup
6621 ///
6622 /// \param DC the context in which the new declaration is being
6623 /// declared.
6624 ///
6625 /// \returns true if PrevDecl is an out-of-scope previous declaration
6626 /// for a new delcaration with the same name.
6627 static bool
6628 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6629                                 ASTContext &Context) {
6630   if (!PrevDecl)
6631     return false;
6632 
6633   if (!PrevDecl->hasLinkage())
6634     return false;
6635 
6636   if (Context.getLangOpts().CPlusPlus) {
6637     // C++ [basic.link]p6:
6638     //   If there is a visible declaration of an entity with linkage
6639     //   having the same name and type, ignoring entities declared
6640     //   outside the innermost enclosing namespace scope, the block
6641     //   scope declaration declares that same entity and receives the
6642     //   linkage of the previous declaration.
6643     DeclContext *OuterContext = DC->getRedeclContext();
6644     if (!OuterContext->isFunctionOrMethod())
6645       // This rule only applies to block-scope declarations.
6646       return false;
6647 
6648     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6649     if (PrevOuterContext->isRecord())
6650       // We found a member function: ignore it.
6651       return false;
6652 
6653     // Find the innermost enclosing namespace for the new and
6654     // previous declarations.
6655     OuterContext = OuterContext->getEnclosingNamespaceContext();
6656     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6657 
6658     // The previous declaration is in a different namespace, so it
6659     // isn't the same function.
6660     if (!OuterContext->Equals(PrevOuterContext))
6661       return false;
6662   }
6663 
6664   return true;
6665 }
6666 
6667 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6668   CXXScopeSpec &SS = D.getCXXScopeSpec();
6669   if (!SS.isSet()) return;
6670   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6671 }
6672 
6673 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6674   QualType type = decl->getType();
6675   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6676   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6677     // Various kinds of declaration aren't allowed to be __autoreleasing.
6678     unsigned kind = -1U;
6679     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6680       if (var->hasAttr<BlocksAttr>())
6681         kind = 0; // __block
6682       else if (!var->hasLocalStorage())
6683         kind = 1; // global
6684     } else if (isa<ObjCIvarDecl>(decl)) {
6685       kind = 3; // ivar
6686     } else if (isa<FieldDecl>(decl)) {
6687       kind = 2; // field
6688     }
6689 
6690     if (kind != -1U) {
6691       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6692         << kind;
6693     }
6694   } else if (lifetime == Qualifiers::OCL_None) {
6695     // Try to infer lifetime.
6696     if (!type->isObjCLifetimeType())
6697       return false;
6698 
6699     lifetime = type->getObjCARCImplicitLifetime();
6700     type = Context.getLifetimeQualifiedType(type, lifetime);
6701     decl->setType(type);
6702   }
6703 
6704   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6705     // Thread-local variables cannot have lifetime.
6706     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6707         var->getTLSKind()) {
6708       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6709         << var->getType();
6710       return true;
6711     }
6712   }
6713 
6714   return false;
6715 }
6716 
6717 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6718   if (Decl->getType().hasAddressSpace())
6719     return;
6720   if (Decl->getType()->isDependentType())
6721     return;
6722   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6723     QualType Type = Var->getType();
6724     if (Type->isSamplerT() || Type->isVoidType())
6725       return;
6726     LangAS ImplAS = LangAS::opencl_private;
6727     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6728     // __opencl_c_program_scope_global_variables feature, the address space
6729     // for a variable at program scope or a static or extern variable inside
6730     // a function are inferred to be __global.
6731     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6732         Var->hasGlobalStorage())
6733       ImplAS = LangAS::opencl_global;
6734     // If the original type from a decayed type is an array type and that array
6735     // type has no address space yet, deduce it now.
6736     if (auto DT = dyn_cast<DecayedType>(Type)) {
6737       auto OrigTy = DT->getOriginalType();
6738       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6739         // Add the address space to the original array type and then propagate
6740         // that to the element type through `getAsArrayType`.
6741         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6742         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6743         // Re-generate the decayed type.
6744         Type = Context.getDecayedType(OrigTy);
6745       }
6746     }
6747     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6748     // Apply any qualifiers (including address space) from the array type to
6749     // the element type. This implements C99 6.7.3p8: "If the specification of
6750     // an array type includes any type qualifiers, the element type is so
6751     // qualified, not the array type."
6752     if (Type->isArrayType())
6753       Type = QualType(Context.getAsArrayType(Type), 0);
6754     Decl->setType(Type);
6755   }
6756 }
6757 
6758 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6759   // Ensure that an auto decl is deduced otherwise the checks below might cache
6760   // the wrong linkage.
6761   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6762 
6763   // 'weak' only applies to declarations with external linkage.
6764   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6765     if (!ND.isExternallyVisible()) {
6766       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6767       ND.dropAttr<WeakAttr>();
6768     }
6769   }
6770   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6771     if (ND.isExternallyVisible()) {
6772       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6773       ND.dropAttr<WeakRefAttr>();
6774       ND.dropAttr<AliasAttr>();
6775     }
6776   }
6777 
6778   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6779     if (VD->hasInit()) {
6780       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6781         assert(VD->isThisDeclarationADefinition() &&
6782                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6783         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6784         VD->dropAttr<AliasAttr>();
6785       }
6786     }
6787   }
6788 
6789   // 'selectany' only applies to externally visible variable declarations.
6790   // It does not apply to functions.
6791   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6792     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6793       S.Diag(Attr->getLocation(),
6794              diag::err_attribute_selectany_non_extern_data);
6795       ND.dropAttr<SelectAnyAttr>();
6796     }
6797   }
6798 
6799   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6800     auto *VD = dyn_cast<VarDecl>(&ND);
6801     bool IsAnonymousNS = false;
6802     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6803     if (VD) {
6804       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6805       while (NS && !IsAnonymousNS) {
6806         IsAnonymousNS = NS->isAnonymousNamespace();
6807         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6808       }
6809     }
6810     // dll attributes require external linkage. Static locals may have external
6811     // linkage but still cannot be explicitly imported or exported.
6812     // In Microsoft mode, a variable defined in anonymous namespace must have
6813     // external linkage in order to be exported.
6814     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6815     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6816         (!AnonNSInMicrosoftMode &&
6817          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6818       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6819         << &ND << Attr;
6820       ND.setInvalidDecl();
6821     }
6822   }
6823 
6824   // Check the attributes on the function type, if any.
6825   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6826     // Don't declare this variable in the second operand of the for-statement;
6827     // GCC miscompiles that by ending its lifetime before evaluating the
6828     // third operand. See gcc.gnu.org/PR86769.
6829     AttributedTypeLoc ATL;
6830     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6831          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6832          TL = ATL.getModifiedLoc()) {
6833       // The [[lifetimebound]] attribute can be applied to the implicit object
6834       // parameter of a non-static member function (other than a ctor or dtor)
6835       // by applying it to the function type.
6836       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6837         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6838         if (!MD || MD->isStatic()) {
6839           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6840               << !MD << A->getRange();
6841         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6842           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6843               << isa<CXXDestructorDecl>(MD) << A->getRange();
6844         }
6845       }
6846     }
6847   }
6848 }
6849 
6850 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6851                                            NamedDecl *NewDecl,
6852                                            bool IsSpecialization,
6853                                            bool IsDefinition) {
6854   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6855     return;
6856 
6857   bool IsTemplate = false;
6858   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6859     OldDecl = OldTD->getTemplatedDecl();
6860     IsTemplate = true;
6861     if (!IsSpecialization)
6862       IsDefinition = false;
6863   }
6864   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6865     NewDecl = NewTD->getTemplatedDecl();
6866     IsTemplate = true;
6867   }
6868 
6869   if (!OldDecl || !NewDecl)
6870     return;
6871 
6872   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6873   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6874   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6875   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6876 
6877   // dllimport and dllexport are inheritable attributes so we have to exclude
6878   // inherited attribute instances.
6879   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6880                     (NewExportAttr && !NewExportAttr->isInherited());
6881 
6882   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6883   // the only exception being explicit specializations.
6884   // Implicitly generated declarations are also excluded for now because there
6885   // is no other way to switch these to use dllimport or dllexport.
6886   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6887 
6888   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6889     // Allow with a warning for free functions and global variables.
6890     bool JustWarn = false;
6891     if (!OldDecl->isCXXClassMember()) {
6892       auto *VD = dyn_cast<VarDecl>(OldDecl);
6893       if (VD && !VD->getDescribedVarTemplate())
6894         JustWarn = true;
6895       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6896       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6897         JustWarn = true;
6898     }
6899 
6900     // We cannot change a declaration that's been used because IR has already
6901     // been emitted. Dllimported functions will still work though (modulo
6902     // address equality) as they can use the thunk.
6903     if (OldDecl->isUsed())
6904       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6905         JustWarn = false;
6906 
6907     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6908                                : diag::err_attribute_dll_redeclaration;
6909     S.Diag(NewDecl->getLocation(), DiagID)
6910         << NewDecl
6911         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6912     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6913     if (!JustWarn) {
6914       NewDecl->setInvalidDecl();
6915       return;
6916     }
6917   }
6918 
6919   // A redeclaration is not allowed to drop a dllimport attribute, the only
6920   // exceptions being inline function definitions (except for function
6921   // templates), local extern declarations, qualified friend declarations or
6922   // special MSVC extension: in the last case, the declaration is treated as if
6923   // it were marked dllexport.
6924   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6925   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6926   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6927     // Ignore static data because out-of-line definitions are diagnosed
6928     // separately.
6929     IsStaticDataMember = VD->isStaticDataMember();
6930     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6931                    VarDecl::DeclarationOnly;
6932   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6933     IsInline = FD->isInlined();
6934     IsQualifiedFriend = FD->getQualifier() &&
6935                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6936   }
6937 
6938   if (OldImportAttr && !HasNewAttr &&
6939       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6940       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6941     if (IsMicrosoftABI && IsDefinition) {
6942       S.Diag(NewDecl->getLocation(),
6943              diag::warn_redeclaration_without_import_attribute)
6944           << NewDecl;
6945       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6946       NewDecl->dropAttr<DLLImportAttr>();
6947       NewDecl->addAttr(
6948           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6949     } else {
6950       S.Diag(NewDecl->getLocation(),
6951              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6952           << NewDecl << OldImportAttr;
6953       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6954       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6955       OldDecl->dropAttr<DLLImportAttr>();
6956       NewDecl->dropAttr<DLLImportAttr>();
6957     }
6958   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6959     // In MinGW, seeing a function declared inline drops the dllimport
6960     // attribute.
6961     OldDecl->dropAttr<DLLImportAttr>();
6962     NewDecl->dropAttr<DLLImportAttr>();
6963     S.Diag(NewDecl->getLocation(),
6964            diag::warn_dllimport_dropped_from_inline_function)
6965         << NewDecl << OldImportAttr;
6966   }
6967 
6968   // A specialization of a class template member function is processed here
6969   // since it's a redeclaration. If the parent class is dllexport, the
6970   // specialization inherits that attribute. This doesn't happen automatically
6971   // since the parent class isn't instantiated until later.
6972   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6973     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6974         !NewImportAttr && !NewExportAttr) {
6975       if (const DLLExportAttr *ParentExportAttr =
6976               MD->getParent()->getAttr<DLLExportAttr>()) {
6977         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6978         NewAttr->setInherited(true);
6979         NewDecl->addAttr(NewAttr);
6980       }
6981     }
6982   }
6983 }
6984 
6985 /// Given that we are within the definition of the given function,
6986 /// will that definition behave like C99's 'inline', where the
6987 /// definition is discarded except for optimization purposes?
6988 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6989   // Try to avoid calling GetGVALinkageForFunction.
6990 
6991   // All cases of this require the 'inline' keyword.
6992   if (!FD->isInlined()) return false;
6993 
6994   // This is only possible in C++ with the gnu_inline attribute.
6995   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6996     return false;
6997 
6998   // Okay, go ahead and call the relatively-more-expensive function.
6999   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7000 }
7001 
7002 /// Determine whether a variable is extern "C" prior to attaching
7003 /// an initializer. We can't just call isExternC() here, because that
7004 /// will also compute and cache whether the declaration is externally
7005 /// visible, which might change when we attach the initializer.
7006 ///
7007 /// This can only be used if the declaration is known to not be a
7008 /// redeclaration of an internal linkage declaration.
7009 ///
7010 /// For instance:
7011 ///
7012 ///   auto x = []{};
7013 ///
7014 /// Attaching the initializer here makes this declaration not externally
7015 /// visible, because its type has internal linkage.
7016 ///
7017 /// FIXME: This is a hack.
7018 template<typename T>
7019 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7020   if (S.getLangOpts().CPlusPlus) {
7021     // In C++, the overloadable attribute negates the effects of extern "C".
7022     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7023       return false;
7024 
7025     // So do CUDA's host/device attributes.
7026     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7027                                  D->template hasAttr<CUDAHostAttr>()))
7028       return false;
7029   }
7030   return D->isExternC();
7031 }
7032 
7033 static bool shouldConsiderLinkage(const VarDecl *VD) {
7034   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7035   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7036       isa<OMPDeclareMapperDecl>(DC))
7037     return VD->hasExternalStorage();
7038   if (DC->isFileContext())
7039     return true;
7040   if (DC->isRecord())
7041     return false;
7042   if (isa<RequiresExprBodyDecl>(DC))
7043     return false;
7044   llvm_unreachable("Unexpected context");
7045 }
7046 
7047 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7048   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7049   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7050       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7051     return true;
7052   if (DC->isRecord())
7053     return false;
7054   llvm_unreachable("Unexpected context");
7055 }
7056 
7057 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7058                           ParsedAttr::Kind Kind) {
7059   // Check decl attributes on the DeclSpec.
7060   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7061     return true;
7062 
7063   // Walk the declarator structure, checking decl attributes that were in a type
7064   // position to the decl itself.
7065   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7066     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7067       return true;
7068   }
7069 
7070   // Finally, check attributes on the decl itself.
7071   return PD.getAttributes().hasAttribute(Kind) ||
7072          PD.getDeclarationAttributes().hasAttribute(Kind);
7073 }
7074 
7075 /// Adjust the \c DeclContext for a function or variable that might be a
7076 /// function-local external declaration.
7077 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7078   if (!DC->isFunctionOrMethod())
7079     return false;
7080 
7081   // If this is a local extern function or variable declared within a function
7082   // template, don't add it into the enclosing namespace scope until it is
7083   // instantiated; it might have a dependent type right now.
7084   if (DC->isDependentContext())
7085     return true;
7086 
7087   // C++11 [basic.link]p7:
7088   //   When a block scope declaration of an entity with linkage is not found to
7089   //   refer to some other declaration, then that entity is a member of the
7090   //   innermost enclosing namespace.
7091   //
7092   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7093   // semantically-enclosing namespace, not a lexically-enclosing one.
7094   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7095     DC = DC->getParent();
7096   return true;
7097 }
7098 
7099 /// Returns true if given declaration has external C language linkage.
7100 static bool isDeclExternC(const Decl *D) {
7101   if (const auto *FD = dyn_cast<FunctionDecl>(D))
7102     return FD->isExternC();
7103   if (const auto *VD = dyn_cast<VarDecl>(D))
7104     return VD->isExternC();
7105 
7106   llvm_unreachable("Unknown type of decl!");
7107 }
7108 
7109 /// Returns true if there hasn't been any invalid type diagnosed.
7110 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7111   DeclContext *DC = NewVD->getDeclContext();
7112   QualType R = NewVD->getType();
7113 
7114   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7115   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7116   // argument.
7117   if (R->isImageType() || R->isPipeType()) {
7118     Se.Diag(NewVD->getLocation(),
7119             diag::err_opencl_type_can_only_be_used_as_function_parameter)
7120         << R;
7121     NewVD->setInvalidDecl();
7122     return false;
7123   }
7124 
7125   // OpenCL v1.2 s6.9.r:
7126   // The event type cannot be used to declare a program scope variable.
7127   // OpenCL v2.0 s6.9.q:
7128   // The clk_event_t and reserve_id_t types cannot be declared in program
7129   // scope.
7130   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7131     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7132       Se.Diag(NewVD->getLocation(),
7133               diag::err_invalid_type_for_program_scope_var)
7134           << R;
7135       NewVD->setInvalidDecl();
7136       return false;
7137     }
7138   }
7139 
7140   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7141   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7142                                                Se.getLangOpts())) {
7143     QualType NR = R.getCanonicalType();
7144     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7145            NR->isReferenceType()) {
7146       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7147           NR->isFunctionReferenceType()) {
7148         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7149             << NR->isReferenceType();
7150         NewVD->setInvalidDecl();
7151         return false;
7152       }
7153       NR = NR->getPointeeType();
7154     }
7155   }
7156 
7157   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7158                                                Se.getLangOpts())) {
7159     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7160     // half array type (unless the cl_khr_fp16 extension is enabled).
7161     if (Se.Context.getBaseElementType(R)->isHalfType()) {
7162       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7163       NewVD->setInvalidDecl();
7164       return false;
7165     }
7166   }
7167 
7168   // OpenCL v1.2 s6.9.r:
7169   // The event type cannot be used with the __local, __constant and __global
7170   // address space qualifiers.
7171   if (R->isEventT()) {
7172     if (R.getAddressSpace() != LangAS::opencl_private) {
7173       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7174       NewVD->setInvalidDecl();
7175       return false;
7176     }
7177   }
7178 
7179   if (R->isSamplerT()) {
7180     // OpenCL v1.2 s6.9.b p4:
7181     // The sampler type cannot be used with the __local and __global address
7182     // space qualifiers.
7183     if (R.getAddressSpace() == LangAS::opencl_local ||
7184         R.getAddressSpace() == LangAS::opencl_global) {
7185       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7186       NewVD->setInvalidDecl();
7187     }
7188 
7189     // OpenCL v1.2 s6.12.14.1:
7190     // A global sampler must be declared with either the constant address
7191     // space qualifier or with the const qualifier.
7192     if (DC->isTranslationUnit() &&
7193         !(R.getAddressSpace() == LangAS::opencl_constant ||
7194           R.isConstQualified())) {
7195       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7196       NewVD->setInvalidDecl();
7197     }
7198     if (NewVD->isInvalidDecl())
7199       return false;
7200   }
7201 
7202   return true;
7203 }
7204 
7205 template <typename AttrTy>
7206 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7207   const TypedefNameDecl *TND = TT->getDecl();
7208   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7209     AttrTy *Clone = Attribute->clone(S.Context);
7210     Clone->setInherited(true);
7211     D->addAttr(Clone);
7212   }
7213 }
7214 
7215 NamedDecl *Sema::ActOnVariableDeclarator(
7216     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7217     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7218     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7219   QualType R = TInfo->getType();
7220   DeclarationName Name = GetNameForDeclarator(D).getName();
7221 
7222   IdentifierInfo *II = Name.getAsIdentifierInfo();
7223 
7224   if (D.isDecompositionDeclarator()) {
7225     // Take the name of the first declarator as our name for diagnostic
7226     // purposes.
7227     auto &Decomp = D.getDecompositionDeclarator();
7228     if (!Decomp.bindings().empty()) {
7229       II = Decomp.bindings()[0].Name;
7230       Name = II;
7231     }
7232   } else if (!II) {
7233     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7234     return nullptr;
7235   }
7236 
7237 
7238   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7239   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7240 
7241   // dllimport globals without explicit storage class are treated as extern. We
7242   // have to change the storage class this early to get the right DeclContext.
7243   if (SC == SC_None && !DC->isRecord() &&
7244       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7245       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7246     SC = SC_Extern;
7247 
7248   DeclContext *OriginalDC = DC;
7249   bool IsLocalExternDecl = SC == SC_Extern &&
7250                            adjustContextForLocalExternDecl(DC);
7251 
7252   if (SCSpec == DeclSpec::SCS_mutable) {
7253     // mutable can only appear on non-static class members, so it's always
7254     // an error here
7255     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7256     D.setInvalidType();
7257     SC = SC_None;
7258   }
7259 
7260   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7261       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7262                               D.getDeclSpec().getStorageClassSpecLoc())) {
7263     // In C++11, the 'register' storage class specifier is deprecated.
7264     // Suppress the warning in system macros, it's used in macros in some
7265     // popular C system headers, such as in glibc's htonl() macro.
7266     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7267          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7268                                    : diag::warn_deprecated_register)
7269       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7270   }
7271 
7272   DiagnoseFunctionSpecifiers(D.getDeclSpec());
7273 
7274   if (!DC->isRecord() && S->getFnParent() == nullptr) {
7275     // C99 6.9p2: The storage-class specifiers auto and register shall not
7276     // appear in the declaration specifiers in an external declaration.
7277     // Global Register+Asm is a GNU extension we support.
7278     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7279       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7280       D.setInvalidType();
7281     }
7282   }
7283 
7284   // If this variable has a VLA type and an initializer, try to
7285   // fold to a constant-sized type. This is otherwise invalid.
7286   if (D.hasInitializer() && R->isVariableArrayType())
7287     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7288                                     /*DiagID=*/0);
7289 
7290   bool IsMemberSpecialization = false;
7291   bool IsVariableTemplateSpecialization = false;
7292   bool IsPartialSpecialization = false;
7293   bool IsVariableTemplate = false;
7294   VarDecl *NewVD = nullptr;
7295   VarTemplateDecl *NewTemplate = nullptr;
7296   TemplateParameterList *TemplateParams = nullptr;
7297   if (!getLangOpts().CPlusPlus) {
7298     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7299                             II, R, TInfo, SC);
7300 
7301     if (R->getContainedDeducedType())
7302       ParsingInitForAutoVars.insert(NewVD);
7303 
7304     if (D.isInvalidType())
7305       NewVD->setInvalidDecl();
7306 
7307     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7308         NewVD->hasLocalStorage())
7309       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7310                             NTCUC_AutoVar, NTCUK_Destruct);
7311   } else {
7312     bool Invalid = false;
7313 
7314     if (DC->isRecord() && !CurContext->isRecord()) {
7315       // This is an out-of-line definition of a static data member.
7316       switch (SC) {
7317       case SC_None:
7318         break;
7319       case SC_Static:
7320         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7321              diag::err_static_out_of_line)
7322           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7323         break;
7324       case SC_Auto:
7325       case SC_Register:
7326       case SC_Extern:
7327         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7328         // to names of variables declared in a block or to function parameters.
7329         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7330         // of class members
7331 
7332         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7333              diag::err_storage_class_for_static_member)
7334           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7335         break;
7336       case SC_PrivateExtern:
7337         llvm_unreachable("C storage class in c++!");
7338       }
7339     }
7340 
7341     if (SC == SC_Static && CurContext->isRecord()) {
7342       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7343         // Walk up the enclosing DeclContexts to check for any that are
7344         // incompatible with static data members.
7345         const DeclContext *FunctionOrMethod = nullptr;
7346         const CXXRecordDecl *AnonStruct = nullptr;
7347         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7348           if (Ctxt->isFunctionOrMethod()) {
7349             FunctionOrMethod = Ctxt;
7350             break;
7351           }
7352           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7353           if (ParentDecl && !ParentDecl->getDeclName()) {
7354             AnonStruct = ParentDecl;
7355             break;
7356           }
7357         }
7358         if (FunctionOrMethod) {
7359           // C++ [class.static.data]p5: A local class shall not have static data
7360           // members.
7361           Diag(D.getIdentifierLoc(),
7362                diag::err_static_data_member_not_allowed_in_local_class)
7363             << Name << RD->getDeclName() << RD->getTagKind();
7364         } else if (AnonStruct) {
7365           // C++ [class.static.data]p4: Unnamed classes and classes contained
7366           // directly or indirectly within unnamed classes shall not contain
7367           // static data members.
7368           Diag(D.getIdentifierLoc(),
7369                diag::err_static_data_member_not_allowed_in_anon_struct)
7370             << Name << AnonStruct->getTagKind();
7371           Invalid = true;
7372         } else if (RD->isUnion()) {
7373           // C++98 [class.union]p1: If a union contains a static data member,
7374           // the program is ill-formed. C++11 drops this restriction.
7375           Diag(D.getIdentifierLoc(),
7376                getLangOpts().CPlusPlus11
7377                  ? diag::warn_cxx98_compat_static_data_member_in_union
7378                  : diag::ext_static_data_member_in_union) << Name;
7379         }
7380       }
7381     }
7382 
7383     // Match up the template parameter lists with the scope specifier, then
7384     // determine whether we have a template or a template specialization.
7385     bool InvalidScope = false;
7386     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7387         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7388         D.getCXXScopeSpec(),
7389         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7390             ? D.getName().TemplateId
7391             : nullptr,
7392         TemplateParamLists,
7393         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7394     Invalid |= InvalidScope;
7395 
7396     if (TemplateParams) {
7397       if (!TemplateParams->size() &&
7398           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7399         // There is an extraneous 'template<>' for this variable. Complain
7400         // about it, but allow the declaration of the variable.
7401         Diag(TemplateParams->getTemplateLoc(),
7402              diag::err_template_variable_noparams)
7403           << II
7404           << SourceRange(TemplateParams->getTemplateLoc(),
7405                          TemplateParams->getRAngleLoc());
7406         TemplateParams = nullptr;
7407       } else {
7408         // Check that we can declare a template here.
7409         if (CheckTemplateDeclScope(S, TemplateParams))
7410           return nullptr;
7411 
7412         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7413           // This is an explicit specialization or a partial specialization.
7414           IsVariableTemplateSpecialization = true;
7415           IsPartialSpecialization = TemplateParams->size() > 0;
7416         } else { // if (TemplateParams->size() > 0)
7417           // This is a template declaration.
7418           IsVariableTemplate = true;
7419 
7420           // Only C++1y supports variable templates (N3651).
7421           Diag(D.getIdentifierLoc(),
7422                getLangOpts().CPlusPlus14
7423                    ? diag::warn_cxx11_compat_variable_template
7424                    : diag::ext_variable_template);
7425         }
7426       }
7427     } else {
7428       // Check that we can declare a member specialization here.
7429       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7430           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7431         return nullptr;
7432       assert((Invalid ||
7433               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7434              "should have a 'template<>' for this decl");
7435     }
7436 
7437     if (IsVariableTemplateSpecialization) {
7438       SourceLocation TemplateKWLoc =
7439           TemplateParamLists.size() > 0
7440               ? TemplateParamLists[0]->getTemplateLoc()
7441               : SourceLocation();
7442       DeclResult Res = ActOnVarTemplateSpecialization(
7443           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7444           IsPartialSpecialization);
7445       if (Res.isInvalid())
7446         return nullptr;
7447       NewVD = cast<VarDecl>(Res.get());
7448       AddToScope = false;
7449     } else if (D.isDecompositionDeclarator()) {
7450       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7451                                         D.getIdentifierLoc(), R, TInfo, SC,
7452                                         Bindings);
7453     } else
7454       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7455                               D.getIdentifierLoc(), II, R, TInfo, SC);
7456 
7457     // If this is supposed to be a variable template, create it as such.
7458     if (IsVariableTemplate) {
7459       NewTemplate =
7460           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7461                                   TemplateParams, NewVD);
7462       NewVD->setDescribedVarTemplate(NewTemplate);
7463     }
7464 
7465     // If this decl has an auto type in need of deduction, make a note of the
7466     // Decl so we can diagnose uses of it in its own initializer.
7467     if (R->getContainedDeducedType())
7468       ParsingInitForAutoVars.insert(NewVD);
7469 
7470     if (D.isInvalidType() || Invalid) {
7471       NewVD->setInvalidDecl();
7472       if (NewTemplate)
7473         NewTemplate->setInvalidDecl();
7474     }
7475 
7476     SetNestedNameSpecifier(*this, NewVD, D);
7477 
7478     // If we have any template parameter lists that don't directly belong to
7479     // the variable (matching the scope specifier), store them.
7480     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7481     if (TemplateParamLists.size() > VDTemplateParamLists)
7482       NewVD->setTemplateParameterListsInfo(
7483           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7484   }
7485 
7486   if (D.getDeclSpec().isInlineSpecified()) {
7487     if (!getLangOpts().CPlusPlus) {
7488       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7489           << 0;
7490     } else if (CurContext->isFunctionOrMethod()) {
7491       // 'inline' is not allowed on block scope variable declaration.
7492       Diag(D.getDeclSpec().getInlineSpecLoc(),
7493            diag::err_inline_declaration_block_scope) << Name
7494         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7495     } else {
7496       Diag(D.getDeclSpec().getInlineSpecLoc(),
7497            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7498                                      : diag::ext_inline_variable);
7499       NewVD->setInlineSpecified();
7500     }
7501   }
7502 
7503   // Set the lexical context. If the declarator has a C++ scope specifier, the
7504   // lexical context will be different from the semantic context.
7505   NewVD->setLexicalDeclContext(CurContext);
7506   if (NewTemplate)
7507     NewTemplate->setLexicalDeclContext(CurContext);
7508 
7509   if (IsLocalExternDecl) {
7510     if (D.isDecompositionDeclarator())
7511       for (auto *B : Bindings)
7512         B->setLocalExternDecl();
7513     else
7514       NewVD->setLocalExternDecl();
7515   }
7516 
7517   bool EmitTLSUnsupportedError = false;
7518   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7519     // C++11 [dcl.stc]p4:
7520     //   When thread_local is applied to a variable of block scope the
7521     //   storage-class-specifier static is implied if it does not appear
7522     //   explicitly.
7523     // Core issue: 'static' is not implied if the variable is declared
7524     //   'extern'.
7525     if (NewVD->hasLocalStorage() &&
7526         (SCSpec != DeclSpec::SCS_unspecified ||
7527          TSCS != DeclSpec::TSCS_thread_local ||
7528          !DC->isFunctionOrMethod()))
7529       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7530            diag::err_thread_non_global)
7531         << DeclSpec::getSpecifierName(TSCS);
7532     else if (!Context.getTargetInfo().isTLSSupported()) {
7533       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7534           getLangOpts().SYCLIsDevice) {
7535         // Postpone error emission until we've collected attributes required to
7536         // figure out whether it's a host or device variable and whether the
7537         // error should be ignored.
7538         EmitTLSUnsupportedError = true;
7539         // We still need to mark the variable as TLS so it shows up in AST with
7540         // proper storage class for other tools to use even if we're not going
7541         // to emit any code for it.
7542         NewVD->setTSCSpec(TSCS);
7543       } else
7544         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7545              diag::err_thread_unsupported);
7546     } else
7547       NewVD->setTSCSpec(TSCS);
7548   }
7549 
7550   switch (D.getDeclSpec().getConstexprSpecifier()) {
7551   case ConstexprSpecKind::Unspecified:
7552     break;
7553 
7554   case ConstexprSpecKind::Consteval:
7555     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7556          diag::err_constexpr_wrong_decl_kind)
7557         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7558     LLVM_FALLTHROUGH;
7559 
7560   case ConstexprSpecKind::Constexpr:
7561     NewVD->setConstexpr(true);
7562     // C++1z [dcl.spec.constexpr]p1:
7563     //   A static data member declared with the constexpr specifier is
7564     //   implicitly an inline variable.
7565     if (NewVD->isStaticDataMember() &&
7566         (getLangOpts().CPlusPlus17 ||
7567          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7568       NewVD->setImplicitlyInline();
7569     break;
7570 
7571   case ConstexprSpecKind::Constinit:
7572     if (!NewVD->hasGlobalStorage())
7573       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7574            diag::err_constinit_local_variable);
7575     else
7576       NewVD->addAttr(ConstInitAttr::Create(
7577           Context, D.getDeclSpec().getConstexprSpecLoc(),
7578           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7579     break;
7580   }
7581 
7582   // C99 6.7.4p3
7583   //   An inline definition of a function with external linkage shall
7584   //   not contain a definition of a modifiable object with static or
7585   //   thread storage duration...
7586   // We only apply this when the function is required to be defined
7587   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7588   // that a local variable with thread storage duration still has to
7589   // be marked 'static'.  Also note that it's possible to get these
7590   // semantics in C++ using __attribute__((gnu_inline)).
7591   if (SC == SC_Static && S->getFnParent() != nullptr &&
7592       !NewVD->getType().isConstQualified()) {
7593     FunctionDecl *CurFD = getCurFunctionDecl();
7594     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7595       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7596            diag::warn_static_local_in_extern_inline);
7597       MaybeSuggestAddingStaticToDecl(CurFD);
7598     }
7599   }
7600 
7601   if (D.getDeclSpec().isModulePrivateSpecified()) {
7602     if (IsVariableTemplateSpecialization)
7603       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7604           << (IsPartialSpecialization ? 1 : 0)
7605           << FixItHint::CreateRemoval(
7606                  D.getDeclSpec().getModulePrivateSpecLoc());
7607     else if (IsMemberSpecialization)
7608       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7609         << 2
7610         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7611     else if (NewVD->hasLocalStorage())
7612       Diag(NewVD->getLocation(), diag::err_module_private_local)
7613           << 0 << NewVD
7614           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7615           << FixItHint::CreateRemoval(
7616                  D.getDeclSpec().getModulePrivateSpecLoc());
7617     else {
7618       NewVD->setModulePrivate();
7619       if (NewTemplate)
7620         NewTemplate->setModulePrivate();
7621       for (auto *B : Bindings)
7622         B->setModulePrivate();
7623     }
7624   }
7625 
7626   if (getLangOpts().OpenCL) {
7627     deduceOpenCLAddressSpace(NewVD);
7628 
7629     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7630     if (TSC != TSCS_unspecified) {
7631       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7632            diag::err_opencl_unknown_type_specifier)
7633           << getLangOpts().getOpenCLVersionString()
7634           << DeclSpec::getSpecifierName(TSC) << 1;
7635       NewVD->setInvalidDecl();
7636     }
7637   }
7638 
7639   // Handle attributes prior to checking for duplicates in MergeVarDecl
7640   ProcessDeclAttributes(S, NewVD, D);
7641 
7642   // FIXME: This is probably the wrong location to be doing this and we should
7643   // probably be doing this for more attributes (especially for function
7644   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7645   // the code to copy attributes would be generated by TableGen.
7646   if (R->isFunctionPointerType())
7647     if (const auto *TT = R->getAs<TypedefType>())
7648       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7649 
7650   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7651       getLangOpts().SYCLIsDevice) {
7652     if (EmitTLSUnsupportedError &&
7653         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7654          (getLangOpts().OpenMPIsDevice &&
7655           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7656       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7657            diag::err_thread_unsupported);
7658 
7659     if (EmitTLSUnsupportedError &&
7660         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7661       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7662     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7663     // storage [duration]."
7664     if (SC == SC_None && S->getFnParent() != nullptr &&
7665         (NewVD->hasAttr<CUDASharedAttr>() ||
7666          NewVD->hasAttr<CUDAConstantAttr>())) {
7667       NewVD->setStorageClass(SC_Static);
7668     }
7669   }
7670 
7671   // Ensure that dllimport globals without explicit storage class are treated as
7672   // extern. The storage class is set above using parsed attributes. Now we can
7673   // check the VarDecl itself.
7674   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7675          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7676          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7677 
7678   // In auto-retain/release, infer strong retension for variables of
7679   // retainable type.
7680   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7681     NewVD->setInvalidDecl();
7682 
7683   // Handle GNU asm-label extension (encoded as an attribute).
7684   if (Expr *E = (Expr*)D.getAsmLabel()) {
7685     // The parser guarantees this is a string.
7686     StringLiteral *SE = cast<StringLiteral>(E);
7687     StringRef Label = SE->getString();
7688     if (S->getFnParent() != nullptr) {
7689       switch (SC) {
7690       case SC_None:
7691       case SC_Auto:
7692         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7693         break;
7694       case SC_Register:
7695         // Local Named register
7696         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7697             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7698           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7699         break;
7700       case SC_Static:
7701       case SC_Extern:
7702       case SC_PrivateExtern:
7703         break;
7704       }
7705     } else if (SC == SC_Register) {
7706       // Global Named register
7707       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7708         const auto &TI = Context.getTargetInfo();
7709         bool HasSizeMismatch;
7710 
7711         if (!TI.isValidGCCRegisterName(Label))
7712           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7713         else if (!TI.validateGlobalRegisterVariable(Label,
7714                                                     Context.getTypeSize(R),
7715                                                     HasSizeMismatch))
7716           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7717         else if (HasSizeMismatch)
7718           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7719       }
7720 
7721       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7722         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7723         NewVD->setInvalidDecl(true);
7724       }
7725     }
7726 
7727     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7728                                         /*IsLiteralLabel=*/true,
7729                                         SE->getStrTokenLoc(0)));
7730   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7731     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7732       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7733     if (I != ExtnameUndeclaredIdentifiers.end()) {
7734       if (isDeclExternC(NewVD)) {
7735         NewVD->addAttr(I->second);
7736         ExtnameUndeclaredIdentifiers.erase(I);
7737       } else
7738         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7739             << /*Variable*/1 << NewVD;
7740     }
7741   }
7742 
7743   // Find the shadowed declaration before filtering for scope.
7744   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7745                                 ? getShadowedDeclaration(NewVD, Previous)
7746                                 : nullptr;
7747 
7748   // Don't consider existing declarations that are in a different
7749   // scope and are out-of-semantic-context declarations (if the new
7750   // declaration has linkage).
7751   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7752                        D.getCXXScopeSpec().isNotEmpty() ||
7753                        IsMemberSpecialization ||
7754                        IsVariableTemplateSpecialization);
7755 
7756   // Check whether the previous declaration is in the same block scope. This
7757   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7758   if (getLangOpts().CPlusPlus &&
7759       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7760     NewVD->setPreviousDeclInSameBlockScope(
7761         Previous.isSingleResult() && !Previous.isShadowed() &&
7762         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7763 
7764   if (!getLangOpts().CPlusPlus) {
7765     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7766   } else {
7767     // If this is an explicit specialization of a static data member, check it.
7768     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7769         CheckMemberSpecialization(NewVD, Previous))
7770       NewVD->setInvalidDecl();
7771 
7772     // Merge the decl with the existing one if appropriate.
7773     if (!Previous.empty()) {
7774       if (Previous.isSingleResult() &&
7775           isa<FieldDecl>(Previous.getFoundDecl()) &&
7776           D.getCXXScopeSpec().isSet()) {
7777         // The user tried to define a non-static data member
7778         // out-of-line (C++ [dcl.meaning]p1).
7779         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7780           << D.getCXXScopeSpec().getRange();
7781         Previous.clear();
7782         NewVD->setInvalidDecl();
7783       }
7784     } else if (D.getCXXScopeSpec().isSet()) {
7785       // No previous declaration in the qualifying scope.
7786       Diag(D.getIdentifierLoc(), diag::err_no_member)
7787         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7788         << D.getCXXScopeSpec().getRange();
7789       NewVD->setInvalidDecl();
7790     }
7791 
7792     if (!IsVariableTemplateSpecialization)
7793       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7794 
7795     if (NewTemplate) {
7796       VarTemplateDecl *PrevVarTemplate =
7797           NewVD->getPreviousDecl()
7798               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7799               : nullptr;
7800 
7801       // Check the template parameter list of this declaration, possibly
7802       // merging in the template parameter list from the previous variable
7803       // template declaration.
7804       if (CheckTemplateParameterList(
7805               TemplateParams,
7806               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7807                               : nullptr,
7808               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7809                DC->isDependentContext())
7810                   ? TPC_ClassTemplateMember
7811                   : TPC_VarTemplate))
7812         NewVD->setInvalidDecl();
7813 
7814       // If we are providing an explicit specialization of a static variable
7815       // template, make a note of that.
7816       if (PrevVarTemplate &&
7817           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7818         PrevVarTemplate->setMemberSpecialization();
7819     }
7820   }
7821 
7822   // Diagnose shadowed variables iff this isn't a redeclaration.
7823   if (ShadowedDecl && !D.isRedeclaration())
7824     CheckShadow(NewVD, ShadowedDecl, Previous);
7825 
7826   ProcessPragmaWeak(S, NewVD);
7827 
7828   // If this is the first declaration of an extern C variable, update
7829   // the map of such variables.
7830   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7831       isIncompleteDeclExternC(*this, NewVD))
7832     RegisterLocallyScopedExternCDecl(NewVD, S);
7833 
7834   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7835     MangleNumberingContext *MCtx;
7836     Decl *ManglingContextDecl;
7837     std::tie(MCtx, ManglingContextDecl) =
7838         getCurrentMangleNumberContext(NewVD->getDeclContext());
7839     if (MCtx) {
7840       Context.setManglingNumber(
7841           NewVD, MCtx->getManglingNumber(
7842                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7843       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7844     }
7845   }
7846 
7847   // Special handling of variable named 'main'.
7848   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7849       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7850       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7851 
7852     // C++ [basic.start.main]p3
7853     // A program that declares a variable main at global scope is ill-formed.
7854     if (getLangOpts().CPlusPlus)
7855       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7856 
7857     // In C, and external-linkage variable named main results in undefined
7858     // behavior.
7859     else if (NewVD->hasExternalFormalLinkage())
7860       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7861   }
7862 
7863   if (D.isRedeclaration() && !Previous.empty()) {
7864     NamedDecl *Prev = Previous.getRepresentativeDecl();
7865     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7866                                    D.isFunctionDefinition());
7867   }
7868 
7869   if (NewTemplate) {
7870     if (NewVD->isInvalidDecl())
7871       NewTemplate->setInvalidDecl();
7872     ActOnDocumentableDecl(NewTemplate);
7873     return NewTemplate;
7874   }
7875 
7876   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7877     CompleteMemberSpecialization(NewVD, Previous);
7878 
7879   return NewVD;
7880 }
7881 
7882 /// Enum describing the %select options in diag::warn_decl_shadow.
7883 enum ShadowedDeclKind {
7884   SDK_Local,
7885   SDK_Global,
7886   SDK_StaticMember,
7887   SDK_Field,
7888   SDK_Typedef,
7889   SDK_Using,
7890   SDK_StructuredBinding
7891 };
7892 
7893 /// Determine what kind of declaration we're shadowing.
7894 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7895                                                 const DeclContext *OldDC) {
7896   if (isa<TypeAliasDecl>(ShadowedDecl))
7897     return SDK_Using;
7898   else if (isa<TypedefDecl>(ShadowedDecl))
7899     return SDK_Typedef;
7900   else if (isa<BindingDecl>(ShadowedDecl))
7901     return SDK_StructuredBinding;
7902   else if (isa<RecordDecl>(OldDC))
7903     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7904 
7905   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7906 }
7907 
7908 /// Return the location of the capture if the given lambda captures the given
7909 /// variable \p VD, or an invalid source location otherwise.
7910 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7911                                          const VarDecl *VD) {
7912   for (const Capture &Capture : LSI->Captures) {
7913     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7914       return Capture.getLocation();
7915   }
7916   return SourceLocation();
7917 }
7918 
7919 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7920                                      const LookupResult &R) {
7921   // Only diagnose if we're shadowing an unambiguous field or variable.
7922   if (R.getResultKind() != LookupResult::Found)
7923     return false;
7924 
7925   // Return false if warning is ignored.
7926   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7927 }
7928 
7929 /// Return the declaration shadowed by the given variable \p D, or null
7930 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7931 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7932                                         const LookupResult &R) {
7933   if (!shouldWarnIfShadowedDecl(Diags, R))
7934     return nullptr;
7935 
7936   // Don't diagnose declarations at file scope.
7937   if (D->hasGlobalStorage())
7938     return nullptr;
7939 
7940   NamedDecl *ShadowedDecl = R.getFoundDecl();
7941   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7942                                                             : nullptr;
7943 }
7944 
7945 /// Return the declaration shadowed by the given typedef \p D, or null
7946 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7947 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7948                                         const LookupResult &R) {
7949   // Don't warn if typedef declaration is part of a class
7950   if (D->getDeclContext()->isRecord())
7951     return nullptr;
7952 
7953   if (!shouldWarnIfShadowedDecl(Diags, R))
7954     return nullptr;
7955 
7956   NamedDecl *ShadowedDecl = R.getFoundDecl();
7957   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7958 }
7959 
7960 /// Return the declaration shadowed by the given variable \p D, or null
7961 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7962 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7963                                         const LookupResult &R) {
7964   if (!shouldWarnIfShadowedDecl(Diags, R))
7965     return nullptr;
7966 
7967   NamedDecl *ShadowedDecl = R.getFoundDecl();
7968   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7969                                                             : nullptr;
7970 }
7971 
7972 /// Diagnose variable or built-in function shadowing.  Implements
7973 /// -Wshadow.
7974 ///
7975 /// This method is called whenever a VarDecl is added to a "useful"
7976 /// scope.
7977 ///
7978 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7979 /// \param R the lookup of the name
7980 ///
7981 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7982                        const LookupResult &R) {
7983   DeclContext *NewDC = D->getDeclContext();
7984 
7985   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7986     // Fields are not shadowed by variables in C++ static methods.
7987     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7988       if (MD->isStatic())
7989         return;
7990 
7991     // Fields shadowed by constructor parameters are a special case. Usually
7992     // the constructor initializes the field with the parameter.
7993     if (isa<CXXConstructorDecl>(NewDC))
7994       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7995         // Remember that this was shadowed so we can either warn about its
7996         // modification or its existence depending on warning settings.
7997         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7998         return;
7999       }
8000   }
8001 
8002   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8003     if (shadowedVar->isExternC()) {
8004       // For shadowing external vars, make sure that we point to the global
8005       // declaration, not a locally scoped extern declaration.
8006       for (auto I : shadowedVar->redecls())
8007         if (I->isFileVarDecl()) {
8008           ShadowedDecl = I;
8009           break;
8010         }
8011     }
8012 
8013   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8014 
8015   unsigned WarningDiag = diag::warn_decl_shadow;
8016   SourceLocation CaptureLoc;
8017   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8018       isa<CXXMethodDecl>(NewDC)) {
8019     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8020       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8021         if (RD->getLambdaCaptureDefault() == LCD_None) {
8022           // Try to avoid warnings for lambdas with an explicit capture list.
8023           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8024           // Warn only when the lambda captures the shadowed decl explicitly.
8025           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8026           if (CaptureLoc.isInvalid())
8027             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8028         } else {
8029           // Remember that this was shadowed so we can avoid the warning if the
8030           // shadowed decl isn't captured and the warning settings allow it.
8031           cast<LambdaScopeInfo>(getCurFunction())
8032               ->ShadowingDecls.push_back(
8033                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8034           return;
8035         }
8036       }
8037 
8038       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8039         // A variable can't shadow a local variable in an enclosing scope, if
8040         // they are separated by a non-capturing declaration context.
8041         for (DeclContext *ParentDC = NewDC;
8042              ParentDC && !ParentDC->Equals(OldDC);
8043              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8044           // Only block literals, captured statements, and lambda expressions
8045           // can capture; other scopes don't.
8046           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8047               !isLambdaCallOperator(ParentDC)) {
8048             return;
8049           }
8050         }
8051       }
8052     }
8053   }
8054 
8055   // Only warn about certain kinds of shadowing for class members.
8056   if (NewDC && NewDC->isRecord()) {
8057     // In particular, don't warn about shadowing non-class members.
8058     if (!OldDC->isRecord())
8059       return;
8060 
8061     // TODO: should we warn about static data members shadowing
8062     // static data members from base classes?
8063 
8064     // TODO: don't diagnose for inaccessible shadowed members.
8065     // This is hard to do perfectly because we might friend the
8066     // shadowing context, but that's just a false negative.
8067   }
8068 
8069 
8070   DeclarationName Name = R.getLookupName();
8071 
8072   // Emit warning and note.
8073   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8074   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8075   if (!CaptureLoc.isInvalid())
8076     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8077         << Name << /*explicitly*/ 1;
8078   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8079 }
8080 
8081 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8082 /// when these variables are captured by the lambda.
8083 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8084   for (const auto &Shadow : LSI->ShadowingDecls) {
8085     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8086     // Try to avoid the warning when the shadowed decl isn't captured.
8087     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8088     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8089     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8090                                        ? diag::warn_decl_shadow_uncaptured_local
8091                                        : diag::warn_decl_shadow)
8092         << Shadow.VD->getDeclName()
8093         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8094     if (!CaptureLoc.isInvalid())
8095       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8096           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8097     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8098   }
8099 }
8100 
8101 /// Check -Wshadow without the advantage of a previous lookup.
8102 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8103   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8104     return;
8105 
8106   LookupResult R(*this, D->getDeclName(), D->getLocation(),
8107                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8108   LookupName(R, S);
8109   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8110     CheckShadow(D, ShadowedDecl, R);
8111 }
8112 
8113 /// Check if 'E', which is an expression that is about to be modified, refers
8114 /// to a constructor parameter that shadows a field.
8115 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8116   // Quickly ignore expressions that can't be shadowing ctor parameters.
8117   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8118     return;
8119   E = E->IgnoreParenImpCasts();
8120   auto *DRE = dyn_cast<DeclRefExpr>(E);
8121   if (!DRE)
8122     return;
8123   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8124   auto I = ShadowingDecls.find(D);
8125   if (I == ShadowingDecls.end())
8126     return;
8127   const NamedDecl *ShadowedDecl = I->second;
8128   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8129   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8130   Diag(D->getLocation(), diag::note_var_declared_here) << D;
8131   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8132 
8133   // Avoid issuing multiple warnings about the same decl.
8134   ShadowingDecls.erase(I);
8135 }
8136 
8137 /// Check for conflict between this global or extern "C" declaration and
8138 /// previous global or extern "C" declarations. This is only used in C++.
8139 template<typename T>
8140 static bool checkGlobalOrExternCConflict(
8141     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8142   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8143   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8144 
8145   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8146     // The common case: this global doesn't conflict with any extern "C"
8147     // declaration.
8148     return false;
8149   }
8150 
8151   if (Prev) {
8152     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8153       // Both the old and new declarations have C language linkage. This is a
8154       // redeclaration.
8155       Previous.clear();
8156       Previous.addDecl(Prev);
8157       return true;
8158     }
8159 
8160     // This is a global, non-extern "C" declaration, and there is a previous
8161     // non-global extern "C" declaration. Diagnose if this is a variable
8162     // declaration.
8163     if (!isa<VarDecl>(ND))
8164       return false;
8165   } else {
8166     // The declaration is extern "C". Check for any declaration in the
8167     // translation unit which might conflict.
8168     if (IsGlobal) {
8169       // We have already performed the lookup into the translation unit.
8170       IsGlobal = false;
8171       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8172            I != E; ++I) {
8173         if (isa<VarDecl>(*I)) {
8174           Prev = *I;
8175           break;
8176         }
8177       }
8178     } else {
8179       DeclContext::lookup_result R =
8180           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8181       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8182            I != E; ++I) {
8183         if (isa<VarDecl>(*I)) {
8184           Prev = *I;
8185           break;
8186         }
8187         // FIXME: If we have any other entity with this name in global scope,
8188         // the declaration is ill-formed, but that is a defect: it breaks the
8189         // 'stat' hack, for instance. Only variables can have mangled name
8190         // clashes with extern "C" declarations, so only they deserve a
8191         // diagnostic.
8192       }
8193     }
8194 
8195     if (!Prev)
8196       return false;
8197   }
8198 
8199   // Use the first declaration's location to ensure we point at something which
8200   // is lexically inside an extern "C" linkage-spec.
8201   assert(Prev && "should have found a previous declaration to diagnose");
8202   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8203     Prev = FD->getFirstDecl();
8204   else
8205     Prev = cast<VarDecl>(Prev)->getFirstDecl();
8206 
8207   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8208     << IsGlobal << ND;
8209   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8210     << IsGlobal;
8211   return false;
8212 }
8213 
8214 /// Apply special rules for handling extern "C" declarations. Returns \c true
8215 /// if we have found that this is a redeclaration of some prior entity.
8216 ///
8217 /// Per C++ [dcl.link]p6:
8218 ///   Two declarations [for a function or variable] with C language linkage
8219 ///   with the same name that appear in different scopes refer to the same
8220 ///   [entity]. An entity with C language linkage shall not be declared with
8221 ///   the same name as an entity in global scope.
8222 template<typename T>
8223 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8224                                                   LookupResult &Previous) {
8225   if (!S.getLangOpts().CPlusPlus) {
8226     // In C, when declaring a global variable, look for a corresponding 'extern'
8227     // variable declared in function scope. We don't need this in C++, because
8228     // we find local extern decls in the surrounding file-scope DeclContext.
8229     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8230       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8231         Previous.clear();
8232         Previous.addDecl(Prev);
8233         return true;
8234       }
8235     }
8236     return false;
8237   }
8238 
8239   // A declaration in the translation unit can conflict with an extern "C"
8240   // declaration.
8241   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8242     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8243 
8244   // An extern "C" declaration can conflict with a declaration in the
8245   // translation unit or can be a redeclaration of an extern "C" declaration
8246   // in another scope.
8247   if (isIncompleteDeclExternC(S,ND))
8248     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8249 
8250   // Neither global nor extern "C": nothing to do.
8251   return false;
8252 }
8253 
8254 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8255   // If the decl is already known invalid, don't check it.
8256   if (NewVD->isInvalidDecl())
8257     return;
8258 
8259   QualType T = NewVD->getType();
8260 
8261   // Defer checking an 'auto' type until its initializer is attached.
8262   if (T->isUndeducedType())
8263     return;
8264 
8265   if (NewVD->hasAttrs())
8266     CheckAlignasUnderalignment(NewVD);
8267 
8268   if (T->isObjCObjectType()) {
8269     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8270       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8271     T = Context.getObjCObjectPointerType(T);
8272     NewVD->setType(T);
8273   }
8274 
8275   // Emit an error if an address space was applied to decl with local storage.
8276   // This includes arrays of objects with address space qualifiers, but not
8277   // automatic variables that point to other address spaces.
8278   // ISO/IEC TR 18037 S5.1.2
8279   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8280       T.getAddressSpace() != LangAS::Default) {
8281     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8282     NewVD->setInvalidDecl();
8283     return;
8284   }
8285 
8286   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8287   // scope.
8288   if (getLangOpts().OpenCLVersion == 120 &&
8289       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8290                                             getLangOpts()) &&
8291       NewVD->isStaticLocal()) {
8292     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8293     NewVD->setInvalidDecl();
8294     return;
8295   }
8296 
8297   if (getLangOpts().OpenCL) {
8298     if (!diagnoseOpenCLTypes(*this, NewVD))
8299       return;
8300 
8301     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8302     if (NewVD->hasAttr<BlocksAttr>()) {
8303       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8304       return;
8305     }
8306 
8307     if (T->isBlockPointerType()) {
8308       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8309       // can't use 'extern' storage class.
8310       if (!T.isConstQualified()) {
8311         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8312             << 0 /*const*/;
8313         NewVD->setInvalidDecl();
8314         return;
8315       }
8316       if (NewVD->hasExternalStorage()) {
8317         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8318         NewVD->setInvalidDecl();
8319         return;
8320       }
8321     }
8322 
8323     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8324     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8325         NewVD->hasExternalStorage()) {
8326       if (!T->isSamplerT() && !T->isDependentType() &&
8327           !(T.getAddressSpace() == LangAS::opencl_constant ||
8328             (T.getAddressSpace() == LangAS::opencl_global &&
8329              getOpenCLOptions().areProgramScopeVariablesSupported(
8330                  getLangOpts())))) {
8331         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8332         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8333           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8334               << Scope << "global or constant";
8335         else
8336           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8337               << Scope << "constant";
8338         NewVD->setInvalidDecl();
8339         return;
8340       }
8341     } else {
8342       if (T.getAddressSpace() == LangAS::opencl_global) {
8343         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8344             << 1 /*is any function*/ << "global";
8345         NewVD->setInvalidDecl();
8346         return;
8347       }
8348       if (T.getAddressSpace() == LangAS::opencl_constant ||
8349           T.getAddressSpace() == LangAS::opencl_local) {
8350         FunctionDecl *FD = getCurFunctionDecl();
8351         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8352         // in functions.
8353         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8354           if (T.getAddressSpace() == LangAS::opencl_constant)
8355             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8356                 << 0 /*non-kernel only*/ << "constant";
8357           else
8358             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8359                 << 0 /*non-kernel only*/ << "local";
8360           NewVD->setInvalidDecl();
8361           return;
8362         }
8363         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8364         // in the outermost scope of a kernel function.
8365         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8366           if (!getCurScope()->isFunctionScope()) {
8367             if (T.getAddressSpace() == LangAS::opencl_constant)
8368               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8369                   << "constant";
8370             else
8371               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8372                   << "local";
8373             NewVD->setInvalidDecl();
8374             return;
8375           }
8376         }
8377       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8378                  // If we are parsing a template we didn't deduce an addr
8379                  // space yet.
8380                  T.getAddressSpace() != LangAS::Default) {
8381         // Do not allow other address spaces on automatic variable.
8382         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8383         NewVD->setInvalidDecl();
8384         return;
8385       }
8386     }
8387   }
8388 
8389   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8390       && !NewVD->hasAttr<BlocksAttr>()) {
8391     if (getLangOpts().getGC() != LangOptions::NonGC)
8392       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8393     else {
8394       assert(!getLangOpts().ObjCAutoRefCount);
8395       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8396     }
8397   }
8398 
8399   bool isVM = T->isVariablyModifiedType();
8400   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8401       NewVD->hasAttr<BlocksAttr>())
8402     setFunctionHasBranchProtectedScope();
8403 
8404   if ((isVM && NewVD->hasLinkage()) ||
8405       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8406     bool SizeIsNegative;
8407     llvm::APSInt Oversized;
8408     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8409         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8410     QualType FixedT;
8411     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8412       FixedT = FixedTInfo->getType();
8413     else if (FixedTInfo) {
8414       // Type and type-as-written are canonically different. We need to fix up
8415       // both types separately.
8416       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8417                                                    Oversized);
8418     }
8419     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8420       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8421       // FIXME: This won't give the correct result for
8422       // int a[10][n];
8423       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8424 
8425       if (NewVD->isFileVarDecl())
8426         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8427         << SizeRange;
8428       else if (NewVD->isStaticLocal())
8429         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8430         << SizeRange;
8431       else
8432         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8433         << SizeRange;
8434       NewVD->setInvalidDecl();
8435       return;
8436     }
8437 
8438     if (!FixedTInfo) {
8439       if (NewVD->isFileVarDecl())
8440         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8441       else
8442         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8443       NewVD->setInvalidDecl();
8444       return;
8445     }
8446 
8447     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8448     NewVD->setType(FixedT);
8449     NewVD->setTypeSourceInfo(FixedTInfo);
8450   }
8451 
8452   if (T->isVoidType()) {
8453     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8454     //                    of objects and functions.
8455     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8456       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8457         << T;
8458       NewVD->setInvalidDecl();
8459       return;
8460     }
8461   }
8462 
8463   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8464     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8465     NewVD->setInvalidDecl();
8466     return;
8467   }
8468 
8469   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8470     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8471     NewVD->setInvalidDecl();
8472     return;
8473   }
8474 
8475   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8476     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8477     NewVD->setInvalidDecl();
8478     return;
8479   }
8480 
8481   if (NewVD->isConstexpr() && !T->isDependentType() &&
8482       RequireLiteralType(NewVD->getLocation(), T,
8483                          diag::err_constexpr_var_non_literal)) {
8484     NewVD->setInvalidDecl();
8485     return;
8486   }
8487 
8488   // PPC MMA non-pointer types are not allowed as non-local variable types.
8489   if (Context.getTargetInfo().getTriple().isPPC64() &&
8490       !NewVD->isLocalVarDecl() &&
8491       CheckPPCMMAType(T, NewVD->getLocation())) {
8492     NewVD->setInvalidDecl();
8493     return;
8494   }
8495 }
8496 
8497 /// Perform semantic checking on a newly-created variable
8498 /// declaration.
8499 ///
8500 /// This routine performs all of the type-checking required for a
8501 /// variable declaration once it has been built. It is used both to
8502 /// check variables after they have been parsed and their declarators
8503 /// have been translated into a declaration, and to check variables
8504 /// that have been instantiated from a template.
8505 ///
8506 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8507 ///
8508 /// Returns true if the variable declaration is a redeclaration.
8509 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8510   CheckVariableDeclarationType(NewVD);
8511 
8512   // If the decl is already known invalid, don't check it.
8513   if (NewVD->isInvalidDecl())
8514     return false;
8515 
8516   // If we did not find anything by this name, look for a non-visible
8517   // extern "C" declaration with the same name.
8518   if (Previous.empty() &&
8519       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8520     Previous.setShadowed();
8521 
8522   if (!Previous.empty()) {
8523     MergeVarDecl(NewVD, Previous);
8524     return true;
8525   }
8526   return false;
8527 }
8528 
8529 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8530 /// and if so, check that it's a valid override and remember it.
8531 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8532   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8533 
8534   // Look for methods in base classes that this method might override.
8535   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8536                      /*DetectVirtual=*/false);
8537   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8538     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8539     DeclarationName Name = MD->getDeclName();
8540 
8541     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8542       // We really want to find the base class destructor here.
8543       QualType T = Context.getTypeDeclType(BaseRecord);
8544       CanQualType CT = Context.getCanonicalType(T);
8545       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8546     }
8547 
8548     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8549       CXXMethodDecl *BaseMD =
8550           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8551       if (!BaseMD || !BaseMD->isVirtual() ||
8552           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8553                      /*ConsiderCudaAttrs=*/true,
8554                      // C++2a [class.virtual]p2 does not consider requires
8555                      // clauses when overriding.
8556                      /*ConsiderRequiresClauses=*/false))
8557         continue;
8558 
8559       if (Overridden.insert(BaseMD).second) {
8560         MD->addOverriddenMethod(BaseMD);
8561         CheckOverridingFunctionReturnType(MD, BaseMD);
8562         CheckOverridingFunctionAttributes(MD, BaseMD);
8563         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8564         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8565       }
8566 
8567       // A method can only override one function from each base class. We
8568       // don't track indirectly overridden methods from bases of bases.
8569       return true;
8570     }
8571 
8572     return false;
8573   };
8574 
8575   DC->lookupInBases(VisitBase, Paths);
8576   return !Overridden.empty();
8577 }
8578 
8579 namespace {
8580   // Struct for holding all of the extra arguments needed by
8581   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8582   struct ActOnFDArgs {
8583     Scope *S;
8584     Declarator &D;
8585     MultiTemplateParamsArg TemplateParamLists;
8586     bool AddToScope;
8587   };
8588 } // end anonymous namespace
8589 
8590 namespace {
8591 
8592 // Callback to only accept typo corrections that have a non-zero edit distance.
8593 // Also only accept corrections that have the same parent decl.
8594 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8595  public:
8596   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8597                             CXXRecordDecl *Parent)
8598       : Context(Context), OriginalFD(TypoFD),
8599         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8600 
8601   bool ValidateCandidate(const TypoCorrection &candidate) override {
8602     if (candidate.getEditDistance() == 0)
8603       return false;
8604 
8605     SmallVector<unsigned, 1> MismatchedParams;
8606     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8607                                           CDeclEnd = candidate.end();
8608          CDecl != CDeclEnd; ++CDecl) {
8609       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8610 
8611       if (FD && !FD->hasBody() &&
8612           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8613         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8614           CXXRecordDecl *Parent = MD->getParent();
8615           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8616             return true;
8617         } else if (!ExpectedParent) {
8618           return true;
8619         }
8620       }
8621     }
8622 
8623     return false;
8624   }
8625 
8626   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8627     return std::make_unique<DifferentNameValidatorCCC>(*this);
8628   }
8629 
8630  private:
8631   ASTContext &Context;
8632   FunctionDecl *OriginalFD;
8633   CXXRecordDecl *ExpectedParent;
8634 };
8635 
8636 } // end anonymous namespace
8637 
8638 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8639   TypoCorrectedFunctionDefinitions.insert(F);
8640 }
8641 
8642 /// Generate diagnostics for an invalid function redeclaration.
8643 ///
8644 /// This routine handles generating the diagnostic messages for an invalid
8645 /// function redeclaration, including finding possible similar declarations
8646 /// or performing typo correction if there are no previous declarations with
8647 /// the same name.
8648 ///
8649 /// Returns a NamedDecl iff typo correction was performed and substituting in
8650 /// the new declaration name does not cause new errors.
8651 static NamedDecl *DiagnoseInvalidRedeclaration(
8652     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8653     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8654   DeclarationName Name = NewFD->getDeclName();
8655   DeclContext *NewDC = NewFD->getDeclContext();
8656   SmallVector<unsigned, 1> MismatchedParams;
8657   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8658   TypoCorrection Correction;
8659   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8660   unsigned DiagMsg =
8661     IsLocalFriend ? diag::err_no_matching_local_friend :
8662     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8663     diag::err_member_decl_does_not_match;
8664   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8665                     IsLocalFriend ? Sema::LookupLocalFriendName
8666                                   : Sema::LookupOrdinaryName,
8667                     Sema::ForVisibleRedeclaration);
8668 
8669   NewFD->setInvalidDecl();
8670   if (IsLocalFriend)
8671     SemaRef.LookupName(Prev, S);
8672   else
8673     SemaRef.LookupQualifiedName(Prev, NewDC);
8674   assert(!Prev.isAmbiguous() &&
8675          "Cannot have an ambiguity in previous-declaration lookup");
8676   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8677   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8678                                 MD ? MD->getParent() : nullptr);
8679   if (!Prev.empty()) {
8680     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8681          Func != FuncEnd; ++Func) {
8682       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8683       if (FD &&
8684           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8685         // Add 1 to the index so that 0 can mean the mismatch didn't
8686         // involve a parameter
8687         unsigned ParamNum =
8688             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8689         NearMatches.push_back(std::make_pair(FD, ParamNum));
8690       }
8691     }
8692   // If the qualified name lookup yielded nothing, try typo correction
8693   } else if ((Correction = SemaRef.CorrectTypo(
8694                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8695                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8696                   IsLocalFriend ? nullptr : NewDC))) {
8697     // Set up everything for the call to ActOnFunctionDeclarator
8698     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8699                               ExtraArgs.D.getIdentifierLoc());
8700     Previous.clear();
8701     Previous.setLookupName(Correction.getCorrection());
8702     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8703                                     CDeclEnd = Correction.end();
8704          CDecl != CDeclEnd; ++CDecl) {
8705       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8706       if (FD && !FD->hasBody() &&
8707           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8708         Previous.addDecl(FD);
8709       }
8710     }
8711     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8712 
8713     NamedDecl *Result;
8714     // Retry building the function declaration with the new previous
8715     // declarations, and with errors suppressed.
8716     {
8717       // Trap errors.
8718       Sema::SFINAETrap Trap(SemaRef);
8719 
8720       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8721       // pieces need to verify the typo-corrected C++ declaration and hopefully
8722       // eliminate the need for the parameter pack ExtraArgs.
8723       Result = SemaRef.ActOnFunctionDeclarator(
8724           ExtraArgs.S, ExtraArgs.D,
8725           Correction.getCorrectionDecl()->getDeclContext(),
8726           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8727           ExtraArgs.AddToScope);
8728 
8729       if (Trap.hasErrorOccurred())
8730         Result = nullptr;
8731     }
8732 
8733     if (Result) {
8734       // Determine which correction we picked.
8735       Decl *Canonical = Result->getCanonicalDecl();
8736       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8737            I != E; ++I)
8738         if ((*I)->getCanonicalDecl() == Canonical)
8739           Correction.setCorrectionDecl(*I);
8740 
8741       // Let Sema know about the correction.
8742       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8743       SemaRef.diagnoseTypo(
8744           Correction,
8745           SemaRef.PDiag(IsLocalFriend
8746                           ? diag::err_no_matching_local_friend_suggest
8747                           : diag::err_member_decl_does_not_match_suggest)
8748             << Name << NewDC << IsDefinition);
8749       return Result;
8750     }
8751 
8752     // Pretend the typo correction never occurred
8753     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8754                               ExtraArgs.D.getIdentifierLoc());
8755     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8756     Previous.clear();
8757     Previous.setLookupName(Name);
8758   }
8759 
8760   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8761       << Name << NewDC << IsDefinition << NewFD->getLocation();
8762 
8763   bool NewFDisConst = false;
8764   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8765     NewFDisConst = NewMD->isConst();
8766 
8767   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8768        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8769        NearMatch != NearMatchEnd; ++NearMatch) {
8770     FunctionDecl *FD = NearMatch->first;
8771     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8772     bool FDisConst = MD && MD->isConst();
8773     bool IsMember = MD || !IsLocalFriend;
8774 
8775     // FIXME: These notes are poorly worded for the local friend case.
8776     if (unsigned Idx = NearMatch->second) {
8777       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8778       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8779       if (Loc.isInvalid()) Loc = FD->getLocation();
8780       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8781                                  : diag::note_local_decl_close_param_match)
8782         << Idx << FDParam->getType()
8783         << NewFD->getParamDecl(Idx - 1)->getType();
8784     } else if (FDisConst != NewFDisConst) {
8785       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8786           << NewFDisConst << FD->getSourceRange().getEnd()
8787           << (NewFDisConst
8788                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8789                                                  .getConstQualifierLoc())
8790                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8791                                                    .getRParenLoc()
8792                                                    .getLocWithOffset(1),
8793                                                " const"));
8794     } else
8795       SemaRef.Diag(FD->getLocation(),
8796                    IsMember ? diag::note_member_def_close_match
8797                             : diag::note_local_decl_close_match);
8798   }
8799   return nullptr;
8800 }
8801 
8802 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8803   switch (D.getDeclSpec().getStorageClassSpec()) {
8804   default: llvm_unreachable("Unknown storage class!");
8805   case DeclSpec::SCS_auto:
8806   case DeclSpec::SCS_register:
8807   case DeclSpec::SCS_mutable:
8808     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8809                  diag::err_typecheck_sclass_func);
8810     D.getMutableDeclSpec().ClearStorageClassSpecs();
8811     D.setInvalidType();
8812     break;
8813   case DeclSpec::SCS_unspecified: break;
8814   case DeclSpec::SCS_extern:
8815     if (D.getDeclSpec().isExternInLinkageSpec())
8816       return SC_None;
8817     return SC_Extern;
8818   case DeclSpec::SCS_static: {
8819     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8820       // C99 6.7.1p5:
8821       //   The declaration of an identifier for a function that has
8822       //   block scope shall have no explicit storage-class specifier
8823       //   other than extern
8824       // See also (C++ [dcl.stc]p4).
8825       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8826                    diag::err_static_block_func);
8827       break;
8828     } else
8829       return SC_Static;
8830   }
8831   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8832   }
8833 
8834   // No explicit storage class has already been returned
8835   return SC_None;
8836 }
8837 
8838 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8839                                            DeclContext *DC, QualType &R,
8840                                            TypeSourceInfo *TInfo,
8841                                            StorageClass SC,
8842                                            bool &IsVirtualOkay) {
8843   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8844   DeclarationName Name = NameInfo.getName();
8845 
8846   FunctionDecl *NewFD = nullptr;
8847   bool isInline = D.getDeclSpec().isInlineSpecified();
8848 
8849   if (!SemaRef.getLangOpts().CPlusPlus) {
8850     // Determine whether the function was written with a prototype. This is
8851     // true when:
8852     //   - there is a prototype in the declarator, or
8853     //   - the type R of the function is some kind of typedef or other non-
8854     //     attributed reference to a type name (which eventually refers to a
8855     //     function type). Note, we can't always look at the adjusted type to
8856     //     check this case because attributes may cause a non-function
8857     //     declarator to still have a function type. e.g.,
8858     //       typedef void func(int a);
8859     //       __attribute__((noreturn)) func other_func; // This has a prototype
8860     bool HasPrototype =
8861         (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8862         (D.getDeclSpec().isTypeRep() &&
8863          D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
8864         (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8865     assert(
8866         (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
8867         "Strict prototypes are required");
8868 
8869     NewFD = FunctionDecl::Create(
8870         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8871         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8872         ConstexprSpecKind::Unspecified,
8873         /*TrailingRequiresClause=*/nullptr);
8874     if (D.isInvalidType())
8875       NewFD->setInvalidDecl();
8876 
8877     return NewFD;
8878   }
8879 
8880   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8881 
8882   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8883   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8884     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8885                  diag::err_constexpr_wrong_decl_kind)
8886         << static_cast<int>(ConstexprKind);
8887     ConstexprKind = ConstexprSpecKind::Unspecified;
8888     D.getMutableDeclSpec().ClearConstexprSpec();
8889   }
8890   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8891 
8892   // Check that the return type is not an abstract class type.
8893   // For record types, this is done by the AbstractClassUsageDiagnoser once
8894   // the class has been completely parsed.
8895   if (!DC->isRecord() &&
8896       SemaRef.RequireNonAbstractType(
8897           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8898           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8899     D.setInvalidType();
8900 
8901   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8902     // This is a C++ constructor declaration.
8903     assert(DC->isRecord() &&
8904            "Constructors can only be declared in a member context");
8905 
8906     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8907     return CXXConstructorDecl::Create(
8908         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8909         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8910         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8911         InheritedConstructor(), TrailingRequiresClause);
8912 
8913   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8914     // This is a C++ destructor declaration.
8915     if (DC->isRecord()) {
8916       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8917       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8918       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8919           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8920           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8921           /*isImplicitlyDeclared=*/false, ConstexprKind,
8922           TrailingRequiresClause);
8923       // User defined destructors start as not selected if the class definition is still
8924       // not done.
8925       if (Record->isBeingDefined())
8926         NewDD->setIneligibleOrNotSelected(true);
8927 
8928       // If the destructor needs an implicit exception specification, set it
8929       // now. FIXME: It'd be nice to be able to create the right type to start
8930       // with, but the type needs to reference the destructor declaration.
8931       if (SemaRef.getLangOpts().CPlusPlus11)
8932         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8933 
8934       IsVirtualOkay = true;
8935       return NewDD;
8936 
8937     } else {
8938       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8939       D.setInvalidType();
8940 
8941       // Create a FunctionDecl to satisfy the function definition parsing
8942       // code path.
8943       return FunctionDecl::Create(
8944           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8945           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8946           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8947     }
8948 
8949   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8950     if (!DC->isRecord()) {
8951       SemaRef.Diag(D.getIdentifierLoc(),
8952            diag::err_conv_function_not_member);
8953       return nullptr;
8954     }
8955 
8956     SemaRef.CheckConversionDeclarator(D, R, SC);
8957     if (D.isInvalidType())
8958       return nullptr;
8959 
8960     IsVirtualOkay = true;
8961     return CXXConversionDecl::Create(
8962         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8963         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8964         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8965         TrailingRequiresClause);
8966 
8967   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8968     if (TrailingRequiresClause)
8969       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8970                    diag::err_trailing_requires_clause_on_deduction_guide)
8971           << TrailingRequiresClause->getSourceRange();
8972     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8973 
8974     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8975                                          ExplicitSpecifier, NameInfo, R, TInfo,
8976                                          D.getEndLoc());
8977   } else if (DC->isRecord()) {
8978     // If the name of the function is the same as the name of the record,
8979     // then this must be an invalid constructor that has a return type.
8980     // (The parser checks for a return type and makes the declarator a
8981     // constructor if it has no return type).
8982     if (Name.getAsIdentifierInfo() &&
8983         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8984       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8985         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8986         << SourceRange(D.getIdentifierLoc());
8987       return nullptr;
8988     }
8989 
8990     // This is a C++ method declaration.
8991     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8992         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8993         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8994         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8995     IsVirtualOkay = !Ret->isStatic();
8996     return Ret;
8997   } else {
8998     bool isFriend =
8999         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9000     if (!isFriend && SemaRef.CurContext->isRecord())
9001       return nullptr;
9002 
9003     // Determine whether the function was written with a
9004     // prototype. This true when:
9005     //   - we're in C++ (where every function has a prototype),
9006     return FunctionDecl::Create(
9007         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9008         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9009         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9010   }
9011 }
9012 
9013 enum OpenCLParamType {
9014   ValidKernelParam,
9015   PtrPtrKernelParam,
9016   PtrKernelParam,
9017   InvalidAddrSpacePtrKernelParam,
9018   InvalidKernelParam,
9019   RecordKernelParam
9020 };
9021 
9022 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9023   // Size dependent types are just typedefs to normal integer types
9024   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9025   // integers other than by their names.
9026   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9027 
9028   // Remove typedefs one by one until we reach a typedef
9029   // for a size dependent type.
9030   QualType DesugaredTy = Ty;
9031   do {
9032     ArrayRef<StringRef> Names(SizeTypeNames);
9033     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9034     if (Names.end() != Match)
9035       return true;
9036 
9037     Ty = DesugaredTy;
9038     DesugaredTy = Ty.getSingleStepDesugaredType(C);
9039   } while (DesugaredTy != Ty);
9040 
9041   return false;
9042 }
9043 
9044 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9045   if (PT->isDependentType())
9046     return InvalidKernelParam;
9047 
9048   if (PT->isPointerType() || PT->isReferenceType()) {
9049     QualType PointeeType = PT->getPointeeType();
9050     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9051         PointeeType.getAddressSpace() == LangAS::opencl_private ||
9052         PointeeType.getAddressSpace() == LangAS::Default)
9053       return InvalidAddrSpacePtrKernelParam;
9054 
9055     if (PointeeType->isPointerType()) {
9056       // This is a pointer to pointer parameter.
9057       // Recursively check inner type.
9058       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9059       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9060           ParamKind == InvalidKernelParam)
9061         return ParamKind;
9062 
9063       return PtrPtrKernelParam;
9064     }
9065 
9066     // C++ for OpenCL v1.0 s2.4:
9067     // Moreover the types used in parameters of the kernel functions must be:
9068     // Standard layout types for pointer parameters. The same applies to
9069     // reference if an implementation supports them in kernel parameters.
9070     if (S.getLangOpts().OpenCLCPlusPlus &&
9071         !S.getOpenCLOptions().isAvailableOption(
9072             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9073         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9074         !PointeeType->isStandardLayoutType())
9075       return InvalidKernelParam;
9076 
9077     return PtrKernelParam;
9078   }
9079 
9080   // OpenCL v1.2 s6.9.k:
9081   // Arguments to kernel functions in a program cannot be declared with the
9082   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9083   // uintptr_t or a struct and/or union that contain fields declared to be one
9084   // of these built-in scalar types.
9085   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9086     return InvalidKernelParam;
9087 
9088   if (PT->isImageType())
9089     return PtrKernelParam;
9090 
9091   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9092     return InvalidKernelParam;
9093 
9094   // OpenCL extension spec v1.2 s9.5:
9095   // This extension adds support for half scalar and vector types as built-in
9096   // types that can be used for arithmetic operations, conversions etc.
9097   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9098       PT->isHalfType())
9099     return InvalidKernelParam;
9100 
9101   // Look into an array argument to check if it has a forbidden type.
9102   if (PT->isArrayType()) {
9103     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9104     // Call ourself to check an underlying type of an array. Since the
9105     // getPointeeOrArrayElementType returns an innermost type which is not an
9106     // array, this recursive call only happens once.
9107     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9108   }
9109 
9110   // C++ for OpenCL v1.0 s2.4:
9111   // Moreover the types used in parameters of the kernel functions must be:
9112   // Trivial and standard-layout types C++17 [basic.types] (plain old data
9113   // types) for parameters passed by value;
9114   if (S.getLangOpts().OpenCLCPlusPlus &&
9115       !S.getOpenCLOptions().isAvailableOption(
9116           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9117       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9118     return InvalidKernelParam;
9119 
9120   if (PT->isRecordType())
9121     return RecordKernelParam;
9122 
9123   return ValidKernelParam;
9124 }
9125 
9126 static void checkIsValidOpenCLKernelParameter(
9127   Sema &S,
9128   Declarator &D,
9129   ParmVarDecl *Param,
9130   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9131   QualType PT = Param->getType();
9132 
9133   // Cache the valid types we encounter to avoid rechecking structs that are
9134   // used again
9135   if (ValidTypes.count(PT.getTypePtr()))
9136     return;
9137 
9138   switch (getOpenCLKernelParameterType(S, PT)) {
9139   case PtrPtrKernelParam:
9140     // OpenCL v3.0 s6.11.a:
9141     // A kernel function argument cannot be declared as a pointer to a pointer
9142     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9143     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9144       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9145       D.setInvalidType();
9146       return;
9147     }
9148 
9149     ValidTypes.insert(PT.getTypePtr());
9150     return;
9151 
9152   case InvalidAddrSpacePtrKernelParam:
9153     // OpenCL v1.0 s6.5:
9154     // __kernel function arguments declared to be a pointer of a type can point
9155     // to one of the following address spaces only : __global, __local or
9156     // __constant.
9157     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9158     D.setInvalidType();
9159     return;
9160 
9161     // OpenCL v1.2 s6.9.k:
9162     // Arguments to kernel functions in a program cannot be declared with the
9163     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9164     // uintptr_t or a struct and/or union that contain fields declared to be
9165     // one of these built-in scalar types.
9166 
9167   case InvalidKernelParam:
9168     // OpenCL v1.2 s6.8 n:
9169     // A kernel function argument cannot be declared
9170     // of event_t type.
9171     // Do not diagnose half type since it is diagnosed as invalid argument
9172     // type for any function elsewhere.
9173     if (!PT->isHalfType()) {
9174       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9175 
9176       // Explain what typedefs are involved.
9177       const TypedefType *Typedef = nullptr;
9178       while ((Typedef = PT->getAs<TypedefType>())) {
9179         SourceLocation Loc = Typedef->getDecl()->getLocation();
9180         // SourceLocation may be invalid for a built-in type.
9181         if (Loc.isValid())
9182           S.Diag(Loc, diag::note_entity_declared_at) << PT;
9183         PT = Typedef->desugar();
9184       }
9185     }
9186 
9187     D.setInvalidType();
9188     return;
9189 
9190   case PtrKernelParam:
9191   case ValidKernelParam:
9192     ValidTypes.insert(PT.getTypePtr());
9193     return;
9194 
9195   case RecordKernelParam:
9196     break;
9197   }
9198 
9199   // Track nested structs we will inspect
9200   SmallVector<const Decl *, 4> VisitStack;
9201 
9202   // Track where we are in the nested structs. Items will migrate from
9203   // VisitStack to HistoryStack as we do the DFS for bad field.
9204   SmallVector<const FieldDecl *, 4> HistoryStack;
9205   HistoryStack.push_back(nullptr);
9206 
9207   // At this point we already handled everything except of a RecordType or
9208   // an ArrayType of a RecordType.
9209   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9210   const RecordType *RecTy =
9211       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9212   const RecordDecl *OrigRecDecl = RecTy->getDecl();
9213 
9214   VisitStack.push_back(RecTy->getDecl());
9215   assert(VisitStack.back() && "First decl null?");
9216 
9217   do {
9218     const Decl *Next = VisitStack.pop_back_val();
9219     if (!Next) {
9220       assert(!HistoryStack.empty());
9221       // Found a marker, we have gone up a level
9222       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9223         ValidTypes.insert(Hist->getType().getTypePtr());
9224 
9225       continue;
9226     }
9227 
9228     // Adds everything except the original parameter declaration (which is not a
9229     // field itself) to the history stack.
9230     const RecordDecl *RD;
9231     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9232       HistoryStack.push_back(Field);
9233 
9234       QualType FieldTy = Field->getType();
9235       // Other field types (known to be valid or invalid) are handled while we
9236       // walk around RecordDecl::fields().
9237       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9238              "Unexpected type.");
9239       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9240 
9241       RD = FieldRecTy->castAs<RecordType>()->getDecl();
9242     } else {
9243       RD = cast<RecordDecl>(Next);
9244     }
9245 
9246     // Add a null marker so we know when we've gone back up a level
9247     VisitStack.push_back(nullptr);
9248 
9249     for (const auto *FD : RD->fields()) {
9250       QualType QT = FD->getType();
9251 
9252       if (ValidTypes.count(QT.getTypePtr()))
9253         continue;
9254 
9255       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9256       if (ParamType == ValidKernelParam)
9257         continue;
9258 
9259       if (ParamType == RecordKernelParam) {
9260         VisitStack.push_back(FD);
9261         continue;
9262       }
9263 
9264       // OpenCL v1.2 s6.9.p:
9265       // Arguments to kernel functions that are declared to be a struct or union
9266       // do not allow OpenCL objects to be passed as elements of the struct or
9267       // union.
9268       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9269           ParamType == InvalidAddrSpacePtrKernelParam) {
9270         S.Diag(Param->getLocation(),
9271                diag::err_record_with_pointers_kernel_param)
9272           << PT->isUnionType()
9273           << PT;
9274       } else {
9275         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9276       }
9277 
9278       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9279           << OrigRecDecl->getDeclName();
9280 
9281       // We have an error, now let's go back up through history and show where
9282       // the offending field came from
9283       for (ArrayRef<const FieldDecl *>::const_iterator
9284                I = HistoryStack.begin() + 1,
9285                E = HistoryStack.end();
9286            I != E; ++I) {
9287         const FieldDecl *OuterField = *I;
9288         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9289           << OuterField->getType();
9290       }
9291 
9292       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9293         << QT->isPointerType()
9294         << QT;
9295       D.setInvalidType();
9296       return;
9297     }
9298   } while (!VisitStack.empty());
9299 }
9300 
9301 /// Find the DeclContext in which a tag is implicitly declared if we see an
9302 /// elaborated type specifier in the specified context, and lookup finds
9303 /// nothing.
9304 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9305   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9306     DC = DC->getParent();
9307   return DC;
9308 }
9309 
9310 /// Find the Scope in which a tag is implicitly declared if we see an
9311 /// elaborated type specifier in the specified context, and lookup finds
9312 /// nothing.
9313 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9314   while (S->isClassScope() ||
9315          (LangOpts.CPlusPlus &&
9316           S->isFunctionPrototypeScope()) ||
9317          ((S->getFlags() & Scope::DeclScope) == 0) ||
9318          (S->getEntity() && S->getEntity()->isTransparentContext()))
9319     S = S->getParent();
9320   return S;
9321 }
9322 
9323 /// Determine whether a declaration matches a known function in namespace std.
9324 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9325                          unsigned BuiltinID) {
9326   switch (BuiltinID) {
9327   case Builtin::BI__GetExceptionInfo:
9328     // No type checking whatsoever.
9329     return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9330 
9331   case Builtin::BIaddressof:
9332   case Builtin::BI__addressof:
9333   case Builtin::BIforward:
9334   case Builtin::BImove:
9335   case Builtin::BImove_if_noexcept:
9336   case Builtin::BIas_const: {
9337     // Ensure that we don't treat the algorithm
9338     //   OutputIt std::move(InputIt, InputIt, OutputIt)
9339     // as the builtin std::move.
9340     const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9341     return FPT->getNumParams() == 1 && !FPT->isVariadic();
9342   }
9343 
9344   default:
9345     return false;
9346   }
9347 }
9348 
9349 NamedDecl*
9350 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9351                               TypeSourceInfo *TInfo, LookupResult &Previous,
9352                               MultiTemplateParamsArg TemplateParamListsRef,
9353                               bool &AddToScope) {
9354   QualType R = TInfo->getType();
9355 
9356   assert(R->isFunctionType());
9357   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9358     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9359 
9360   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9361   llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9362   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9363     if (!TemplateParamLists.empty() &&
9364         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9365       TemplateParamLists.back() = Invented;
9366     else
9367       TemplateParamLists.push_back(Invented);
9368   }
9369 
9370   // TODO: consider using NameInfo for diagnostic.
9371   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9372   DeclarationName Name = NameInfo.getName();
9373   StorageClass SC = getFunctionStorageClass(*this, D);
9374 
9375   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9376     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9377          diag::err_invalid_thread)
9378       << DeclSpec::getSpecifierName(TSCS);
9379 
9380   if (D.isFirstDeclarationOfMember())
9381     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9382                            D.getIdentifierLoc());
9383 
9384   bool isFriend = false;
9385   FunctionTemplateDecl *FunctionTemplate = nullptr;
9386   bool isMemberSpecialization = false;
9387   bool isFunctionTemplateSpecialization = false;
9388 
9389   bool isDependentClassScopeExplicitSpecialization = false;
9390   bool HasExplicitTemplateArgs = false;
9391   TemplateArgumentListInfo TemplateArgs;
9392 
9393   bool isVirtualOkay = false;
9394 
9395   DeclContext *OriginalDC = DC;
9396   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9397 
9398   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9399                                               isVirtualOkay);
9400   if (!NewFD) return nullptr;
9401 
9402   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9403     NewFD->setTopLevelDeclInObjCContainer();
9404 
9405   // Set the lexical context. If this is a function-scope declaration, or has a
9406   // C++ scope specifier, or is the object of a friend declaration, the lexical
9407   // context will be different from the semantic context.
9408   NewFD->setLexicalDeclContext(CurContext);
9409 
9410   if (IsLocalExternDecl)
9411     NewFD->setLocalExternDecl();
9412 
9413   if (getLangOpts().CPlusPlus) {
9414     bool isInline = D.getDeclSpec().isInlineSpecified();
9415     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9416     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9417     isFriend = D.getDeclSpec().isFriendSpecified();
9418     if (isFriend && !isInline && D.isFunctionDefinition()) {
9419       // C++ [class.friend]p5
9420       //   A function can be defined in a friend declaration of a
9421       //   class . . . . Such a function is implicitly inline.
9422       NewFD->setImplicitlyInline();
9423     }
9424 
9425     // If this is a method defined in an __interface, and is not a constructor
9426     // or an overloaded operator, then set the pure flag (isVirtual will already
9427     // return true).
9428     if (const CXXRecordDecl *Parent =
9429           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9430       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9431         NewFD->setPure(true);
9432 
9433       // C++ [class.union]p2
9434       //   A union can have member functions, but not virtual functions.
9435       if (isVirtual && Parent->isUnion()) {
9436         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9437         NewFD->setInvalidDecl();
9438       }
9439       if ((Parent->isClass() || Parent->isStruct()) &&
9440           Parent->hasAttr<SYCLSpecialClassAttr>() &&
9441           NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9442           NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9443         if (auto *Def = Parent->getDefinition())
9444           Def->setInitMethod(true);
9445       }
9446     }
9447 
9448     SetNestedNameSpecifier(*this, NewFD, D);
9449     isMemberSpecialization = false;
9450     isFunctionTemplateSpecialization = false;
9451     if (D.isInvalidType())
9452       NewFD->setInvalidDecl();
9453 
9454     // Match up the template parameter lists with the scope specifier, then
9455     // determine whether we have a template or a template specialization.
9456     bool Invalid = false;
9457     TemplateParameterList *TemplateParams =
9458         MatchTemplateParametersToScopeSpecifier(
9459             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9460             D.getCXXScopeSpec(),
9461             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9462                 ? D.getName().TemplateId
9463                 : nullptr,
9464             TemplateParamLists, isFriend, isMemberSpecialization,
9465             Invalid);
9466     if (TemplateParams) {
9467       // Check that we can declare a template here.
9468       if (CheckTemplateDeclScope(S, TemplateParams))
9469         NewFD->setInvalidDecl();
9470 
9471       if (TemplateParams->size() > 0) {
9472         // This is a function template
9473 
9474         // A destructor cannot be a template.
9475         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9476           Diag(NewFD->getLocation(), diag::err_destructor_template);
9477           NewFD->setInvalidDecl();
9478         }
9479 
9480         // If we're adding a template to a dependent context, we may need to
9481         // rebuilding some of the types used within the template parameter list,
9482         // now that we know what the current instantiation is.
9483         if (DC->isDependentContext()) {
9484           ContextRAII SavedContext(*this, DC);
9485           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9486             Invalid = true;
9487         }
9488 
9489         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9490                                                         NewFD->getLocation(),
9491                                                         Name, TemplateParams,
9492                                                         NewFD);
9493         FunctionTemplate->setLexicalDeclContext(CurContext);
9494         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9495 
9496         // For source fidelity, store the other template param lists.
9497         if (TemplateParamLists.size() > 1) {
9498           NewFD->setTemplateParameterListsInfo(Context,
9499               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9500                   .drop_back(1));
9501         }
9502       } else {
9503         // This is a function template specialization.
9504         isFunctionTemplateSpecialization = true;
9505         // For source fidelity, store all the template param lists.
9506         if (TemplateParamLists.size() > 0)
9507           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9508 
9509         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9510         if (isFriend) {
9511           // We want to remove the "template<>", found here.
9512           SourceRange RemoveRange = TemplateParams->getSourceRange();
9513 
9514           // If we remove the template<> and the name is not a
9515           // template-id, we're actually silently creating a problem:
9516           // the friend declaration will refer to an untemplated decl,
9517           // and clearly the user wants a template specialization.  So
9518           // we need to insert '<>' after the name.
9519           SourceLocation InsertLoc;
9520           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9521             InsertLoc = D.getName().getSourceRange().getEnd();
9522             InsertLoc = getLocForEndOfToken(InsertLoc);
9523           }
9524 
9525           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9526             << Name << RemoveRange
9527             << FixItHint::CreateRemoval(RemoveRange)
9528             << FixItHint::CreateInsertion(InsertLoc, "<>");
9529           Invalid = true;
9530         }
9531       }
9532     } else {
9533       // Check that we can declare a template here.
9534       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9535           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9536         NewFD->setInvalidDecl();
9537 
9538       // All template param lists were matched against the scope specifier:
9539       // this is NOT (an explicit specialization of) a template.
9540       if (TemplateParamLists.size() > 0)
9541         // For source fidelity, store all the template param lists.
9542         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9543     }
9544 
9545     if (Invalid) {
9546       NewFD->setInvalidDecl();
9547       if (FunctionTemplate)
9548         FunctionTemplate->setInvalidDecl();
9549     }
9550 
9551     // C++ [dcl.fct.spec]p5:
9552     //   The virtual specifier shall only be used in declarations of
9553     //   nonstatic class member functions that appear within a
9554     //   member-specification of a class declaration; see 10.3.
9555     //
9556     if (isVirtual && !NewFD->isInvalidDecl()) {
9557       if (!isVirtualOkay) {
9558         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9559              diag::err_virtual_non_function);
9560       } else if (!CurContext->isRecord()) {
9561         // 'virtual' was specified outside of the class.
9562         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9563              diag::err_virtual_out_of_class)
9564           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9565       } else if (NewFD->getDescribedFunctionTemplate()) {
9566         // C++ [temp.mem]p3:
9567         //  A member function template shall not be virtual.
9568         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9569              diag::err_virtual_member_function_template)
9570           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9571       } else {
9572         // Okay: Add virtual to the method.
9573         NewFD->setVirtualAsWritten(true);
9574       }
9575 
9576       if (getLangOpts().CPlusPlus14 &&
9577           NewFD->getReturnType()->isUndeducedType())
9578         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9579     }
9580 
9581     if (getLangOpts().CPlusPlus14 &&
9582         (NewFD->isDependentContext() ||
9583          (isFriend && CurContext->isDependentContext())) &&
9584         NewFD->getReturnType()->isUndeducedType()) {
9585       // If the function template is referenced directly (for instance, as a
9586       // member of the current instantiation), pretend it has a dependent type.
9587       // This is not really justified by the standard, but is the only sane
9588       // thing to do.
9589       // FIXME: For a friend function, we have not marked the function as being
9590       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9591       const FunctionProtoType *FPT =
9592           NewFD->getType()->castAs<FunctionProtoType>();
9593       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9594       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9595                                              FPT->getExtProtoInfo()));
9596     }
9597 
9598     // C++ [dcl.fct.spec]p3:
9599     //  The inline specifier shall not appear on a block scope function
9600     //  declaration.
9601     if (isInline && !NewFD->isInvalidDecl()) {
9602       if (CurContext->isFunctionOrMethod()) {
9603         // 'inline' is not allowed on block scope function declaration.
9604         Diag(D.getDeclSpec().getInlineSpecLoc(),
9605              diag::err_inline_declaration_block_scope) << Name
9606           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9607       }
9608     }
9609 
9610     // C++ [dcl.fct.spec]p6:
9611     //  The explicit specifier shall be used only in the declaration of a
9612     //  constructor or conversion function within its class definition;
9613     //  see 12.3.1 and 12.3.2.
9614     if (hasExplicit && !NewFD->isInvalidDecl() &&
9615         !isa<CXXDeductionGuideDecl>(NewFD)) {
9616       if (!CurContext->isRecord()) {
9617         // 'explicit' was specified outside of the class.
9618         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9619              diag::err_explicit_out_of_class)
9620             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9621       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9622                  !isa<CXXConversionDecl>(NewFD)) {
9623         // 'explicit' was specified on a function that wasn't a constructor
9624         // or conversion function.
9625         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9626              diag::err_explicit_non_ctor_or_conv_function)
9627             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9628       }
9629     }
9630 
9631     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9632     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9633       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9634       // are implicitly inline.
9635       NewFD->setImplicitlyInline();
9636 
9637       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9638       // be either constructors or to return a literal type. Therefore,
9639       // destructors cannot be declared constexpr.
9640       if (isa<CXXDestructorDecl>(NewFD) &&
9641           (!getLangOpts().CPlusPlus20 ||
9642            ConstexprKind == ConstexprSpecKind::Consteval)) {
9643         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9644             << static_cast<int>(ConstexprKind);
9645         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9646                                     ? ConstexprSpecKind::Unspecified
9647                                     : ConstexprSpecKind::Constexpr);
9648       }
9649       // C++20 [dcl.constexpr]p2: An allocation function, or a
9650       // deallocation function shall not be declared with the consteval
9651       // specifier.
9652       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9653           (NewFD->getOverloadedOperator() == OO_New ||
9654            NewFD->getOverloadedOperator() == OO_Array_New ||
9655            NewFD->getOverloadedOperator() == OO_Delete ||
9656            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9657         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9658              diag::err_invalid_consteval_decl_kind)
9659             << NewFD;
9660         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9661       }
9662     }
9663 
9664     // If __module_private__ was specified, mark the function accordingly.
9665     if (D.getDeclSpec().isModulePrivateSpecified()) {
9666       if (isFunctionTemplateSpecialization) {
9667         SourceLocation ModulePrivateLoc
9668           = D.getDeclSpec().getModulePrivateSpecLoc();
9669         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9670           << 0
9671           << FixItHint::CreateRemoval(ModulePrivateLoc);
9672       } else {
9673         NewFD->setModulePrivate();
9674         if (FunctionTemplate)
9675           FunctionTemplate->setModulePrivate();
9676       }
9677     }
9678 
9679     if (isFriend) {
9680       if (FunctionTemplate) {
9681         FunctionTemplate->setObjectOfFriendDecl();
9682         FunctionTemplate->setAccess(AS_public);
9683       }
9684       NewFD->setObjectOfFriendDecl();
9685       NewFD->setAccess(AS_public);
9686     }
9687 
9688     // If a function is defined as defaulted or deleted, mark it as such now.
9689     // We'll do the relevant checks on defaulted / deleted functions later.
9690     switch (D.getFunctionDefinitionKind()) {
9691     case FunctionDefinitionKind::Declaration:
9692     case FunctionDefinitionKind::Definition:
9693       break;
9694 
9695     case FunctionDefinitionKind::Defaulted:
9696       NewFD->setDefaulted();
9697       break;
9698 
9699     case FunctionDefinitionKind::Deleted:
9700       NewFD->setDeletedAsWritten();
9701       break;
9702     }
9703 
9704     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9705         D.isFunctionDefinition()) {
9706       // C++ [class.mfct]p2:
9707       //   A member function may be defined (8.4) in its class definition, in
9708       //   which case it is an inline member function (7.1.2)
9709       NewFD->setImplicitlyInline();
9710     }
9711 
9712     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9713         !CurContext->isRecord()) {
9714       // C++ [class.static]p1:
9715       //   A data or function member of a class may be declared static
9716       //   in a class definition, in which case it is a static member of
9717       //   the class.
9718 
9719       // Complain about the 'static' specifier if it's on an out-of-line
9720       // member function definition.
9721 
9722       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9723       // member function template declaration and class member template
9724       // declaration (MSVC versions before 2015), warn about this.
9725       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9726            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9727              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9728            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9729            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9730         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9731     }
9732 
9733     // C++11 [except.spec]p15:
9734     //   A deallocation function with no exception-specification is treated
9735     //   as if it were specified with noexcept(true).
9736     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9737     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9738          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9739         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9740       NewFD->setType(Context.getFunctionType(
9741           FPT->getReturnType(), FPT->getParamTypes(),
9742           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9743   }
9744 
9745   // Filter out previous declarations that don't match the scope.
9746   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9747                        D.getCXXScopeSpec().isNotEmpty() ||
9748                        isMemberSpecialization ||
9749                        isFunctionTemplateSpecialization);
9750 
9751   // Handle GNU asm-label extension (encoded as an attribute).
9752   if (Expr *E = (Expr*) D.getAsmLabel()) {
9753     // The parser guarantees this is a string.
9754     StringLiteral *SE = cast<StringLiteral>(E);
9755     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9756                                         /*IsLiteralLabel=*/true,
9757                                         SE->getStrTokenLoc(0)));
9758   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9759     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9760       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9761     if (I != ExtnameUndeclaredIdentifiers.end()) {
9762       if (isDeclExternC(NewFD)) {
9763         NewFD->addAttr(I->second);
9764         ExtnameUndeclaredIdentifiers.erase(I);
9765       } else
9766         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9767             << /*Variable*/0 << NewFD;
9768     }
9769   }
9770 
9771   // Copy the parameter declarations from the declarator D to the function
9772   // declaration NewFD, if they are available.  First scavenge them into Params.
9773   SmallVector<ParmVarDecl*, 16> Params;
9774   unsigned FTIIdx;
9775   if (D.isFunctionDeclarator(FTIIdx)) {
9776     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9777 
9778     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9779     // function that takes no arguments, not a function that takes a
9780     // single void argument.
9781     // We let through "const void" here because Sema::GetTypeForDeclarator
9782     // already checks for that case.
9783     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9784       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9785         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9786         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9787         Param->setDeclContext(NewFD);
9788         Params.push_back(Param);
9789 
9790         if (Param->isInvalidDecl())
9791           NewFD->setInvalidDecl();
9792       }
9793     }
9794 
9795     if (!getLangOpts().CPlusPlus) {
9796       // In C, find all the tag declarations from the prototype and move them
9797       // into the function DeclContext. Remove them from the surrounding tag
9798       // injection context of the function, which is typically but not always
9799       // the TU.
9800       DeclContext *PrototypeTagContext =
9801           getTagInjectionContext(NewFD->getLexicalDeclContext());
9802       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9803         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9804 
9805         // We don't want to reparent enumerators. Look at their parent enum
9806         // instead.
9807         if (!TD) {
9808           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9809             TD = cast<EnumDecl>(ECD->getDeclContext());
9810         }
9811         if (!TD)
9812           continue;
9813         DeclContext *TagDC = TD->getLexicalDeclContext();
9814         if (!TagDC->containsDecl(TD))
9815           continue;
9816         TagDC->removeDecl(TD);
9817         TD->setDeclContext(NewFD);
9818         NewFD->addDecl(TD);
9819 
9820         // Preserve the lexical DeclContext if it is not the surrounding tag
9821         // injection context of the FD. In this example, the semantic context of
9822         // E will be f and the lexical context will be S, while both the
9823         // semantic and lexical contexts of S will be f:
9824         //   void f(struct S { enum E { a } f; } s);
9825         if (TagDC != PrototypeTagContext)
9826           TD->setLexicalDeclContext(TagDC);
9827       }
9828     }
9829   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9830     // When we're declaring a function with a typedef, typeof, etc as in the
9831     // following example, we'll need to synthesize (unnamed)
9832     // parameters for use in the declaration.
9833     //
9834     // @code
9835     // typedef void fn(int);
9836     // fn f;
9837     // @endcode
9838 
9839     // Synthesize a parameter for each argument type.
9840     for (const auto &AI : FT->param_types()) {
9841       ParmVarDecl *Param =
9842           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9843       Param->setScopeInfo(0, Params.size());
9844       Params.push_back(Param);
9845     }
9846   } else {
9847     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9848            "Should not need args for typedef of non-prototype fn");
9849   }
9850 
9851   // Finally, we know we have the right number of parameters, install them.
9852   NewFD->setParams(Params);
9853 
9854   if (D.getDeclSpec().isNoreturnSpecified())
9855     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9856                                            D.getDeclSpec().getNoreturnSpecLoc(),
9857                                            AttributeCommonInfo::AS_Keyword));
9858 
9859   // Functions returning a variably modified type violate C99 6.7.5.2p2
9860   // because all functions have linkage.
9861   if (!NewFD->isInvalidDecl() &&
9862       NewFD->getReturnType()->isVariablyModifiedType()) {
9863     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9864     NewFD->setInvalidDecl();
9865   }
9866 
9867   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9868   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9869       !NewFD->hasAttr<SectionAttr>())
9870     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9871         Context, PragmaClangTextSection.SectionName,
9872         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9873 
9874   // Apply an implicit SectionAttr if #pragma code_seg is active.
9875   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9876       !NewFD->hasAttr<SectionAttr>()) {
9877     NewFD->addAttr(SectionAttr::CreateImplicit(
9878         Context, CodeSegStack.CurrentValue->getString(),
9879         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9880         SectionAttr::Declspec_allocate));
9881     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9882                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9883                          ASTContext::PSF_Read,
9884                      NewFD))
9885       NewFD->dropAttr<SectionAttr>();
9886   }
9887 
9888   // Apply an implicit CodeSegAttr from class declspec or
9889   // apply an implicit SectionAttr from #pragma code_seg if active.
9890   if (!NewFD->hasAttr<CodeSegAttr>()) {
9891     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9892                                                                  D.isFunctionDefinition())) {
9893       NewFD->addAttr(SAttr);
9894     }
9895   }
9896 
9897   // Handle attributes.
9898   ProcessDeclAttributes(S, NewFD, D);
9899 
9900   if (getLangOpts().OpenCL) {
9901     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9902     // type declaration will generate a compilation error.
9903     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9904     if (AddressSpace != LangAS::Default) {
9905       Diag(NewFD->getLocation(),
9906            diag::err_opencl_return_value_with_address_space);
9907       NewFD->setInvalidDecl();
9908     }
9909   }
9910 
9911   if (!getLangOpts().CPlusPlus) {
9912     // Perform semantic checking on the function declaration.
9913     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9914       CheckMain(NewFD, D.getDeclSpec());
9915 
9916     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9917       CheckMSVCRTEntryPoint(NewFD);
9918 
9919     if (!NewFD->isInvalidDecl())
9920       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9921                                                   isMemberSpecialization,
9922                                                   D.isFunctionDefinition()));
9923     else if (!Previous.empty())
9924       // Recover gracefully from an invalid redeclaration.
9925       D.setRedeclaration(true);
9926     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9927             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9928            "previous declaration set still overloaded");
9929 
9930     // Diagnose no-prototype function declarations with calling conventions that
9931     // don't support variadic calls. Only do this in C and do it after merging
9932     // possibly prototyped redeclarations.
9933     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9934     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9935       CallingConv CC = FT->getExtInfo().getCC();
9936       if (!supportsVariadicCall(CC)) {
9937         // Windows system headers sometimes accidentally use stdcall without
9938         // (void) parameters, so we relax this to a warning.
9939         int DiagID =
9940             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9941         Diag(NewFD->getLocation(), DiagID)
9942             << FunctionType::getNameForCallConv(CC);
9943       }
9944     }
9945 
9946    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9947        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9948      checkNonTrivialCUnion(NewFD->getReturnType(),
9949                            NewFD->getReturnTypeSourceRange().getBegin(),
9950                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9951   } else {
9952     // C++11 [replacement.functions]p3:
9953     //  The program's definitions shall not be specified as inline.
9954     //
9955     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9956     //
9957     // Suppress the diagnostic if the function is __attribute__((used)), since
9958     // that forces an external definition to be emitted.
9959     if (D.getDeclSpec().isInlineSpecified() &&
9960         NewFD->isReplaceableGlobalAllocationFunction() &&
9961         !NewFD->hasAttr<UsedAttr>())
9962       Diag(D.getDeclSpec().getInlineSpecLoc(),
9963            diag::ext_operator_new_delete_declared_inline)
9964         << NewFD->getDeclName();
9965 
9966     // If the declarator is a template-id, translate the parser's template
9967     // argument list into our AST format.
9968     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9969       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9970       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9971       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9972       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9973                                          TemplateId->NumArgs);
9974       translateTemplateArguments(TemplateArgsPtr,
9975                                  TemplateArgs);
9976 
9977       HasExplicitTemplateArgs = true;
9978 
9979       if (NewFD->isInvalidDecl()) {
9980         HasExplicitTemplateArgs = false;
9981       } else if (FunctionTemplate) {
9982         // Function template with explicit template arguments.
9983         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9984           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9985 
9986         HasExplicitTemplateArgs = false;
9987       } else {
9988         assert((isFunctionTemplateSpecialization ||
9989                 D.getDeclSpec().isFriendSpecified()) &&
9990                "should have a 'template<>' for this decl");
9991         // "friend void foo<>(int);" is an implicit specialization decl.
9992         isFunctionTemplateSpecialization = true;
9993       }
9994     } else if (isFriend && isFunctionTemplateSpecialization) {
9995       // This combination is only possible in a recovery case;  the user
9996       // wrote something like:
9997       //   template <> friend void foo(int);
9998       // which we're recovering from as if the user had written:
9999       //   friend void foo<>(int);
10000       // Go ahead and fake up a template id.
10001       HasExplicitTemplateArgs = true;
10002       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10003       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10004     }
10005 
10006     // We do not add HD attributes to specializations here because
10007     // they may have different constexpr-ness compared to their
10008     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10009     // may end up with different effective targets. Instead, a
10010     // specialization inherits its target attributes from its template
10011     // in the CheckFunctionTemplateSpecialization() call below.
10012     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10013       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10014 
10015     // If it's a friend (and only if it's a friend), it's possible
10016     // that either the specialized function type or the specialized
10017     // template is dependent, and therefore matching will fail.  In
10018     // this case, don't check the specialization yet.
10019     if (isFunctionTemplateSpecialization && isFriend &&
10020         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10021          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10022              TemplateArgs.arguments()))) {
10023       assert(HasExplicitTemplateArgs &&
10024              "friend function specialization without template args");
10025       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10026                                                        Previous))
10027         NewFD->setInvalidDecl();
10028     } else if (isFunctionTemplateSpecialization) {
10029       if (CurContext->isDependentContext() && CurContext->isRecord()
10030           && !isFriend) {
10031         isDependentClassScopeExplicitSpecialization = true;
10032       } else if (!NewFD->isInvalidDecl() &&
10033                  CheckFunctionTemplateSpecialization(
10034                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10035                      Previous))
10036         NewFD->setInvalidDecl();
10037 
10038       // C++ [dcl.stc]p1:
10039       //   A storage-class-specifier shall not be specified in an explicit
10040       //   specialization (14.7.3)
10041       FunctionTemplateSpecializationInfo *Info =
10042           NewFD->getTemplateSpecializationInfo();
10043       if (Info && SC != SC_None) {
10044         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10045           Diag(NewFD->getLocation(),
10046                diag::err_explicit_specialization_inconsistent_storage_class)
10047             << SC
10048             << FixItHint::CreateRemoval(
10049                                       D.getDeclSpec().getStorageClassSpecLoc());
10050 
10051         else
10052           Diag(NewFD->getLocation(),
10053                diag::ext_explicit_specialization_storage_class)
10054             << FixItHint::CreateRemoval(
10055                                       D.getDeclSpec().getStorageClassSpecLoc());
10056       }
10057     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10058       if (CheckMemberSpecialization(NewFD, Previous))
10059           NewFD->setInvalidDecl();
10060     }
10061 
10062     // Perform semantic checking on the function declaration.
10063     if (!isDependentClassScopeExplicitSpecialization) {
10064       if (!NewFD->isInvalidDecl() && NewFD->isMain())
10065         CheckMain(NewFD, D.getDeclSpec());
10066 
10067       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10068         CheckMSVCRTEntryPoint(NewFD);
10069 
10070       if (!NewFD->isInvalidDecl())
10071         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10072                                                     isMemberSpecialization,
10073                                                     D.isFunctionDefinition()));
10074       else if (!Previous.empty())
10075         // Recover gracefully from an invalid redeclaration.
10076         D.setRedeclaration(true);
10077     }
10078 
10079     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10080             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10081            "previous declaration set still overloaded");
10082 
10083     NamedDecl *PrincipalDecl = (FunctionTemplate
10084                                 ? cast<NamedDecl>(FunctionTemplate)
10085                                 : NewFD);
10086 
10087     if (isFriend && NewFD->getPreviousDecl()) {
10088       AccessSpecifier Access = AS_public;
10089       if (!NewFD->isInvalidDecl())
10090         Access = NewFD->getPreviousDecl()->getAccess();
10091 
10092       NewFD->setAccess(Access);
10093       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10094     }
10095 
10096     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10097         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10098       PrincipalDecl->setNonMemberOperator();
10099 
10100     // If we have a function template, check the template parameter
10101     // list. This will check and merge default template arguments.
10102     if (FunctionTemplate) {
10103       FunctionTemplateDecl *PrevTemplate =
10104                                      FunctionTemplate->getPreviousDecl();
10105       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10106                        PrevTemplate ? PrevTemplate->getTemplateParameters()
10107                                     : nullptr,
10108                             D.getDeclSpec().isFriendSpecified()
10109                               ? (D.isFunctionDefinition()
10110                                    ? TPC_FriendFunctionTemplateDefinition
10111                                    : TPC_FriendFunctionTemplate)
10112                               : (D.getCXXScopeSpec().isSet() &&
10113                                  DC && DC->isRecord() &&
10114                                  DC->isDependentContext())
10115                                   ? TPC_ClassTemplateMember
10116                                   : TPC_FunctionTemplate);
10117     }
10118 
10119     if (NewFD->isInvalidDecl()) {
10120       // Ignore all the rest of this.
10121     } else if (!D.isRedeclaration()) {
10122       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10123                                        AddToScope };
10124       // Fake up an access specifier if it's supposed to be a class member.
10125       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10126         NewFD->setAccess(AS_public);
10127 
10128       // Qualified decls generally require a previous declaration.
10129       if (D.getCXXScopeSpec().isSet()) {
10130         // ...with the major exception of templated-scope or
10131         // dependent-scope friend declarations.
10132 
10133         // TODO: we currently also suppress this check in dependent
10134         // contexts because (1) the parameter depth will be off when
10135         // matching friend templates and (2) we might actually be
10136         // selecting a friend based on a dependent factor.  But there
10137         // are situations where these conditions don't apply and we
10138         // can actually do this check immediately.
10139         //
10140         // Unless the scope is dependent, it's always an error if qualified
10141         // redeclaration lookup found nothing at all. Diagnose that now;
10142         // nothing will diagnose that error later.
10143         if (isFriend &&
10144             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10145              (!Previous.empty() && CurContext->isDependentContext()))) {
10146           // ignore these
10147         } else if (NewFD->isCPUDispatchMultiVersion() ||
10148                    NewFD->isCPUSpecificMultiVersion()) {
10149           // ignore this, we allow the redeclaration behavior here to create new
10150           // versions of the function.
10151         } else {
10152           // The user tried to provide an out-of-line definition for a
10153           // function that is a member of a class or namespace, but there
10154           // was no such member function declared (C++ [class.mfct]p2,
10155           // C++ [namespace.memdef]p2). For example:
10156           //
10157           // class X {
10158           //   void f() const;
10159           // };
10160           //
10161           // void X::f() { } // ill-formed
10162           //
10163           // Complain about this problem, and attempt to suggest close
10164           // matches (e.g., those that differ only in cv-qualifiers and
10165           // whether the parameter types are references).
10166 
10167           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10168                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10169             AddToScope = ExtraArgs.AddToScope;
10170             return Result;
10171           }
10172         }
10173 
10174         // Unqualified local friend declarations are required to resolve
10175         // to something.
10176       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10177         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10178                 *this, Previous, NewFD, ExtraArgs, true, S)) {
10179           AddToScope = ExtraArgs.AddToScope;
10180           return Result;
10181         }
10182       }
10183     } else if (!D.isFunctionDefinition() &&
10184                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10185                !isFriend && !isFunctionTemplateSpecialization &&
10186                !isMemberSpecialization) {
10187       // An out-of-line member function declaration must also be a
10188       // definition (C++ [class.mfct]p2).
10189       // Note that this is not the case for explicit specializations of
10190       // function templates or member functions of class templates, per
10191       // C++ [temp.expl.spec]p2. We also allow these declarations as an
10192       // extension for compatibility with old SWIG code which likes to
10193       // generate them.
10194       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10195         << D.getCXXScopeSpec().getRange();
10196     }
10197   }
10198 
10199   // If this is the first declaration of a library builtin function, add
10200   // attributes as appropriate.
10201   if (!D.isRedeclaration()) {
10202     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10203       if (unsigned BuiltinID = II->getBuiltinID()) {
10204         bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10205         if (!InStdNamespace &&
10206             NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10207           if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10208             // Validate the type matches unless this builtin is specified as
10209             // matching regardless of its declared type.
10210             if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10211               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10212             } else {
10213               ASTContext::GetBuiltinTypeError Error;
10214               LookupNecessaryTypesForBuiltin(S, BuiltinID);
10215               QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10216 
10217               if (!Error && !BuiltinType.isNull() &&
10218                   Context.hasSameFunctionTypeIgnoringExceptionSpec(
10219                       NewFD->getType(), BuiltinType))
10220                 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10221             }
10222           }
10223         } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10224                    isStdBuiltin(Context, NewFD, BuiltinID)) {
10225           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10226         }
10227       }
10228     }
10229   }
10230 
10231   ProcessPragmaWeak(S, NewFD);
10232   checkAttributesAfterMerging(*this, *NewFD);
10233 
10234   AddKnownFunctionAttributes(NewFD);
10235 
10236   if (NewFD->hasAttr<OverloadableAttr>() &&
10237       !NewFD->getType()->getAs<FunctionProtoType>()) {
10238     Diag(NewFD->getLocation(),
10239          diag::err_attribute_overloadable_no_prototype)
10240       << NewFD;
10241 
10242     // Turn this into a variadic function with no parameters.
10243     const auto *FT = NewFD->getType()->castAs<FunctionType>();
10244     FunctionProtoType::ExtProtoInfo EPI(
10245         Context.getDefaultCallingConvention(true, false));
10246     EPI.Variadic = true;
10247     EPI.ExtInfo = FT->getExtInfo();
10248 
10249     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10250     NewFD->setType(R);
10251   }
10252 
10253   // If there's a #pragma GCC visibility in scope, and this isn't a class
10254   // member, set the visibility of this function.
10255   if (!DC->isRecord() && NewFD->isExternallyVisible())
10256     AddPushedVisibilityAttribute(NewFD);
10257 
10258   // If there's a #pragma clang arc_cf_code_audited in scope, consider
10259   // marking the function.
10260   AddCFAuditedAttribute(NewFD);
10261 
10262   // If this is a function definition, check if we have to apply any
10263   // attributes (i.e. optnone and no_builtin) due to a pragma.
10264   if (D.isFunctionDefinition()) {
10265     AddRangeBasedOptnone(NewFD);
10266     AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10267     AddSectionMSAllocText(NewFD);
10268     ModifyFnAttributesMSPragmaOptimize(NewFD);
10269   }
10270 
10271   // If this is the first declaration of an extern C variable, update
10272   // the map of such variables.
10273   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10274       isIncompleteDeclExternC(*this, NewFD))
10275     RegisterLocallyScopedExternCDecl(NewFD, S);
10276 
10277   // Set this FunctionDecl's range up to the right paren.
10278   NewFD->setRangeEnd(D.getSourceRange().getEnd());
10279 
10280   if (D.isRedeclaration() && !Previous.empty()) {
10281     NamedDecl *Prev = Previous.getRepresentativeDecl();
10282     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10283                                    isMemberSpecialization ||
10284                                        isFunctionTemplateSpecialization,
10285                                    D.isFunctionDefinition());
10286   }
10287 
10288   if (getLangOpts().CUDA) {
10289     IdentifierInfo *II = NewFD->getIdentifier();
10290     if (II && II->isStr(getCudaConfigureFuncName()) &&
10291         !NewFD->isInvalidDecl() &&
10292         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10293       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10294         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10295             << getCudaConfigureFuncName();
10296       Context.setcudaConfigureCallDecl(NewFD);
10297     }
10298 
10299     // Variadic functions, other than a *declaration* of printf, are not allowed
10300     // in device-side CUDA code, unless someone passed
10301     // -fcuda-allow-variadic-functions.
10302     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10303         (NewFD->hasAttr<CUDADeviceAttr>() ||
10304          NewFD->hasAttr<CUDAGlobalAttr>()) &&
10305         !(II && II->isStr("printf") && NewFD->isExternC() &&
10306           !D.isFunctionDefinition())) {
10307       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10308     }
10309   }
10310 
10311   MarkUnusedFileScopedDecl(NewFD);
10312 
10313 
10314 
10315   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10316     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10317     if (SC == SC_Static) {
10318       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10319       D.setInvalidType();
10320     }
10321 
10322     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10323     if (!NewFD->getReturnType()->isVoidType()) {
10324       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10325       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10326           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10327                                 : FixItHint());
10328       D.setInvalidType();
10329     }
10330 
10331     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10332     for (auto Param : NewFD->parameters())
10333       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10334 
10335     if (getLangOpts().OpenCLCPlusPlus) {
10336       if (DC->isRecord()) {
10337         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10338         D.setInvalidType();
10339       }
10340       if (FunctionTemplate) {
10341         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10342         D.setInvalidType();
10343       }
10344     }
10345   }
10346 
10347   if (getLangOpts().CPlusPlus) {
10348     if (FunctionTemplate) {
10349       if (NewFD->isInvalidDecl())
10350         FunctionTemplate->setInvalidDecl();
10351       return FunctionTemplate;
10352     }
10353 
10354     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10355       CompleteMemberSpecialization(NewFD, Previous);
10356   }
10357 
10358   for (const ParmVarDecl *Param : NewFD->parameters()) {
10359     QualType PT = Param->getType();
10360 
10361     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10362     // types.
10363     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10364       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10365         QualType ElemTy = PipeTy->getElementType();
10366           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10367             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10368             D.setInvalidType();
10369           }
10370       }
10371     }
10372   }
10373 
10374   // Here we have an function template explicit specialization at class scope.
10375   // The actual specialization will be postponed to template instatiation
10376   // time via the ClassScopeFunctionSpecializationDecl node.
10377   if (isDependentClassScopeExplicitSpecialization) {
10378     ClassScopeFunctionSpecializationDecl *NewSpec =
10379                          ClassScopeFunctionSpecializationDecl::Create(
10380                                 Context, CurContext, NewFD->getLocation(),
10381                                 cast<CXXMethodDecl>(NewFD),
10382                                 HasExplicitTemplateArgs, TemplateArgs);
10383     CurContext->addDecl(NewSpec);
10384     AddToScope = false;
10385   }
10386 
10387   // Diagnose availability attributes. Availability cannot be used on functions
10388   // that are run during load/unload.
10389   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10390     if (NewFD->hasAttr<ConstructorAttr>()) {
10391       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10392           << 1;
10393       NewFD->dropAttr<AvailabilityAttr>();
10394     }
10395     if (NewFD->hasAttr<DestructorAttr>()) {
10396       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10397           << 2;
10398       NewFD->dropAttr<AvailabilityAttr>();
10399     }
10400   }
10401 
10402   // Diagnose no_builtin attribute on function declaration that are not a
10403   // definition.
10404   // FIXME: We should really be doing this in
10405   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10406   // the FunctionDecl and at this point of the code
10407   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10408   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10409   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10410     switch (D.getFunctionDefinitionKind()) {
10411     case FunctionDefinitionKind::Defaulted:
10412     case FunctionDefinitionKind::Deleted:
10413       Diag(NBA->getLocation(),
10414            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10415           << NBA->getSpelling();
10416       break;
10417     case FunctionDefinitionKind::Declaration:
10418       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10419           << NBA->getSpelling();
10420       break;
10421     case FunctionDefinitionKind::Definition:
10422       break;
10423     }
10424 
10425   return NewFD;
10426 }
10427 
10428 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10429 /// when __declspec(code_seg) "is applied to a class, all member functions of
10430 /// the class and nested classes -- this includes compiler-generated special
10431 /// member functions -- are put in the specified segment."
10432 /// The actual behavior is a little more complicated. The Microsoft compiler
10433 /// won't check outer classes if there is an active value from #pragma code_seg.
10434 /// The CodeSeg is always applied from the direct parent but only from outer
10435 /// classes when the #pragma code_seg stack is empty. See:
10436 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10437 /// available since MS has removed the page.
10438 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10439   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10440   if (!Method)
10441     return nullptr;
10442   const CXXRecordDecl *Parent = Method->getParent();
10443   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10444     Attr *NewAttr = SAttr->clone(S.getASTContext());
10445     NewAttr->setImplicit(true);
10446     return NewAttr;
10447   }
10448 
10449   // The Microsoft compiler won't check outer classes for the CodeSeg
10450   // when the #pragma code_seg stack is active.
10451   if (S.CodeSegStack.CurrentValue)
10452    return nullptr;
10453 
10454   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10455     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10456       Attr *NewAttr = SAttr->clone(S.getASTContext());
10457       NewAttr->setImplicit(true);
10458       return NewAttr;
10459     }
10460   }
10461   return nullptr;
10462 }
10463 
10464 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10465 /// containing class. Otherwise it will return implicit SectionAttr if the
10466 /// function is a definition and there is an active value on CodeSegStack
10467 /// (from the current #pragma code-seg value).
10468 ///
10469 /// \param FD Function being declared.
10470 /// \param IsDefinition Whether it is a definition or just a declarartion.
10471 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10472 ///          nullptr if no attribute should be added.
10473 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10474                                                        bool IsDefinition) {
10475   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10476     return A;
10477   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10478       CodeSegStack.CurrentValue)
10479     return SectionAttr::CreateImplicit(
10480         getASTContext(), CodeSegStack.CurrentValue->getString(),
10481         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10482         SectionAttr::Declspec_allocate);
10483   return nullptr;
10484 }
10485 
10486 /// Determines if we can perform a correct type check for \p D as a
10487 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10488 /// best-effort check.
10489 ///
10490 /// \param NewD The new declaration.
10491 /// \param OldD The old declaration.
10492 /// \param NewT The portion of the type of the new declaration to check.
10493 /// \param OldT The portion of the type of the old declaration to check.
10494 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10495                                           QualType NewT, QualType OldT) {
10496   if (!NewD->getLexicalDeclContext()->isDependentContext())
10497     return true;
10498 
10499   // For dependently-typed local extern declarations and friends, we can't
10500   // perform a correct type check in general until instantiation:
10501   //
10502   //   int f();
10503   //   template<typename T> void g() { T f(); }
10504   //
10505   // (valid if g() is only instantiated with T = int).
10506   if (NewT->isDependentType() &&
10507       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10508     return false;
10509 
10510   // Similarly, if the previous declaration was a dependent local extern
10511   // declaration, we don't really know its type yet.
10512   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10513     return false;
10514 
10515   return true;
10516 }
10517 
10518 /// Checks if the new declaration declared in dependent context must be
10519 /// put in the same redeclaration chain as the specified declaration.
10520 ///
10521 /// \param D Declaration that is checked.
10522 /// \param PrevDecl Previous declaration found with proper lookup method for the
10523 ///                 same declaration name.
10524 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10525 ///          belongs to.
10526 ///
10527 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10528   if (!D->getLexicalDeclContext()->isDependentContext())
10529     return true;
10530 
10531   // Don't chain dependent friend function definitions until instantiation, to
10532   // permit cases like
10533   //
10534   //   void func();
10535   //   template<typename T> class C1 { friend void func() {} };
10536   //   template<typename T> class C2 { friend void func() {} };
10537   //
10538   // ... which is valid if only one of C1 and C2 is ever instantiated.
10539   //
10540   // FIXME: This need only apply to function definitions. For now, we proxy
10541   // this by checking for a file-scope function. We do not want this to apply
10542   // to friend declarations nominating member functions, because that gets in
10543   // the way of access checks.
10544   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10545     return false;
10546 
10547   auto *VD = dyn_cast<ValueDecl>(D);
10548   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10549   return !VD || !PrevVD ||
10550          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10551                                         PrevVD->getType());
10552 }
10553 
10554 /// Check the target attribute of the function for MultiVersion
10555 /// validity.
10556 ///
10557 /// Returns true if there was an error, false otherwise.
10558 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10559   const auto *TA = FD->getAttr<TargetAttr>();
10560   assert(TA && "MultiVersion Candidate requires a target attribute");
10561   ParsedTargetAttr ParseInfo = TA->parse();
10562   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10563   enum ErrType { Feature = 0, Architecture = 1 };
10564 
10565   if (!ParseInfo.Architecture.empty() &&
10566       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10567     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10568         << Architecture << ParseInfo.Architecture;
10569     return true;
10570   }
10571 
10572   for (const auto &Feat : ParseInfo.Features) {
10573     auto BareFeat = StringRef{Feat}.substr(1);
10574     if (Feat[0] == '-') {
10575       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10576           << Feature << ("no-" + BareFeat).str();
10577       return true;
10578     }
10579 
10580     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10581         !TargetInfo.isValidFeatureName(BareFeat)) {
10582       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10583           << Feature << BareFeat;
10584       return true;
10585     }
10586   }
10587   return false;
10588 }
10589 
10590 // Provide a white-list of attributes that are allowed to be combined with
10591 // multiversion functions.
10592 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10593                                            MultiVersionKind MVKind) {
10594   // Note: this list/diagnosis must match the list in
10595   // checkMultiversionAttributesAllSame.
10596   switch (Kind) {
10597   default:
10598     return false;
10599   case attr::Used:
10600     return MVKind == MultiVersionKind::Target;
10601   case attr::NonNull:
10602   case attr::NoThrow:
10603     return true;
10604   }
10605 }
10606 
10607 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10608                                                  const FunctionDecl *FD,
10609                                                  const FunctionDecl *CausedFD,
10610                                                  MultiVersionKind MVKind) {
10611   const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10612     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10613         << static_cast<unsigned>(MVKind) << A;
10614     if (CausedFD)
10615       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10616     return true;
10617   };
10618 
10619   for (const Attr *A : FD->attrs()) {
10620     switch (A->getKind()) {
10621     case attr::CPUDispatch:
10622     case attr::CPUSpecific:
10623       if (MVKind != MultiVersionKind::CPUDispatch &&
10624           MVKind != MultiVersionKind::CPUSpecific)
10625         return Diagnose(S, A);
10626       break;
10627     case attr::Target:
10628       if (MVKind != MultiVersionKind::Target)
10629         return Diagnose(S, A);
10630       break;
10631     case attr::TargetClones:
10632       if (MVKind != MultiVersionKind::TargetClones)
10633         return Diagnose(S, A);
10634       break;
10635     default:
10636       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10637         return Diagnose(S, A);
10638       break;
10639     }
10640   }
10641   return false;
10642 }
10643 
10644 bool Sema::areMultiversionVariantFunctionsCompatible(
10645     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10646     const PartialDiagnostic &NoProtoDiagID,
10647     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10648     const PartialDiagnosticAt &NoSupportDiagIDAt,
10649     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10650     bool ConstexprSupported, bool CLinkageMayDiffer) {
10651   enum DoesntSupport {
10652     FuncTemplates = 0,
10653     VirtFuncs = 1,
10654     DeducedReturn = 2,
10655     Constructors = 3,
10656     Destructors = 4,
10657     DeletedFuncs = 5,
10658     DefaultedFuncs = 6,
10659     ConstexprFuncs = 7,
10660     ConstevalFuncs = 8,
10661     Lambda = 9,
10662   };
10663   enum Different {
10664     CallingConv = 0,
10665     ReturnType = 1,
10666     ConstexprSpec = 2,
10667     InlineSpec = 3,
10668     Linkage = 4,
10669     LanguageLinkage = 5,
10670   };
10671 
10672   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10673       !OldFD->getType()->getAs<FunctionProtoType>()) {
10674     Diag(OldFD->getLocation(), NoProtoDiagID);
10675     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10676     return true;
10677   }
10678 
10679   if (NoProtoDiagID.getDiagID() != 0 &&
10680       !NewFD->getType()->getAs<FunctionProtoType>())
10681     return Diag(NewFD->getLocation(), NoProtoDiagID);
10682 
10683   if (!TemplatesSupported &&
10684       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10685     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10686            << FuncTemplates;
10687 
10688   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10689     if (NewCXXFD->isVirtual())
10690       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10691              << VirtFuncs;
10692 
10693     if (isa<CXXConstructorDecl>(NewCXXFD))
10694       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10695              << Constructors;
10696 
10697     if (isa<CXXDestructorDecl>(NewCXXFD))
10698       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10699              << Destructors;
10700   }
10701 
10702   if (NewFD->isDeleted())
10703     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10704            << DeletedFuncs;
10705 
10706   if (NewFD->isDefaulted())
10707     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10708            << DefaultedFuncs;
10709 
10710   if (!ConstexprSupported && NewFD->isConstexpr())
10711     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10712            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10713 
10714   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10715   const auto *NewType = cast<FunctionType>(NewQType);
10716   QualType NewReturnType = NewType->getReturnType();
10717 
10718   if (NewReturnType->isUndeducedType())
10719     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10720            << DeducedReturn;
10721 
10722   // Ensure the return type is identical.
10723   if (OldFD) {
10724     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10725     const auto *OldType = cast<FunctionType>(OldQType);
10726     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10727     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10728 
10729     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10730       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10731 
10732     QualType OldReturnType = OldType->getReturnType();
10733 
10734     if (OldReturnType != NewReturnType)
10735       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10736 
10737     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10738       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10739 
10740     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10741       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10742 
10743     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10744       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10745 
10746     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10747       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10748 
10749     if (CheckEquivalentExceptionSpec(
10750             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10751             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10752       return true;
10753   }
10754   return false;
10755 }
10756 
10757 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10758                                              const FunctionDecl *NewFD,
10759                                              bool CausesMV,
10760                                              MultiVersionKind MVKind) {
10761   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10762     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10763     if (OldFD)
10764       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10765     return true;
10766   }
10767 
10768   bool IsCPUSpecificCPUDispatchMVKind =
10769       MVKind == MultiVersionKind::CPUDispatch ||
10770       MVKind == MultiVersionKind::CPUSpecific;
10771 
10772   if (CausesMV && OldFD &&
10773       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10774     return true;
10775 
10776   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10777     return true;
10778 
10779   // Only allow transition to MultiVersion if it hasn't been used.
10780   if (OldFD && CausesMV && OldFD->isUsed(false))
10781     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10782 
10783   return S.areMultiversionVariantFunctionsCompatible(
10784       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10785       PartialDiagnosticAt(NewFD->getLocation(),
10786                           S.PDiag(diag::note_multiversioning_caused_here)),
10787       PartialDiagnosticAt(NewFD->getLocation(),
10788                           S.PDiag(diag::err_multiversion_doesnt_support)
10789                               << static_cast<unsigned>(MVKind)),
10790       PartialDiagnosticAt(NewFD->getLocation(),
10791                           S.PDiag(diag::err_multiversion_diff)),
10792       /*TemplatesSupported=*/false,
10793       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10794       /*CLinkageMayDiffer=*/false);
10795 }
10796 
10797 /// Check the validity of a multiversion function declaration that is the
10798 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10799 ///
10800 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10801 ///
10802 /// Returns true if there was an error, false otherwise.
10803 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10804                                            MultiVersionKind MVKind,
10805                                            const TargetAttr *TA) {
10806   assert(MVKind != MultiVersionKind::None &&
10807          "Function lacks multiversion attribute");
10808 
10809   // Target only causes MV if it is default, otherwise this is a normal
10810   // function.
10811   if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10812     return false;
10813 
10814   if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10815     FD->setInvalidDecl();
10816     return true;
10817   }
10818 
10819   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10820     FD->setInvalidDecl();
10821     return true;
10822   }
10823 
10824   FD->setIsMultiVersion();
10825   return false;
10826 }
10827 
10828 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10829   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10830     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10831       return true;
10832   }
10833 
10834   return false;
10835 }
10836 
10837 static bool CheckTargetCausesMultiVersioning(
10838     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10839     bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10840   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10841   ParsedTargetAttr NewParsed = NewTA->parse();
10842   // Sort order doesn't matter, it just needs to be consistent.
10843   llvm::sort(NewParsed.Features);
10844 
10845   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10846   // to change, this is a simple redeclaration.
10847   if (!NewTA->isDefaultVersion() &&
10848       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10849     return false;
10850 
10851   // Otherwise, this decl causes MultiVersioning.
10852   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10853                                        MultiVersionKind::Target)) {
10854     NewFD->setInvalidDecl();
10855     return true;
10856   }
10857 
10858   if (CheckMultiVersionValue(S, NewFD)) {
10859     NewFD->setInvalidDecl();
10860     return true;
10861   }
10862 
10863   // If this is 'default', permit the forward declaration.
10864   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10865     Redeclaration = true;
10866     OldDecl = OldFD;
10867     OldFD->setIsMultiVersion();
10868     NewFD->setIsMultiVersion();
10869     return false;
10870   }
10871 
10872   if (CheckMultiVersionValue(S, OldFD)) {
10873     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10874     NewFD->setInvalidDecl();
10875     return true;
10876   }
10877 
10878   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10879 
10880   if (OldParsed == NewParsed) {
10881     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10882     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10883     NewFD->setInvalidDecl();
10884     return true;
10885   }
10886 
10887   for (const auto *FD : OldFD->redecls()) {
10888     const auto *CurTA = FD->getAttr<TargetAttr>();
10889     // We allow forward declarations before ANY multiversioning attributes, but
10890     // nothing after the fact.
10891     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10892         (!CurTA || CurTA->isInherited())) {
10893       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10894           << 0;
10895       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10896       NewFD->setInvalidDecl();
10897       return true;
10898     }
10899   }
10900 
10901   OldFD->setIsMultiVersion();
10902   NewFD->setIsMultiVersion();
10903   Redeclaration = false;
10904   OldDecl = nullptr;
10905   Previous.clear();
10906   return false;
10907 }
10908 
10909 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10910                                         MultiVersionKind New) {
10911   if (Old == New || Old == MultiVersionKind::None ||
10912       New == MultiVersionKind::None)
10913     return true;
10914 
10915   return (Old == MultiVersionKind::CPUDispatch &&
10916           New == MultiVersionKind::CPUSpecific) ||
10917          (Old == MultiVersionKind::CPUSpecific &&
10918           New == MultiVersionKind::CPUDispatch);
10919 }
10920 
10921 /// Check the validity of a new function declaration being added to an existing
10922 /// multiversioned declaration collection.
10923 static bool CheckMultiVersionAdditionalDecl(
10924     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10925     MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10926     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10927     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10928     LookupResult &Previous) {
10929 
10930   MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10931   // Disallow mixing of multiversioning types.
10932   if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10933     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10934     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10935     NewFD->setInvalidDecl();
10936     return true;
10937   }
10938 
10939   ParsedTargetAttr NewParsed;
10940   if (NewTA) {
10941     NewParsed = NewTA->parse();
10942     llvm::sort(NewParsed.Features);
10943   }
10944 
10945   bool UseMemberUsingDeclRules =
10946       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10947 
10948   bool MayNeedOverloadableChecks =
10949       AllowOverloadingOfFunction(Previous, S.Context, NewFD);
10950 
10951   // Next, check ALL non-overloads to see if this is a redeclaration of a
10952   // previous member of the MultiVersion set.
10953   for (NamedDecl *ND : Previous) {
10954     FunctionDecl *CurFD = ND->getAsFunction();
10955     if (!CurFD)
10956       continue;
10957     if (MayNeedOverloadableChecks &&
10958         S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10959       continue;
10960 
10961     switch (NewMVKind) {
10962     case MultiVersionKind::None:
10963       assert(OldMVKind == MultiVersionKind::TargetClones &&
10964              "Only target_clones can be omitted in subsequent declarations");
10965       break;
10966     case MultiVersionKind::Target: {
10967       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10968       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10969         NewFD->setIsMultiVersion();
10970         Redeclaration = true;
10971         OldDecl = ND;
10972         return false;
10973       }
10974 
10975       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10976       if (CurParsed == NewParsed) {
10977         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10978         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10979         NewFD->setInvalidDecl();
10980         return true;
10981       }
10982       break;
10983     }
10984     case MultiVersionKind::TargetClones: {
10985       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10986       Redeclaration = true;
10987       OldDecl = CurFD;
10988       NewFD->setIsMultiVersion();
10989 
10990       if (CurClones && NewClones &&
10991           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10992            !std::equal(CurClones->featuresStrs_begin(),
10993                        CurClones->featuresStrs_end(),
10994                        NewClones->featuresStrs_begin()))) {
10995         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10996         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10997         NewFD->setInvalidDecl();
10998         return true;
10999       }
11000 
11001       return false;
11002     }
11003     case MultiVersionKind::CPUSpecific:
11004     case MultiVersionKind::CPUDispatch: {
11005       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11006       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11007       // Handle CPUDispatch/CPUSpecific versions.
11008       // Only 1 CPUDispatch function is allowed, this will make it go through
11009       // the redeclaration errors.
11010       if (NewMVKind == MultiVersionKind::CPUDispatch &&
11011           CurFD->hasAttr<CPUDispatchAttr>()) {
11012         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11013             std::equal(
11014                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11015                 NewCPUDisp->cpus_begin(),
11016                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11017                   return Cur->getName() == New->getName();
11018                 })) {
11019           NewFD->setIsMultiVersion();
11020           Redeclaration = true;
11021           OldDecl = ND;
11022           return false;
11023         }
11024 
11025         // If the declarations don't match, this is an error condition.
11026         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11027         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11028         NewFD->setInvalidDecl();
11029         return true;
11030       }
11031       if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11032         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11033             std::equal(
11034                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11035                 NewCPUSpec->cpus_begin(),
11036                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11037                   return Cur->getName() == New->getName();
11038                 })) {
11039           NewFD->setIsMultiVersion();
11040           Redeclaration = true;
11041           OldDecl = ND;
11042           return false;
11043         }
11044 
11045         // Only 1 version of CPUSpecific is allowed for each CPU.
11046         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11047           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11048             if (CurII == NewII) {
11049               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11050                   << NewII;
11051               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11052               NewFD->setInvalidDecl();
11053               return true;
11054             }
11055           }
11056         }
11057       }
11058       break;
11059     }
11060     }
11061   }
11062 
11063   // Else, this is simply a non-redecl case.  Checking the 'value' is only
11064   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11065   // handled in the attribute adding step.
11066   if (NewMVKind == MultiVersionKind::Target &&
11067       CheckMultiVersionValue(S, NewFD)) {
11068     NewFD->setInvalidDecl();
11069     return true;
11070   }
11071 
11072   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11073                                        !OldFD->isMultiVersion(), NewMVKind)) {
11074     NewFD->setInvalidDecl();
11075     return true;
11076   }
11077 
11078   // Permit forward declarations in the case where these two are compatible.
11079   if (!OldFD->isMultiVersion()) {
11080     OldFD->setIsMultiVersion();
11081     NewFD->setIsMultiVersion();
11082     Redeclaration = true;
11083     OldDecl = OldFD;
11084     return false;
11085   }
11086 
11087   NewFD->setIsMultiVersion();
11088   Redeclaration = false;
11089   OldDecl = nullptr;
11090   Previous.clear();
11091   return false;
11092 }
11093 
11094 /// Check the validity of a mulitversion function declaration.
11095 /// Also sets the multiversion'ness' of the function itself.
11096 ///
11097 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11098 ///
11099 /// Returns true if there was an error, false otherwise.
11100 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11101                                       bool &Redeclaration, NamedDecl *&OldDecl,
11102                                       LookupResult &Previous) {
11103   const auto *NewTA = NewFD->getAttr<TargetAttr>();
11104   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11105   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11106   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11107   MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11108 
11109   // Main isn't allowed to become a multiversion function, however it IS
11110   // permitted to have 'main' be marked with the 'target' optimization hint.
11111   if (NewFD->isMain()) {
11112     if (MVKind != MultiVersionKind::None &&
11113         !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
11114       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11115       NewFD->setInvalidDecl();
11116       return true;
11117     }
11118     return false;
11119   }
11120 
11121   if (!OldDecl || !OldDecl->getAsFunction() ||
11122       OldDecl->getDeclContext()->getRedeclContext() !=
11123           NewFD->getDeclContext()->getRedeclContext()) {
11124     // If there's no previous declaration, AND this isn't attempting to cause
11125     // multiversioning, this isn't an error condition.
11126     if (MVKind == MultiVersionKind::None)
11127       return false;
11128     return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
11129   }
11130 
11131   FunctionDecl *OldFD = OldDecl->getAsFunction();
11132 
11133   if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11134     return false;
11135 
11136   // Multiversioned redeclarations aren't allowed to omit the attribute, except
11137   // for target_clones.
11138   if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11139       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
11140     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11141         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11142     NewFD->setInvalidDecl();
11143     return true;
11144   }
11145 
11146   if (!OldFD->isMultiVersion()) {
11147     switch (MVKind) {
11148     case MultiVersionKind::Target:
11149       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
11150                                               Redeclaration, OldDecl, Previous);
11151     case MultiVersionKind::TargetClones:
11152       if (OldFD->isUsed(false)) {
11153         NewFD->setInvalidDecl();
11154         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11155       }
11156       OldFD->setIsMultiVersion();
11157       break;
11158     case MultiVersionKind::CPUDispatch:
11159     case MultiVersionKind::CPUSpecific:
11160     case MultiVersionKind::None:
11161       break;
11162     }
11163   }
11164 
11165   // At this point, we have a multiversion function decl (in OldFD) AND an
11166   // appropriate attribute in the current function decl.  Resolve that these are
11167   // still compatible with previous declarations.
11168   return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11169                                          NewCPUDisp, NewCPUSpec, NewClones,
11170                                          Redeclaration, OldDecl, Previous);
11171 }
11172 
11173 /// Perform semantic checking of a new function declaration.
11174 ///
11175 /// Performs semantic analysis of the new function declaration
11176 /// NewFD. This routine performs all semantic checking that does not
11177 /// require the actual declarator involved in the declaration, and is
11178 /// used both for the declaration of functions as they are parsed
11179 /// (called via ActOnDeclarator) and for the declaration of functions
11180 /// that have been instantiated via C++ template instantiation (called
11181 /// via InstantiateDecl).
11182 ///
11183 /// \param IsMemberSpecialization whether this new function declaration is
11184 /// a member specialization (that replaces any definition provided by the
11185 /// previous declaration).
11186 ///
11187 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11188 ///
11189 /// \returns true if the function declaration is a redeclaration.
11190 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11191                                     LookupResult &Previous,
11192                                     bool IsMemberSpecialization,
11193                                     bool DeclIsDefn) {
11194   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11195          "Variably modified return types are not handled here");
11196 
11197   // Determine whether the type of this function should be merged with
11198   // a previous visible declaration. This never happens for functions in C++,
11199   // and always happens in C if the previous declaration was visible.
11200   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11201                                !Previous.isShadowed();
11202 
11203   bool Redeclaration = false;
11204   NamedDecl *OldDecl = nullptr;
11205   bool MayNeedOverloadableChecks = false;
11206 
11207   // Merge or overload the declaration with an existing declaration of
11208   // the same name, if appropriate.
11209   if (!Previous.empty()) {
11210     // Determine whether NewFD is an overload of PrevDecl or
11211     // a declaration that requires merging. If it's an overload,
11212     // there's no more work to do here; we'll just add the new
11213     // function to the scope.
11214     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11215       NamedDecl *Candidate = Previous.getRepresentativeDecl();
11216       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11217         Redeclaration = true;
11218         OldDecl = Candidate;
11219       }
11220     } else {
11221       MayNeedOverloadableChecks = true;
11222       switch (CheckOverload(S, NewFD, Previous, OldDecl,
11223                             /*NewIsUsingDecl*/ false)) {
11224       case Ovl_Match:
11225         Redeclaration = true;
11226         break;
11227 
11228       case Ovl_NonFunction:
11229         Redeclaration = true;
11230         break;
11231 
11232       case Ovl_Overload:
11233         Redeclaration = false;
11234         break;
11235       }
11236     }
11237   }
11238 
11239   // Check for a previous extern "C" declaration with this name.
11240   if (!Redeclaration &&
11241       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11242     if (!Previous.empty()) {
11243       // This is an extern "C" declaration with the same name as a previous
11244       // declaration, and thus redeclares that entity...
11245       Redeclaration = true;
11246       OldDecl = Previous.getFoundDecl();
11247       MergeTypeWithPrevious = false;
11248 
11249       // ... except in the presence of __attribute__((overloadable)).
11250       if (OldDecl->hasAttr<OverloadableAttr>() ||
11251           NewFD->hasAttr<OverloadableAttr>()) {
11252         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11253           MayNeedOverloadableChecks = true;
11254           Redeclaration = false;
11255           OldDecl = nullptr;
11256         }
11257       }
11258     }
11259   }
11260 
11261   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11262     return Redeclaration;
11263 
11264   // PPC MMA non-pointer types are not allowed as function return types.
11265   if (Context.getTargetInfo().getTriple().isPPC64() &&
11266       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11267     NewFD->setInvalidDecl();
11268   }
11269 
11270   // C++11 [dcl.constexpr]p8:
11271   //   A constexpr specifier for a non-static member function that is not
11272   //   a constructor declares that member function to be const.
11273   //
11274   // This needs to be delayed until we know whether this is an out-of-line
11275   // definition of a static member function.
11276   //
11277   // This rule is not present in C++1y, so we produce a backwards
11278   // compatibility warning whenever it happens in C++11.
11279   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11280   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11281       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11282       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11283     CXXMethodDecl *OldMD = nullptr;
11284     if (OldDecl)
11285       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11286     if (!OldMD || !OldMD->isStatic()) {
11287       const FunctionProtoType *FPT =
11288         MD->getType()->castAs<FunctionProtoType>();
11289       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11290       EPI.TypeQuals.addConst();
11291       MD->setType(Context.getFunctionType(FPT->getReturnType(),
11292                                           FPT->getParamTypes(), EPI));
11293 
11294       // Warn that we did this, if we're not performing template instantiation.
11295       // In that case, we'll have warned already when the template was defined.
11296       if (!inTemplateInstantiation()) {
11297         SourceLocation AddConstLoc;
11298         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11299                 .IgnoreParens().getAs<FunctionTypeLoc>())
11300           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11301 
11302         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11303           << FixItHint::CreateInsertion(AddConstLoc, " const");
11304       }
11305     }
11306   }
11307 
11308   if (Redeclaration) {
11309     // NewFD and OldDecl represent declarations that need to be
11310     // merged.
11311     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11312                           DeclIsDefn)) {
11313       NewFD->setInvalidDecl();
11314       return Redeclaration;
11315     }
11316 
11317     Previous.clear();
11318     Previous.addDecl(OldDecl);
11319 
11320     if (FunctionTemplateDecl *OldTemplateDecl =
11321             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11322       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11323       FunctionTemplateDecl *NewTemplateDecl
11324         = NewFD->getDescribedFunctionTemplate();
11325       assert(NewTemplateDecl && "Template/non-template mismatch");
11326 
11327       // The call to MergeFunctionDecl above may have created some state in
11328       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11329       // can add it as a redeclaration.
11330       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11331 
11332       NewFD->setPreviousDeclaration(OldFD);
11333       if (NewFD->isCXXClassMember()) {
11334         NewFD->setAccess(OldTemplateDecl->getAccess());
11335         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11336       }
11337 
11338       // If this is an explicit specialization of a member that is a function
11339       // template, mark it as a member specialization.
11340       if (IsMemberSpecialization &&
11341           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11342         NewTemplateDecl->setMemberSpecialization();
11343         assert(OldTemplateDecl->isMemberSpecialization());
11344         // Explicit specializations of a member template do not inherit deleted
11345         // status from the parent member template that they are specializing.
11346         if (OldFD->isDeleted()) {
11347           // FIXME: This assert will not hold in the presence of modules.
11348           assert(OldFD->getCanonicalDecl() == OldFD);
11349           // FIXME: We need an update record for this AST mutation.
11350           OldFD->setDeletedAsWritten(false);
11351         }
11352       }
11353 
11354     } else {
11355       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11356         auto *OldFD = cast<FunctionDecl>(OldDecl);
11357         // This needs to happen first so that 'inline' propagates.
11358         NewFD->setPreviousDeclaration(OldFD);
11359         if (NewFD->isCXXClassMember())
11360           NewFD->setAccess(OldFD->getAccess());
11361       }
11362     }
11363   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11364              !NewFD->getAttr<OverloadableAttr>()) {
11365     assert((Previous.empty() ||
11366             llvm::any_of(Previous,
11367                          [](const NamedDecl *ND) {
11368                            return ND->hasAttr<OverloadableAttr>();
11369                          })) &&
11370            "Non-redecls shouldn't happen without overloadable present");
11371 
11372     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11373       const auto *FD = dyn_cast<FunctionDecl>(ND);
11374       return FD && !FD->hasAttr<OverloadableAttr>();
11375     });
11376 
11377     if (OtherUnmarkedIter != Previous.end()) {
11378       Diag(NewFD->getLocation(),
11379            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11380       Diag((*OtherUnmarkedIter)->getLocation(),
11381            diag::note_attribute_overloadable_prev_overload)
11382           << false;
11383 
11384       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11385     }
11386   }
11387 
11388   if (LangOpts.OpenMP)
11389     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11390 
11391   // Semantic checking for this function declaration (in isolation).
11392 
11393   if (getLangOpts().CPlusPlus) {
11394     // C++-specific checks.
11395     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11396       CheckConstructor(Constructor);
11397     } else if (CXXDestructorDecl *Destructor =
11398                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11399       CXXRecordDecl *Record = Destructor->getParent();
11400       QualType ClassType = Context.getTypeDeclType(Record);
11401 
11402       // FIXME: Shouldn't we be able to perform this check even when the class
11403       // type is dependent? Both gcc and edg can handle that.
11404       if (!ClassType->isDependentType()) {
11405         DeclarationName Name
11406           = Context.DeclarationNames.getCXXDestructorName(
11407                                         Context.getCanonicalType(ClassType));
11408         if (NewFD->getDeclName() != Name) {
11409           Diag(NewFD->getLocation(), diag::err_destructor_name);
11410           NewFD->setInvalidDecl();
11411           return Redeclaration;
11412         }
11413       }
11414     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11415       if (auto *TD = Guide->getDescribedFunctionTemplate())
11416         CheckDeductionGuideTemplate(TD);
11417 
11418       // A deduction guide is not on the list of entities that can be
11419       // explicitly specialized.
11420       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11421         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11422             << /*explicit specialization*/ 1;
11423     }
11424 
11425     // Find any virtual functions that this function overrides.
11426     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11427       if (!Method->isFunctionTemplateSpecialization() &&
11428           !Method->getDescribedFunctionTemplate() &&
11429           Method->isCanonicalDecl()) {
11430         AddOverriddenMethods(Method->getParent(), Method);
11431       }
11432       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11433         // C++2a [class.virtual]p6
11434         // A virtual method shall not have a requires-clause.
11435         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11436              diag::err_constrained_virtual_method);
11437 
11438       if (Method->isStatic())
11439         checkThisInStaticMemberFunctionType(Method);
11440     }
11441 
11442     // C++20: dcl.decl.general p4:
11443     // The optional requires-clause ([temp.pre]) in an init-declarator or
11444     // member-declarator shall be present only if the declarator declares a
11445     // templated function ([dcl.fct]).
11446     if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11447       if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
11448         Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11449     }
11450 
11451     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11452       ActOnConversionDeclarator(Conversion);
11453 
11454     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11455     if (NewFD->isOverloadedOperator() &&
11456         CheckOverloadedOperatorDeclaration(NewFD)) {
11457       NewFD->setInvalidDecl();
11458       return Redeclaration;
11459     }
11460 
11461     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11462     if (NewFD->getLiteralIdentifier() &&
11463         CheckLiteralOperatorDeclaration(NewFD)) {
11464       NewFD->setInvalidDecl();
11465       return Redeclaration;
11466     }
11467 
11468     // In C++, check default arguments now that we have merged decls. Unless
11469     // the lexical context is the class, because in this case this is done
11470     // during delayed parsing anyway.
11471     if (!CurContext->isRecord())
11472       CheckCXXDefaultArguments(NewFD);
11473 
11474     // If this function is declared as being extern "C", then check to see if
11475     // the function returns a UDT (class, struct, or union type) that is not C
11476     // compatible, and if it does, warn the user.
11477     // But, issue any diagnostic on the first declaration only.
11478     if (Previous.empty() && NewFD->isExternC()) {
11479       QualType R = NewFD->getReturnType();
11480       if (R->isIncompleteType() && !R->isVoidType())
11481         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11482             << NewFD << R;
11483       else if (!R.isPODType(Context) && !R->isVoidType() &&
11484                !R->isObjCObjectPointerType())
11485         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11486     }
11487 
11488     // C++1z [dcl.fct]p6:
11489     //   [...] whether the function has a non-throwing exception-specification
11490     //   [is] part of the function type
11491     //
11492     // This results in an ABI break between C++14 and C++17 for functions whose
11493     // declared type includes an exception-specification in a parameter or
11494     // return type. (Exception specifications on the function itself are OK in
11495     // most cases, and exception specifications are not permitted in most other
11496     // contexts where they could make it into a mangling.)
11497     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11498       auto HasNoexcept = [&](QualType T) -> bool {
11499         // Strip off declarator chunks that could be between us and a function
11500         // type. We don't need to look far, exception specifications are very
11501         // restricted prior to C++17.
11502         if (auto *RT = T->getAs<ReferenceType>())
11503           T = RT->getPointeeType();
11504         else if (T->isAnyPointerType())
11505           T = T->getPointeeType();
11506         else if (auto *MPT = T->getAs<MemberPointerType>())
11507           T = MPT->getPointeeType();
11508         if (auto *FPT = T->getAs<FunctionProtoType>())
11509           if (FPT->isNothrow())
11510             return true;
11511         return false;
11512       };
11513 
11514       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11515       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11516       for (QualType T : FPT->param_types())
11517         AnyNoexcept |= HasNoexcept(T);
11518       if (AnyNoexcept)
11519         Diag(NewFD->getLocation(),
11520              diag::warn_cxx17_compat_exception_spec_in_signature)
11521             << NewFD;
11522     }
11523 
11524     if (!Redeclaration && LangOpts.CUDA)
11525       checkCUDATargetOverload(NewFD, Previous);
11526   }
11527   return Redeclaration;
11528 }
11529 
11530 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11531   // C++11 [basic.start.main]p3:
11532   //   A program that [...] declares main to be inline, static or
11533   //   constexpr is ill-formed.
11534   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11535   //   appear in a declaration of main.
11536   // static main is not an error under C99, but we should warn about it.
11537   // We accept _Noreturn main as an extension.
11538   if (FD->getStorageClass() == SC_Static)
11539     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11540          ? diag::err_static_main : diag::warn_static_main)
11541       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11542   if (FD->isInlineSpecified())
11543     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11544       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11545   if (DS.isNoreturnSpecified()) {
11546     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11547     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11548     Diag(NoreturnLoc, diag::ext_noreturn_main);
11549     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11550       << FixItHint::CreateRemoval(NoreturnRange);
11551   }
11552   if (FD->isConstexpr()) {
11553     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11554         << FD->isConsteval()
11555         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11556     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11557   }
11558 
11559   if (getLangOpts().OpenCL) {
11560     Diag(FD->getLocation(), diag::err_opencl_no_main)
11561         << FD->hasAttr<OpenCLKernelAttr>();
11562     FD->setInvalidDecl();
11563     return;
11564   }
11565 
11566   // Functions named main in hlsl are default entries, but don't have specific
11567   // signatures they are required to conform to.
11568   if (getLangOpts().HLSL)
11569     return;
11570 
11571   QualType T = FD->getType();
11572   assert(T->isFunctionType() && "function decl is not of function type");
11573   const FunctionType* FT = T->castAs<FunctionType>();
11574 
11575   // Set default calling convention for main()
11576   if (FT->getCallConv() != CC_C) {
11577     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11578     FD->setType(QualType(FT, 0));
11579     T = Context.getCanonicalType(FD->getType());
11580   }
11581 
11582   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11583     // In C with GNU extensions we allow main() to have non-integer return
11584     // type, but we should warn about the extension, and we disable the
11585     // implicit-return-zero rule.
11586 
11587     // GCC in C mode accepts qualified 'int'.
11588     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11589       FD->setHasImplicitReturnZero(true);
11590     else {
11591       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11592       SourceRange RTRange = FD->getReturnTypeSourceRange();
11593       if (RTRange.isValid())
11594         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11595             << FixItHint::CreateReplacement(RTRange, "int");
11596     }
11597   } else {
11598     // In C and C++, main magically returns 0 if you fall off the end;
11599     // set the flag which tells us that.
11600     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11601 
11602     // All the standards say that main() should return 'int'.
11603     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11604       FD->setHasImplicitReturnZero(true);
11605     else {
11606       // Otherwise, this is just a flat-out error.
11607       SourceRange RTRange = FD->getReturnTypeSourceRange();
11608       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11609           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11610                                 : FixItHint());
11611       FD->setInvalidDecl(true);
11612     }
11613   }
11614 
11615   // Treat protoless main() as nullary.
11616   if (isa<FunctionNoProtoType>(FT)) return;
11617 
11618   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11619   unsigned nparams = FTP->getNumParams();
11620   assert(FD->getNumParams() == nparams);
11621 
11622   bool HasExtraParameters = (nparams > 3);
11623 
11624   if (FTP->isVariadic()) {
11625     Diag(FD->getLocation(), diag::ext_variadic_main);
11626     // FIXME: if we had information about the location of the ellipsis, we
11627     // could add a FixIt hint to remove it as a parameter.
11628   }
11629 
11630   // Darwin passes an undocumented fourth argument of type char**.  If
11631   // other platforms start sprouting these, the logic below will start
11632   // getting shifty.
11633   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11634     HasExtraParameters = false;
11635 
11636   if (HasExtraParameters) {
11637     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11638     FD->setInvalidDecl(true);
11639     nparams = 3;
11640   }
11641 
11642   // FIXME: a lot of the following diagnostics would be improved
11643   // if we had some location information about types.
11644 
11645   QualType CharPP =
11646     Context.getPointerType(Context.getPointerType(Context.CharTy));
11647   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11648 
11649   for (unsigned i = 0; i < nparams; ++i) {
11650     QualType AT = FTP->getParamType(i);
11651 
11652     bool mismatch = true;
11653 
11654     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11655       mismatch = false;
11656     else if (Expected[i] == CharPP) {
11657       // As an extension, the following forms are okay:
11658       //   char const **
11659       //   char const * const *
11660       //   char * const *
11661 
11662       QualifierCollector qs;
11663       const PointerType* PT;
11664       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11665           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11666           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11667                               Context.CharTy)) {
11668         qs.removeConst();
11669         mismatch = !qs.empty();
11670       }
11671     }
11672 
11673     if (mismatch) {
11674       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11675       // TODO: suggest replacing given type with expected type
11676       FD->setInvalidDecl(true);
11677     }
11678   }
11679 
11680   if (nparams == 1 && !FD->isInvalidDecl()) {
11681     Diag(FD->getLocation(), diag::warn_main_one_arg);
11682   }
11683 
11684   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11685     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11686     FD->setInvalidDecl();
11687   }
11688 }
11689 
11690 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11691 
11692   // Default calling convention for main and wmain is __cdecl
11693   if (FD->getName() == "main" || FD->getName() == "wmain")
11694     return false;
11695 
11696   // Default calling convention for MinGW is __cdecl
11697   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11698   if (T.isWindowsGNUEnvironment())
11699     return false;
11700 
11701   // Default calling convention for WinMain, wWinMain and DllMain
11702   // is __stdcall on 32 bit Windows
11703   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11704     return true;
11705 
11706   return false;
11707 }
11708 
11709 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11710   QualType T = FD->getType();
11711   assert(T->isFunctionType() && "function decl is not of function type");
11712   const FunctionType *FT = T->castAs<FunctionType>();
11713 
11714   // Set an implicit return of 'zero' if the function can return some integral,
11715   // enumeration, pointer or nullptr type.
11716   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11717       FT->getReturnType()->isAnyPointerType() ||
11718       FT->getReturnType()->isNullPtrType())
11719     // DllMain is exempt because a return value of zero means it failed.
11720     if (FD->getName() != "DllMain")
11721       FD->setHasImplicitReturnZero(true);
11722 
11723   // Explicity specified calling conventions are applied to MSVC entry points
11724   if (!hasExplicitCallingConv(T)) {
11725     if (isDefaultStdCall(FD, *this)) {
11726       if (FT->getCallConv() != CC_X86StdCall) {
11727         FT = Context.adjustFunctionType(
11728             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11729         FD->setType(QualType(FT, 0));
11730       }
11731     } else if (FT->getCallConv() != CC_C) {
11732       FT = Context.adjustFunctionType(FT,
11733                                       FT->getExtInfo().withCallingConv(CC_C));
11734       FD->setType(QualType(FT, 0));
11735     }
11736   }
11737 
11738   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11739     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11740     FD->setInvalidDecl();
11741   }
11742 }
11743 
11744 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11745   // FIXME: Need strict checking.  In C89, we need to check for
11746   // any assignment, increment, decrement, function-calls, or
11747   // commas outside of a sizeof.  In C99, it's the same list,
11748   // except that the aforementioned are allowed in unevaluated
11749   // expressions.  Everything else falls under the
11750   // "may accept other forms of constant expressions" exception.
11751   //
11752   // Regular C++ code will not end up here (exceptions: language extensions,
11753   // OpenCL C++ etc), so the constant expression rules there don't matter.
11754   if (Init->isValueDependent()) {
11755     assert(Init->containsErrors() &&
11756            "Dependent code should only occur in error-recovery path.");
11757     return true;
11758   }
11759   const Expr *Culprit;
11760   if (Init->isConstantInitializer(Context, false, &Culprit))
11761     return false;
11762   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11763     << Culprit->getSourceRange();
11764   return true;
11765 }
11766 
11767 namespace {
11768   // Visits an initialization expression to see if OrigDecl is evaluated in
11769   // its own initialization and throws a warning if it does.
11770   class SelfReferenceChecker
11771       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11772     Sema &S;
11773     Decl *OrigDecl;
11774     bool isRecordType;
11775     bool isPODType;
11776     bool isReferenceType;
11777 
11778     bool isInitList;
11779     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11780 
11781   public:
11782     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11783 
11784     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11785                                                     S(S), OrigDecl(OrigDecl) {
11786       isPODType = false;
11787       isRecordType = false;
11788       isReferenceType = false;
11789       isInitList = false;
11790       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11791         isPODType = VD->getType().isPODType(S.Context);
11792         isRecordType = VD->getType()->isRecordType();
11793         isReferenceType = VD->getType()->isReferenceType();
11794       }
11795     }
11796 
11797     // For most expressions, just call the visitor.  For initializer lists,
11798     // track the index of the field being initialized since fields are
11799     // initialized in order allowing use of previously initialized fields.
11800     void CheckExpr(Expr *E) {
11801       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11802       if (!InitList) {
11803         Visit(E);
11804         return;
11805       }
11806 
11807       // Track and increment the index here.
11808       isInitList = true;
11809       InitFieldIndex.push_back(0);
11810       for (auto Child : InitList->children()) {
11811         CheckExpr(cast<Expr>(Child));
11812         ++InitFieldIndex.back();
11813       }
11814       InitFieldIndex.pop_back();
11815     }
11816 
11817     // Returns true if MemberExpr is checked and no further checking is needed.
11818     // Returns false if additional checking is required.
11819     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11820       llvm::SmallVector<FieldDecl*, 4> Fields;
11821       Expr *Base = E;
11822       bool ReferenceField = false;
11823 
11824       // Get the field members used.
11825       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11826         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11827         if (!FD)
11828           return false;
11829         Fields.push_back(FD);
11830         if (FD->getType()->isReferenceType())
11831           ReferenceField = true;
11832         Base = ME->getBase()->IgnoreParenImpCasts();
11833       }
11834 
11835       // Keep checking only if the base Decl is the same.
11836       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11837       if (!DRE || DRE->getDecl() != OrigDecl)
11838         return false;
11839 
11840       // A reference field can be bound to an unininitialized field.
11841       if (CheckReference && !ReferenceField)
11842         return true;
11843 
11844       // Convert FieldDecls to their index number.
11845       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11846       for (const FieldDecl *I : llvm::reverse(Fields))
11847         UsedFieldIndex.push_back(I->getFieldIndex());
11848 
11849       // See if a warning is needed by checking the first difference in index
11850       // numbers.  If field being used has index less than the field being
11851       // initialized, then the use is safe.
11852       for (auto UsedIter = UsedFieldIndex.begin(),
11853                 UsedEnd = UsedFieldIndex.end(),
11854                 OrigIter = InitFieldIndex.begin(),
11855                 OrigEnd = InitFieldIndex.end();
11856            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11857         if (*UsedIter < *OrigIter)
11858           return true;
11859         if (*UsedIter > *OrigIter)
11860           break;
11861       }
11862 
11863       // TODO: Add a different warning which will print the field names.
11864       HandleDeclRefExpr(DRE);
11865       return true;
11866     }
11867 
11868     // For most expressions, the cast is directly above the DeclRefExpr.
11869     // For conditional operators, the cast can be outside the conditional
11870     // operator if both expressions are DeclRefExpr's.
11871     void HandleValue(Expr *E) {
11872       E = E->IgnoreParens();
11873       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11874         HandleDeclRefExpr(DRE);
11875         return;
11876       }
11877 
11878       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11879         Visit(CO->getCond());
11880         HandleValue(CO->getTrueExpr());
11881         HandleValue(CO->getFalseExpr());
11882         return;
11883       }
11884 
11885       if (BinaryConditionalOperator *BCO =
11886               dyn_cast<BinaryConditionalOperator>(E)) {
11887         Visit(BCO->getCond());
11888         HandleValue(BCO->getFalseExpr());
11889         return;
11890       }
11891 
11892       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11893         HandleValue(OVE->getSourceExpr());
11894         return;
11895       }
11896 
11897       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11898         if (BO->getOpcode() == BO_Comma) {
11899           Visit(BO->getLHS());
11900           HandleValue(BO->getRHS());
11901           return;
11902         }
11903       }
11904 
11905       if (isa<MemberExpr>(E)) {
11906         if (isInitList) {
11907           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11908                                       false /*CheckReference*/))
11909             return;
11910         }
11911 
11912         Expr *Base = E->IgnoreParenImpCasts();
11913         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11914           // Check for static member variables and don't warn on them.
11915           if (!isa<FieldDecl>(ME->getMemberDecl()))
11916             return;
11917           Base = ME->getBase()->IgnoreParenImpCasts();
11918         }
11919         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11920           HandleDeclRefExpr(DRE);
11921         return;
11922       }
11923 
11924       Visit(E);
11925     }
11926 
11927     // Reference types not handled in HandleValue are handled here since all
11928     // uses of references are bad, not just r-value uses.
11929     void VisitDeclRefExpr(DeclRefExpr *E) {
11930       if (isReferenceType)
11931         HandleDeclRefExpr(E);
11932     }
11933 
11934     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11935       if (E->getCastKind() == CK_LValueToRValue) {
11936         HandleValue(E->getSubExpr());
11937         return;
11938       }
11939 
11940       Inherited::VisitImplicitCastExpr(E);
11941     }
11942 
11943     void VisitMemberExpr(MemberExpr *E) {
11944       if (isInitList) {
11945         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11946           return;
11947       }
11948 
11949       // Don't warn on arrays since they can be treated as pointers.
11950       if (E->getType()->canDecayToPointerType()) return;
11951 
11952       // Warn when a non-static method call is followed by non-static member
11953       // field accesses, which is followed by a DeclRefExpr.
11954       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11955       bool Warn = (MD && !MD->isStatic());
11956       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11957       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11958         if (!isa<FieldDecl>(ME->getMemberDecl()))
11959           Warn = false;
11960         Base = ME->getBase()->IgnoreParenImpCasts();
11961       }
11962 
11963       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11964         if (Warn)
11965           HandleDeclRefExpr(DRE);
11966         return;
11967       }
11968 
11969       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11970       // Visit that expression.
11971       Visit(Base);
11972     }
11973 
11974     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11975       Expr *Callee = E->getCallee();
11976 
11977       if (isa<UnresolvedLookupExpr>(Callee))
11978         return Inherited::VisitCXXOperatorCallExpr(E);
11979 
11980       Visit(Callee);
11981       for (auto Arg: E->arguments())
11982         HandleValue(Arg->IgnoreParenImpCasts());
11983     }
11984 
11985     void VisitUnaryOperator(UnaryOperator *E) {
11986       // For POD record types, addresses of its own members are well-defined.
11987       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11988           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11989         if (!isPODType)
11990           HandleValue(E->getSubExpr());
11991         return;
11992       }
11993 
11994       if (E->isIncrementDecrementOp()) {
11995         HandleValue(E->getSubExpr());
11996         return;
11997       }
11998 
11999       Inherited::VisitUnaryOperator(E);
12000     }
12001 
12002     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12003 
12004     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12005       if (E->getConstructor()->isCopyConstructor()) {
12006         Expr *ArgExpr = E->getArg(0);
12007         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12008           if (ILE->getNumInits() == 1)
12009             ArgExpr = ILE->getInit(0);
12010         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12011           if (ICE->getCastKind() == CK_NoOp)
12012             ArgExpr = ICE->getSubExpr();
12013         HandleValue(ArgExpr);
12014         return;
12015       }
12016       Inherited::VisitCXXConstructExpr(E);
12017     }
12018 
12019     void VisitCallExpr(CallExpr *E) {
12020       // Treat std::move as a use.
12021       if (E->isCallToStdMove()) {
12022         HandleValue(E->getArg(0));
12023         return;
12024       }
12025 
12026       Inherited::VisitCallExpr(E);
12027     }
12028 
12029     void VisitBinaryOperator(BinaryOperator *E) {
12030       if (E->isCompoundAssignmentOp()) {
12031         HandleValue(E->getLHS());
12032         Visit(E->getRHS());
12033         return;
12034       }
12035 
12036       Inherited::VisitBinaryOperator(E);
12037     }
12038 
12039     // A custom visitor for BinaryConditionalOperator is needed because the
12040     // regular visitor would check the condition and true expression separately
12041     // but both point to the same place giving duplicate diagnostics.
12042     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12043       Visit(E->getCond());
12044       Visit(E->getFalseExpr());
12045     }
12046 
12047     void HandleDeclRefExpr(DeclRefExpr *DRE) {
12048       Decl* ReferenceDecl = DRE->getDecl();
12049       if (OrigDecl != ReferenceDecl) return;
12050       unsigned diag;
12051       if (isReferenceType) {
12052         diag = diag::warn_uninit_self_reference_in_reference_init;
12053       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12054         diag = diag::warn_static_self_reference_in_init;
12055       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12056                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12057                  DRE->getDecl()->getType()->isRecordType()) {
12058         diag = diag::warn_uninit_self_reference_in_init;
12059       } else {
12060         // Local variables will be handled by the CFG analysis.
12061         return;
12062       }
12063 
12064       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12065                             S.PDiag(diag)
12066                                 << DRE->getDecl() << OrigDecl->getLocation()
12067                                 << DRE->getSourceRange());
12068     }
12069   };
12070 
12071   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12072   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12073                                  bool DirectInit) {
12074     // Parameters arguments are occassionially constructed with itself,
12075     // for instance, in recursive functions.  Skip them.
12076     if (isa<ParmVarDecl>(OrigDecl))
12077       return;
12078 
12079     E = E->IgnoreParens();
12080 
12081     // Skip checking T a = a where T is not a record or reference type.
12082     // Doing so is a way to silence uninitialized warnings.
12083     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12084       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12085         if (ICE->getCastKind() == CK_LValueToRValue)
12086           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12087             if (DRE->getDecl() == OrigDecl)
12088               return;
12089 
12090     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12091   }
12092 } // end anonymous namespace
12093 
12094 namespace {
12095   // Simple wrapper to add the name of a variable or (if no variable is
12096   // available) a DeclarationName into a diagnostic.
12097   struct VarDeclOrName {
12098     VarDecl *VDecl;
12099     DeclarationName Name;
12100 
12101     friend const Sema::SemaDiagnosticBuilder &
12102     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12103       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12104     }
12105   };
12106 } // end anonymous namespace
12107 
12108 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12109                                             DeclarationName Name, QualType Type,
12110                                             TypeSourceInfo *TSI,
12111                                             SourceRange Range, bool DirectInit,
12112                                             Expr *Init) {
12113   bool IsInitCapture = !VDecl;
12114   assert((!VDecl || !VDecl->isInitCapture()) &&
12115          "init captures are expected to be deduced prior to initialization");
12116 
12117   VarDeclOrName VN{VDecl, Name};
12118 
12119   DeducedType *Deduced = Type->getContainedDeducedType();
12120   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12121 
12122   // C++11 [dcl.spec.auto]p3
12123   if (!Init) {
12124     assert(VDecl && "no init for init capture deduction?");
12125 
12126     // Except for class argument deduction, and then for an initializing
12127     // declaration only, i.e. no static at class scope or extern.
12128     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12129         VDecl->hasExternalStorage() ||
12130         VDecl->isStaticDataMember()) {
12131       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12132         << VDecl->getDeclName() << Type;
12133       return QualType();
12134     }
12135   }
12136 
12137   ArrayRef<Expr*> DeduceInits;
12138   if (Init)
12139     DeduceInits = Init;
12140 
12141   if (DirectInit) {
12142     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
12143       DeduceInits = PL->exprs();
12144   }
12145 
12146   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12147     assert(VDecl && "non-auto type for init capture deduction?");
12148     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12149     InitializationKind Kind = InitializationKind::CreateForInit(
12150         VDecl->getLocation(), DirectInit, Init);
12151     // FIXME: Initialization should not be taking a mutable list of inits.
12152     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12153     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12154                                                        InitsCopy);
12155   }
12156 
12157   if (DirectInit) {
12158     if (auto *IL = dyn_cast<InitListExpr>(Init))
12159       DeduceInits = IL->inits();
12160   }
12161 
12162   // Deduction only works if we have exactly one source expression.
12163   if (DeduceInits.empty()) {
12164     // It isn't possible to write this directly, but it is possible to
12165     // end up in this situation with "auto x(some_pack...);"
12166     Diag(Init->getBeginLoc(), IsInitCapture
12167                                   ? diag::err_init_capture_no_expression
12168                                   : diag::err_auto_var_init_no_expression)
12169         << VN << Type << Range;
12170     return QualType();
12171   }
12172 
12173   if (DeduceInits.size() > 1) {
12174     Diag(DeduceInits[1]->getBeginLoc(),
12175          IsInitCapture ? diag::err_init_capture_multiple_expressions
12176                        : diag::err_auto_var_init_multiple_expressions)
12177         << VN << Type << Range;
12178     return QualType();
12179   }
12180 
12181   Expr *DeduceInit = DeduceInits[0];
12182   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12183     Diag(Init->getBeginLoc(), IsInitCapture
12184                                   ? diag::err_init_capture_paren_braces
12185                                   : diag::err_auto_var_init_paren_braces)
12186         << isa<InitListExpr>(Init) << VN << Type << Range;
12187     return QualType();
12188   }
12189 
12190   // Expressions default to 'id' when we're in a debugger.
12191   bool DefaultedAnyToId = false;
12192   if (getLangOpts().DebuggerCastResultToId &&
12193       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12194     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12195     if (Result.isInvalid()) {
12196       return QualType();
12197     }
12198     Init = Result.get();
12199     DefaultedAnyToId = true;
12200   }
12201 
12202   // C++ [dcl.decomp]p1:
12203   //   If the assignment-expression [...] has array type A and no ref-qualifier
12204   //   is present, e has type cv A
12205   if (VDecl && isa<DecompositionDecl>(VDecl) &&
12206       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12207       DeduceInit->getType()->isConstantArrayType())
12208     return Context.getQualifiedType(DeduceInit->getType(),
12209                                     Type.getQualifiers());
12210 
12211   QualType DeducedType;
12212   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12213     if (!IsInitCapture)
12214       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12215     else if (isa<InitListExpr>(Init))
12216       Diag(Range.getBegin(),
12217            diag::err_init_capture_deduction_failure_from_init_list)
12218           << VN
12219           << (DeduceInit->getType().isNull() ? TSI->getType()
12220                                              : DeduceInit->getType())
12221           << DeduceInit->getSourceRange();
12222     else
12223       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12224           << VN << TSI->getType()
12225           << (DeduceInit->getType().isNull() ? TSI->getType()
12226                                              : DeduceInit->getType())
12227           << DeduceInit->getSourceRange();
12228   }
12229 
12230   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12231   // 'id' instead of a specific object type prevents most of our usual
12232   // checks.
12233   // We only want to warn outside of template instantiations, though:
12234   // inside a template, the 'id' could have come from a parameter.
12235   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12236       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12237     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12238     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12239   }
12240 
12241   return DeducedType;
12242 }
12243 
12244 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12245                                          Expr *Init) {
12246   assert(!Init || !Init->containsErrors());
12247   QualType DeducedType = deduceVarTypeFromInitializer(
12248       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12249       VDecl->getSourceRange(), DirectInit, Init);
12250   if (DeducedType.isNull()) {
12251     VDecl->setInvalidDecl();
12252     return true;
12253   }
12254 
12255   VDecl->setType(DeducedType);
12256   assert(VDecl->isLinkageValid());
12257 
12258   // In ARC, infer lifetime.
12259   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12260     VDecl->setInvalidDecl();
12261 
12262   if (getLangOpts().OpenCL)
12263     deduceOpenCLAddressSpace(VDecl);
12264 
12265   // If this is a redeclaration, check that the type we just deduced matches
12266   // the previously declared type.
12267   if (VarDecl *Old = VDecl->getPreviousDecl()) {
12268     // We never need to merge the type, because we cannot form an incomplete
12269     // array of auto, nor deduce such a type.
12270     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12271   }
12272 
12273   // Check the deduced type is valid for a variable declaration.
12274   CheckVariableDeclarationType(VDecl);
12275   return VDecl->isInvalidDecl();
12276 }
12277 
12278 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
12279                                               SourceLocation Loc) {
12280   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12281     Init = EWC->getSubExpr();
12282 
12283   if (auto *CE = dyn_cast<ConstantExpr>(Init))
12284     Init = CE->getSubExpr();
12285 
12286   QualType InitType = Init->getType();
12287   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12288           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12289          "shouldn't be called if type doesn't have a non-trivial C struct");
12290   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12291     for (auto I : ILE->inits()) {
12292       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12293           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12294         continue;
12295       SourceLocation SL = I->getExprLoc();
12296       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12297     }
12298     return;
12299   }
12300 
12301   if (isa<ImplicitValueInitExpr>(Init)) {
12302     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12303       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12304                             NTCUK_Init);
12305   } else {
12306     // Assume all other explicit initializers involving copying some existing
12307     // object.
12308     // TODO: ignore any explicit initializers where we can guarantee
12309     // copy-elision.
12310     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12311       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12312   }
12313 }
12314 
12315 namespace {
12316 
12317 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12318   // Ignore unavailable fields. A field can be marked as unavailable explicitly
12319   // in the source code or implicitly by the compiler if it is in a union
12320   // defined in a system header and has non-trivial ObjC ownership
12321   // qualifications. We don't want those fields to participate in determining
12322   // whether the containing union is non-trivial.
12323   return FD->hasAttr<UnavailableAttr>();
12324 }
12325 
12326 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12327     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12328                                     void> {
12329   using Super =
12330       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12331                                     void>;
12332 
12333   DiagNonTrivalCUnionDefaultInitializeVisitor(
12334       QualType OrigTy, SourceLocation OrigLoc,
12335       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12336       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12337 
12338   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12339                      const FieldDecl *FD, bool InNonTrivialUnion) {
12340     if (const auto *AT = S.Context.getAsArrayType(QT))
12341       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12342                                      InNonTrivialUnion);
12343     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12344   }
12345 
12346   void visitARCStrong(QualType QT, const FieldDecl *FD,
12347                       bool InNonTrivialUnion) {
12348     if (InNonTrivialUnion)
12349       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12350           << 1 << 0 << QT << FD->getName();
12351   }
12352 
12353   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12354     if (InNonTrivialUnion)
12355       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12356           << 1 << 0 << QT << FD->getName();
12357   }
12358 
12359   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12360     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12361     if (RD->isUnion()) {
12362       if (OrigLoc.isValid()) {
12363         bool IsUnion = false;
12364         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12365           IsUnion = OrigRD->isUnion();
12366         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12367             << 0 << OrigTy << IsUnion << UseContext;
12368         // Reset OrigLoc so that this diagnostic is emitted only once.
12369         OrigLoc = SourceLocation();
12370       }
12371       InNonTrivialUnion = true;
12372     }
12373 
12374     if (InNonTrivialUnion)
12375       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12376           << 0 << 0 << QT.getUnqualifiedType() << "";
12377 
12378     for (const FieldDecl *FD : RD->fields())
12379       if (!shouldIgnoreForRecordTriviality(FD))
12380         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12381   }
12382 
12383   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12384 
12385   // The non-trivial C union type or the struct/union type that contains a
12386   // non-trivial C union.
12387   QualType OrigTy;
12388   SourceLocation OrigLoc;
12389   Sema::NonTrivialCUnionContext UseContext;
12390   Sema &S;
12391 };
12392 
12393 struct DiagNonTrivalCUnionDestructedTypeVisitor
12394     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12395   using Super =
12396       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12397 
12398   DiagNonTrivalCUnionDestructedTypeVisitor(
12399       QualType OrigTy, SourceLocation OrigLoc,
12400       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12401       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12402 
12403   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12404                      const FieldDecl *FD, bool InNonTrivialUnion) {
12405     if (const auto *AT = S.Context.getAsArrayType(QT))
12406       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12407                                      InNonTrivialUnion);
12408     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12409   }
12410 
12411   void visitARCStrong(QualType QT, const FieldDecl *FD,
12412                       bool InNonTrivialUnion) {
12413     if (InNonTrivialUnion)
12414       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12415           << 1 << 1 << QT << FD->getName();
12416   }
12417 
12418   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12419     if (InNonTrivialUnion)
12420       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12421           << 1 << 1 << QT << FD->getName();
12422   }
12423 
12424   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12425     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12426     if (RD->isUnion()) {
12427       if (OrigLoc.isValid()) {
12428         bool IsUnion = false;
12429         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12430           IsUnion = OrigRD->isUnion();
12431         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12432             << 1 << OrigTy << IsUnion << UseContext;
12433         // Reset OrigLoc so that this diagnostic is emitted only once.
12434         OrigLoc = SourceLocation();
12435       }
12436       InNonTrivialUnion = true;
12437     }
12438 
12439     if (InNonTrivialUnion)
12440       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12441           << 0 << 1 << QT.getUnqualifiedType() << "";
12442 
12443     for (const FieldDecl *FD : RD->fields())
12444       if (!shouldIgnoreForRecordTriviality(FD))
12445         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12446   }
12447 
12448   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12449   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12450                           bool InNonTrivialUnion) {}
12451 
12452   // The non-trivial C union type or the struct/union type that contains a
12453   // non-trivial C union.
12454   QualType OrigTy;
12455   SourceLocation OrigLoc;
12456   Sema::NonTrivialCUnionContext UseContext;
12457   Sema &S;
12458 };
12459 
12460 struct DiagNonTrivalCUnionCopyVisitor
12461     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12462   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12463 
12464   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12465                                  Sema::NonTrivialCUnionContext UseContext,
12466                                  Sema &S)
12467       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12468 
12469   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12470                      const FieldDecl *FD, bool InNonTrivialUnion) {
12471     if (const auto *AT = S.Context.getAsArrayType(QT))
12472       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12473                                      InNonTrivialUnion);
12474     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12475   }
12476 
12477   void visitARCStrong(QualType QT, const FieldDecl *FD,
12478                       bool InNonTrivialUnion) {
12479     if (InNonTrivialUnion)
12480       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12481           << 1 << 2 << QT << FD->getName();
12482   }
12483 
12484   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12485     if (InNonTrivialUnion)
12486       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12487           << 1 << 2 << QT << FD->getName();
12488   }
12489 
12490   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12491     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12492     if (RD->isUnion()) {
12493       if (OrigLoc.isValid()) {
12494         bool IsUnion = false;
12495         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12496           IsUnion = OrigRD->isUnion();
12497         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12498             << 2 << OrigTy << IsUnion << UseContext;
12499         // Reset OrigLoc so that this diagnostic is emitted only once.
12500         OrigLoc = SourceLocation();
12501       }
12502       InNonTrivialUnion = true;
12503     }
12504 
12505     if (InNonTrivialUnion)
12506       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12507           << 0 << 2 << QT.getUnqualifiedType() << "";
12508 
12509     for (const FieldDecl *FD : RD->fields())
12510       if (!shouldIgnoreForRecordTriviality(FD))
12511         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12512   }
12513 
12514   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12515                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12516   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12517   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12518                             bool InNonTrivialUnion) {}
12519 
12520   // The non-trivial C union type or the struct/union type that contains a
12521   // non-trivial C union.
12522   QualType OrigTy;
12523   SourceLocation OrigLoc;
12524   Sema::NonTrivialCUnionContext UseContext;
12525   Sema &S;
12526 };
12527 
12528 } // namespace
12529 
12530 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12531                                  NonTrivialCUnionContext UseContext,
12532                                  unsigned NonTrivialKind) {
12533   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12534           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12535           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12536          "shouldn't be called if type doesn't have a non-trivial C union");
12537 
12538   if ((NonTrivialKind & NTCUK_Init) &&
12539       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12540     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12541         .visit(QT, nullptr, false);
12542   if ((NonTrivialKind & NTCUK_Destruct) &&
12543       QT.hasNonTrivialToPrimitiveDestructCUnion())
12544     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12545         .visit(QT, nullptr, false);
12546   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12547     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12548         .visit(QT, nullptr, false);
12549 }
12550 
12551 /// AddInitializerToDecl - Adds the initializer Init to the
12552 /// declaration dcl. If DirectInit is true, this is C++ direct
12553 /// initialization rather than copy initialization.
12554 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12555   // If there is no declaration, there was an error parsing it.  Just ignore
12556   // the initializer.
12557   if (!RealDecl || RealDecl->isInvalidDecl()) {
12558     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12559     return;
12560   }
12561 
12562   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12563     // Pure-specifiers are handled in ActOnPureSpecifier.
12564     Diag(Method->getLocation(), diag::err_member_function_initialization)
12565       << Method->getDeclName() << Init->getSourceRange();
12566     Method->setInvalidDecl();
12567     return;
12568   }
12569 
12570   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12571   if (!VDecl) {
12572     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12573     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12574     RealDecl->setInvalidDecl();
12575     return;
12576   }
12577 
12578   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12579   if (VDecl->getType()->isUndeducedType()) {
12580     // Attempt typo correction early so that the type of the init expression can
12581     // be deduced based on the chosen correction if the original init contains a
12582     // TypoExpr.
12583     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12584     if (!Res.isUsable()) {
12585       // There are unresolved typos in Init, just drop them.
12586       // FIXME: improve the recovery strategy to preserve the Init.
12587       RealDecl->setInvalidDecl();
12588       return;
12589     }
12590     if (Res.get()->containsErrors()) {
12591       // Invalidate the decl as we don't know the type for recovery-expr yet.
12592       RealDecl->setInvalidDecl();
12593       VDecl->setInit(Res.get());
12594       return;
12595     }
12596     Init = Res.get();
12597 
12598     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12599       return;
12600   }
12601 
12602   // dllimport cannot be used on variable definitions.
12603   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12604     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12605     VDecl->setInvalidDecl();
12606     return;
12607   }
12608 
12609   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12610     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12611     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12612     VDecl->setInvalidDecl();
12613     return;
12614   }
12615 
12616   if (!VDecl->getType()->isDependentType()) {
12617     // A definition must end up with a complete type, which means it must be
12618     // complete with the restriction that an array type might be completed by
12619     // the initializer; note that later code assumes this restriction.
12620     QualType BaseDeclType = VDecl->getType();
12621     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12622       BaseDeclType = Array->getElementType();
12623     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12624                             diag::err_typecheck_decl_incomplete_type)) {
12625       RealDecl->setInvalidDecl();
12626       return;
12627     }
12628 
12629     // The variable can not have an abstract class type.
12630     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12631                                diag::err_abstract_type_in_decl,
12632                                AbstractVariableType))
12633       VDecl->setInvalidDecl();
12634   }
12635 
12636   // If adding the initializer will turn this declaration into a definition,
12637   // and we already have a definition for this variable, diagnose or otherwise
12638   // handle the situation.
12639   if (VarDecl *Def = VDecl->getDefinition())
12640     if (Def != VDecl &&
12641         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12642         !VDecl->isThisDeclarationADemotedDefinition() &&
12643         checkVarDeclRedefinition(Def, VDecl))
12644       return;
12645 
12646   if (getLangOpts().CPlusPlus) {
12647     // C++ [class.static.data]p4
12648     //   If a static data member is of const integral or const
12649     //   enumeration type, its declaration in the class definition can
12650     //   specify a constant-initializer which shall be an integral
12651     //   constant expression (5.19). In that case, the member can appear
12652     //   in integral constant expressions. The member shall still be
12653     //   defined in a namespace scope if it is used in the program and the
12654     //   namespace scope definition shall not contain an initializer.
12655     //
12656     // We already performed a redefinition check above, but for static
12657     // data members we also need to check whether there was an in-class
12658     // declaration with an initializer.
12659     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12660       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12661           << VDecl->getDeclName();
12662       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12663            diag::note_previous_initializer)
12664           << 0;
12665       return;
12666     }
12667 
12668     if (VDecl->hasLocalStorage())
12669       setFunctionHasBranchProtectedScope();
12670 
12671     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12672       VDecl->setInvalidDecl();
12673       return;
12674     }
12675   }
12676 
12677   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12678   // a kernel function cannot be initialized."
12679   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12680     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12681     VDecl->setInvalidDecl();
12682     return;
12683   }
12684 
12685   // The LoaderUninitialized attribute acts as a definition (of undef).
12686   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12687     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12688     VDecl->setInvalidDecl();
12689     return;
12690   }
12691 
12692   // Get the decls type and save a reference for later, since
12693   // CheckInitializerTypes may change it.
12694   QualType DclT = VDecl->getType(), SavT = DclT;
12695 
12696   // Expressions default to 'id' when we're in a debugger
12697   // and we are assigning it to a variable of Objective-C pointer type.
12698   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12699       Init->getType() == Context.UnknownAnyTy) {
12700     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12701     if (Result.isInvalid()) {
12702       VDecl->setInvalidDecl();
12703       return;
12704     }
12705     Init = Result.get();
12706   }
12707 
12708   // Perform the initialization.
12709   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12710   if (!VDecl->isInvalidDecl()) {
12711     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12712     InitializationKind Kind = InitializationKind::CreateForInit(
12713         VDecl->getLocation(), DirectInit, Init);
12714 
12715     MultiExprArg Args = Init;
12716     if (CXXDirectInit)
12717       Args = MultiExprArg(CXXDirectInit->getExprs(),
12718                           CXXDirectInit->getNumExprs());
12719 
12720     // Try to correct any TypoExprs in the initialization arguments.
12721     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12722       ExprResult Res = CorrectDelayedTyposInExpr(
12723           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12724           [this, Entity, Kind](Expr *E) {
12725             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12726             return Init.Failed() ? ExprError() : E;
12727           });
12728       if (Res.isInvalid()) {
12729         VDecl->setInvalidDecl();
12730       } else if (Res.get() != Args[Idx]) {
12731         Args[Idx] = Res.get();
12732       }
12733     }
12734     if (VDecl->isInvalidDecl())
12735       return;
12736 
12737     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12738                                    /*TopLevelOfInitList=*/false,
12739                                    /*TreatUnavailableAsInvalid=*/false);
12740     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12741     if (Result.isInvalid()) {
12742       // If the provided initializer fails to initialize the var decl,
12743       // we attach a recovery expr for better recovery.
12744       auto RecoveryExpr =
12745           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12746       if (RecoveryExpr.get())
12747         VDecl->setInit(RecoveryExpr.get());
12748       return;
12749     }
12750 
12751     Init = Result.getAs<Expr>();
12752   }
12753 
12754   // Check for self-references within variable initializers.
12755   // Variables declared within a function/method body (except for references)
12756   // are handled by a dataflow analysis.
12757   // This is undefined behavior in C++, but valid in C.
12758   if (getLangOpts().CPlusPlus)
12759     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12760         VDecl->getType()->isReferenceType())
12761       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12762 
12763   // If the type changed, it means we had an incomplete type that was
12764   // completed by the initializer. For example:
12765   //   int ary[] = { 1, 3, 5 };
12766   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12767   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12768     VDecl->setType(DclT);
12769 
12770   if (!VDecl->isInvalidDecl()) {
12771     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12772 
12773     if (VDecl->hasAttr<BlocksAttr>())
12774       checkRetainCycles(VDecl, Init);
12775 
12776     // It is safe to assign a weak reference into a strong variable.
12777     // Although this code can still have problems:
12778     //   id x = self.weakProp;
12779     //   id y = self.weakProp;
12780     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12781     // paths through the function. This should be revisited if
12782     // -Wrepeated-use-of-weak is made flow-sensitive.
12783     if (FunctionScopeInfo *FSI = getCurFunction())
12784       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12785            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12786           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12787                            Init->getBeginLoc()))
12788         FSI->markSafeWeakUse(Init);
12789   }
12790 
12791   // The initialization is usually a full-expression.
12792   //
12793   // FIXME: If this is a braced initialization of an aggregate, it is not
12794   // an expression, and each individual field initializer is a separate
12795   // full-expression. For instance, in:
12796   //
12797   //   struct Temp { ~Temp(); };
12798   //   struct S { S(Temp); };
12799   //   struct T { S a, b; } t = { Temp(), Temp() }
12800   //
12801   // we should destroy the first Temp before constructing the second.
12802   ExprResult Result =
12803       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12804                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12805   if (Result.isInvalid()) {
12806     VDecl->setInvalidDecl();
12807     return;
12808   }
12809   Init = Result.get();
12810 
12811   // Attach the initializer to the decl.
12812   VDecl->setInit(Init);
12813 
12814   if (VDecl->isLocalVarDecl()) {
12815     // Don't check the initializer if the declaration is malformed.
12816     if (VDecl->isInvalidDecl()) {
12817       // do nothing
12818 
12819     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12820     // This is true even in C++ for OpenCL.
12821     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12822       CheckForConstantInitializer(Init, DclT);
12823 
12824     // Otherwise, C++ does not restrict the initializer.
12825     } else if (getLangOpts().CPlusPlus) {
12826       // do nothing
12827 
12828     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12829     // static storage duration shall be constant expressions or string literals.
12830     } else if (VDecl->getStorageClass() == SC_Static) {
12831       CheckForConstantInitializer(Init, DclT);
12832 
12833     // C89 is stricter than C99 for aggregate initializers.
12834     // C89 6.5.7p3: All the expressions [...] in an initializer list
12835     // for an object that has aggregate or union type shall be
12836     // constant expressions.
12837     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12838                isa<InitListExpr>(Init)) {
12839       const Expr *Culprit;
12840       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12841         Diag(Culprit->getExprLoc(),
12842              diag::ext_aggregate_init_not_constant)
12843           << Culprit->getSourceRange();
12844       }
12845     }
12846 
12847     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12848       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12849         if (VDecl->hasLocalStorage())
12850           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12851   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12852              VDecl->getLexicalDeclContext()->isRecord()) {
12853     // This is an in-class initialization for a static data member, e.g.,
12854     //
12855     // struct S {
12856     //   static const int value = 17;
12857     // };
12858 
12859     // C++ [class.mem]p4:
12860     //   A member-declarator can contain a constant-initializer only
12861     //   if it declares a static member (9.4) of const integral or
12862     //   const enumeration type, see 9.4.2.
12863     //
12864     // C++11 [class.static.data]p3:
12865     //   If a non-volatile non-inline const static data member is of integral
12866     //   or enumeration type, its declaration in the class definition can
12867     //   specify a brace-or-equal-initializer in which every initializer-clause
12868     //   that is an assignment-expression is a constant expression. A static
12869     //   data member of literal type can be declared in the class definition
12870     //   with the constexpr specifier; if so, its declaration shall specify a
12871     //   brace-or-equal-initializer in which every initializer-clause that is
12872     //   an assignment-expression is a constant expression.
12873 
12874     // Do nothing on dependent types.
12875     if (DclT->isDependentType()) {
12876 
12877     // Allow any 'static constexpr' members, whether or not they are of literal
12878     // type. We separately check that every constexpr variable is of literal
12879     // type.
12880     } else if (VDecl->isConstexpr()) {
12881 
12882     // Require constness.
12883     } else if (!DclT.isConstQualified()) {
12884       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12885         << Init->getSourceRange();
12886       VDecl->setInvalidDecl();
12887 
12888     // We allow integer constant expressions in all cases.
12889     } else if (DclT->isIntegralOrEnumerationType()) {
12890       // Check whether the expression is a constant expression.
12891       SourceLocation Loc;
12892       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12893         // In C++11, a non-constexpr const static data member with an
12894         // in-class initializer cannot be volatile.
12895         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12896       else if (Init->isValueDependent())
12897         ; // Nothing to check.
12898       else if (Init->isIntegerConstantExpr(Context, &Loc))
12899         ; // Ok, it's an ICE!
12900       else if (Init->getType()->isScopedEnumeralType() &&
12901                Init->isCXX11ConstantExpr(Context))
12902         ; // Ok, it is a scoped-enum constant expression.
12903       else if (Init->isEvaluatable(Context)) {
12904         // If we can constant fold the initializer through heroics, accept it,
12905         // but report this as a use of an extension for -pedantic.
12906         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12907           << Init->getSourceRange();
12908       } else {
12909         // Otherwise, this is some crazy unknown case.  Report the issue at the
12910         // location provided by the isIntegerConstantExpr failed check.
12911         Diag(Loc, diag::err_in_class_initializer_non_constant)
12912           << Init->getSourceRange();
12913         VDecl->setInvalidDecl();
12914       }
12915 
12916     // We allow foldable floating-point constants as an extension.
12917     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12918       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12919       // it anyway and provide a fixit to add the 'constexpr'.
12920       if (getLangOpts().CPlusPlus11) {
12921         Diag(VDecl->getLocation(),
12922              diag::ext_in_class_initializer_float_type_cxx11)
12923             << DclT << Init->getSourceRange();
12924         Diag(VDecl->getBeginLoc(),
12925              diag::note_in_class_initializer_float_type_cxx11)
12926             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12927       } else {
12928         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12929           << DclT << Init->getSourceRange();
12930 
12931         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12932           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12933             << Init->getSourceRange();
12934           VDecl->setInvalidDecl();
12935         }
12936       }
12937 
12938     // Suggest adding 'constexpr' in C++11 for literal types.
12939     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12940       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12941           << DclT << Init->getSourceRange()
12942           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12943       VDecl->setConstexpr(true);
12944 
12945     } else {
12946       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12947         << DclT << Init->getSourceRange();
12948       VDecl->setInvalidDecl();
12949     }
12950   } else if (VDecl->isFileVarDecl()) {
12951     // In C, extern is typically used to avoid tentative definitions when
12952     // declaring variables in headers, but adding an intializer makes it a
12953     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12954     // In C++, extern is often used to give implictly static const variables
12955     // external linkage, so don't warn in that case. If selectany is present,
12956     // this might be header code intended for C and C++ inclusion, so apply the
12957     // C++ rules.
12958     if (VDecl->getStorageClass() == SC_Extern &&
12959         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12960          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12961         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12962         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12963       Diag(VDecl->getLocation(), diag::warn_extern_init);
12964 
12965     // In Microsoft C++ mode, a const variable defined in namespace scope has
12966     // external linkage by default if the variable is declared with
12967     // __declspec(dllexport).
12968     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12969         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12970         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12971       VDecl->setStorageClass(SC_Extern);
12972 
12973     // C99 6.7.8p4. All file scoped initializers need to be constant.
12974     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12975       CheckForConstantInitializer(Init, DclT);
12976   }
12977 
12978   QualType InitType = Init->getType();
12979   if (!InitType.isNull() &&
12980       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12981        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12982     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12983 
12984   // We will represent direct-initialization similarly to copy-initialization:
12985   //    int x(1);  -as-> int x = 1;
12986   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12987   //
12988   // Clients that want to distinguish between the two forms, can check for
12989   // direct initializer using VarDecl::getInitStyle().
12990   // A major benefit is that clients that don't particularly care about which
12991   // exactly form was it (like the CodeGen) can handle both cases without
12992   // special case code.
12993 
12994   // C++ 8.5p11:
12995   // The form of initialization (using parentheses or '=') is generally
12996   // insignificant, but does matter when the entity being initialized has a
12997   // class type.
12998   if (CXXDirectInit) {
12999     assert(DirectInit && "Call-style initializer must be direct init.");
13000     VDecl->setInitStyle(VarDecl::CallInit);
13001   } else if (DirectInit) {
13002     // This must be list-initialization. No other way is direct-initialization.
13003     VDecl->setInitStyle(VarDecl::ListInit);
13004   }
13005 
13006   if (LangOpts.OpenMP &&
13007       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
13008       VDecl->isFileVarDecl())
13009     DeclsToCheckForDeferredDiags.insert(VDecl);
13010   CheckCompleteVariableDeclaration(VDecl);
13011 }
13012 
13013 /// ActOnInitializerError - Given that there was an error parsing an
13014 /// initializer for the given declaration, try to at least re-establish
13015 /// invariants such as whether a variable's type is either dependent or
13016 /// complete.
13017 void Sema::ActOnInitializerError(Decl *D) {
13018   // Our main concern here is re-establishing invariants like "a
13019   // variable's type is either dependent or complete".
13020   if (!D || D->isInvalidDecl()) return;
13021 
13022   VarDecl *VD = dyn_cast<VarDecl>(D);
13023   if (!VD) return;
13024 
13025   // Bindings are not usable if we can't make sense of the initializer.
13026   if (auto *DD = dyn_cast<DecompositionDecl>(D))
13027     for (auto *BD : DD->bindings())
13028       BD->setInvalidDecl();
13029 
13030   // Auto types are meaningless if we can't make sense of the initializer.
13031   if (VD->getType()->isUndeducedType()) {
13032     D->setInvalidDecl();
13033     return;
13034   }
13035 
13036   QualType Ty = VD->getType();
13037   if (Ty->isDependentType()) return;
13038 
13039   // Require a complete type.
13040   if (RequireCompleteType(VD->getLocation(),
13041                           Context.getBaseElementType(Ty),
13042                           diag::err_typecheck_decl_incomplete_type)) {
13043     VD->setInvalidDecl();
13044     return;
13045   }
13046 
13047   // Require a non-abstract type.
13048   if (RequireNonAbstractType(VD->getLocation(), Ty,
13049                              diag::err_abstract_type_in_decl,
13050                              AbstractVariableType)) {
13051     VD->setInvalidDecl();
13052     return;
13053   }
13054 
13055   // Don't bother complaining about constructors or destructors,
13056   // though.
13057 }
13058 
13059 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13060   // If there is no declaration, there was an error parsing it. Just ignore it.
13061   if (!RealDecl)
13062     return;
13063 
13064   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13065     QualType Type = Var->getType();
13066 
13067     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13068     if (isa<DecompositionDecl>(RealDecl)) {
13069       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13070       Var->setInvalidDecl();
13071       return;
13072     }
13073 
13074     if (Type->isUndeducedType() &&
13075         DeduceVariableDeclarationType(Var, false, nullptr))
13076       return;
13077 
13078     // C++11 [class.static.data]p3: A static data member can be declared with
13079     // the constexpr specifier; if so, its declaration shall specify
13080     // a brace-or-equal-initializer.
13081     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13082     // the definition of a variable [...] or the declaration of a static data
13083     // member.
13084     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13085         !Var->isThisDeclarationADemotedDefinition()) {
13086       if (Var->isStaticDataMember()) {
13087         // C++1z removes the relevant rule; the in-class declaration is always
13088         // a definition there.
13089         if (!getLangOpts().CPlusPlus17 &&
13090             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13091           Diag(Var->getLocation(),
13092                diag::err_constexpr_static_mem_var_requires_init)
13093               << Var;
13094           Var->setInvalidDecl();
13095           return;
13096         }
13097       } else {
13098         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13099         Var->setInvalidDecl();
13100         return;
13101       }
13102     }
13103 
13104     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13105     // be initialized.
13106     if (!Var->isInvalidDecl() &&
13107         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13108         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13109       bool HasConstExprDefaultConstructor = false;
13110       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13111         for (auto *Ctor : RD->ctors()) {
13112           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13113               Ctor->getMethodQualifiers().getAddressSpace() ==
13114                   LangAS::opencl_constant) {
13115             HasConstExprDefaultConstructor = true;
13116           }
13117         }
13118       }
13119       if (!HasConstExprDefaultConstructor) {
13120         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13121         Var->setInvalidDecl();
13122         return;
13123       }
13124     }
13125 
13126     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13127       if (Var->getStorageClass() == SC_Extern) {
13128         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13129             << Var;
13130         Var->setInvalidDecl();
13131         return;
13132       }
13133       if (RequireCompleteType(Var->getLocation(), Var->getType(),
13134                               diag::err_typecheck_decl_incomplete_type)) {
13135         Var->setInvalidDecl();
13136         return;
13137       }
13138       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13139         if (!RD->hasTrivialDefaultConstructor()) {
13140           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13141           Var->setInvalidDecl();
13142           return;
13143         }
13144       }
13145       // The declaration is unitialized, no need for further checks.
13146       return;
13147     }
13148 
13149     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13150     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13151         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13152       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13153                             NTCUC_DefaultInitializedObject, NTCUK_Init);
13154 
13155 
13156     switch (DefKind) {
13157     case VarDecl::Definition:
13158       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13159         break;
13160 
13161       // We have an out-of-line definition of a static data member
13162       // that has an in-class initializer, so we type-check this like
13163       // a declaration.
13164       //
13165       LLVM_FALLTHROUGH;
13166 
13167     case VarDecl::DeclarationOnly:
13168       // It's only a declaration.
13169 
13170       // Block scope. C99 6.7p7: If an identifier for an object is
13171       // declared with no linkage (C99 6.2.2p6), the type for the
13172       // object shall be complete.
13173       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13174           !Var->hasLinkage() && !Var->isInvalidDecl() &&
13175           RequireCompleteType(Var->getLocation(), Type,
13176                               diag::err_typecheck_decl_incomplete_type))
13177         Var->setInvalidDecl();
13178 
13179       // Make sure that the type is not abstract.
13180       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13181           RequireNonAbstractType(Var->getLocation(), Type,
13182                                  diag::err_abstract_type_in_decl,
13183                                  AbstractVariableType))
13184         Var->setInvalidDecl();
13185       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13186           Var->getStorageClass() == SC_PrivateExtern) {
13187         Diag(Var->getLocation(), diag::warn_private_extern);
13188         Diag(Var->getLocation(), diag::note_private_extern);
13189       }
13190 
13191       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13192           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13193         ExternalDeclarations.push_back(Var);
13194 
13195       return;
13196 
13197     case VarDecl::TentativeDefinition:
13198       // File scope. C99 6.9.2p2: A declaration of an identifier for an
13199       // object that has file scope without an initializer, and without a
13200       // storage-class specifier or with the storage-class specifier "static",
13201       // constitutes a tentative definition. Note: A tentative definition with
13202       // external linkage is valid (C99 6.2.2p5).
13203       if (!Var->isInvalidDecl()) {
13204         if (const IncompleteArrayType *ArrayT
13205                                     = Context.getAsIncompleteArrayType(Type)) {
13206           if (RequireCompleteSizedType(
13207                   Var->getLocation(), ArrayT->getElementType(),
13208                   diag::err_array_incomplete_or_sizeless_type))
13209             Var->setInvalidDecl();
13210         } else if (Var->getStorageClass() == SC_Static) {
13211           // C99 6.9.2p3: If the declaration of an identifier for an object is
13212           // a tentative definition and has internal linkage (C99 6.2.2p3), the
13213           // declared type shall not be an incomplete type.
13214           // NOTE: code such as the following
13215           //     static struct s;
13216           //     struct s { int a; };
13217           // is accepted by gcc. Hence here we issue a warning instead of
13218           // an error and we do not invalidate the static declaration.
13219           // NOTE: to avoid multiple warnings, only check the first declaration.
13220           if (Var->isFirstDecl())
13221             RequireCompleteType(Var->getLocation(), Type,
13222                                 diag::ext_typecheck_decl_incomplete_type);
13223         }
13224       }
13225 
13226       // Record the tentative definition; we're done.
13227       if (!Var->isInvalidDecl())
13228         TentativeDefinitions.push_back(Var);
13229       return;
13230     }
13231 
13232     // Provide a specific diagnostic for uninitialized variable
13233     // definitions with incomplete array type.
13234     if (Type->isIncompleteArrayType()) {
13235       Diag(Var->getLocation(),
13236            diag::err_typecheck_incomplete_array_needs_initializer);
13237       Var->setInvalidDecl();
13238       return;
13239     }
13240 
13241     // Provide a specific diagnostic for uninitialized variable
13242     // definitions with reference type.
13243     if (Type->isReferenceType()) {
13244       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13245           << Var << SourceRange(Var->getLocation(), Var->getLocation());
13246       return;
13247     }
13248 
13249     // Do not attempt to type-check the default initializer for a
13250     // variable with dependent type.
13251     if (Type->isDependentType())
13252       return;
13253 
13254     if (Var->isInvalidDecl())
13255       return;
13256 
13257     if (!Var->hasAttr<AliasAttr>()) {
13258       if (RequireCompleteType(Var->getLocation(),
13259                               Context.getBaseElementType(Type),
13260                               diag::err_typecheck_decl_incomplete_type)) {
13261         Var->setInvalidDecl();
13262         return;
13263       }
13264     } else {
13265       return;
13266     }
13267 
13268     // The variable can not have an abstract class type.
13269     if (RequireNonAbstractType(Var->getLocation(), Type,
13270                                diag::err_abstract_type_in_decl,
13271                                AbstractVariableType)) {
13272       Var->setInvalidDecl();
13273       return;
13274     }
13275 
13276     // Check for jumps past the implicit initializer.  C++0x
13277     // clarifies that this applies to a "variable with automatic
13278     // storage duration", not a "local variable".
13279     // C++11 [stmt.dcl]p3
13280     //   A program that jumps from a point where a variable with automatic
13281     //   storage duration is not in scope to a point where it is in scope is
13282     //   ill-formed unless the variable has scalar type, class type with a
13283     //   trivial default constructor and a trivial destructor, a cv-qualified
13284     //   version of one of these types, or an array of one of the preceding
13285     //   types and is declared without an initializer.
13286     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13287       if (const RecordType *Record
13288             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13289         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13290         // Mark the function (if we're in one) for further checking even if the
13291         // looser rules of C++11 do not require such checks, so that we can
13292         // diagnose incompatibilities with C++98.
13293         if (!CXXRecord->isPOD())
13294           setFunctionHasBranchProtectedScope();
13295       }
13296     }
13297     // In OpenCL, we can't initialize objects in the __local address space,
13298     // even implicitly, so don't synthesize an implicit initializer.
13299     if (getLangOpts().OpenCL &&
13300         Var->getType().getAddressSpace() == LangAS::opencl_local)
13301       return;
13302     // C++03 [dcl.init]p9:
13303     //   If no initializer is specified for an object, and the
13304     //   object is of (possibly cv-qualified) non-POD class type (or
13305     //   array thereof), the object shall be default-initialized; if
13306     //   the object is of const-qualified type, the underlying class
13307     //   type shall have a user-declared default
13308     //   constructor. Otherwise, if no initializer is specified for
13309     //   a non- static object, the object and its subobjects, if
13310     //   any, have an indeterminate initial value); if the object
13311     //   or any of its subobjects are of const-qualified type, the
13312     //   program is ill-formed.
13313     // C++0x [dcl.init]p11:
13314     //   If no initializer is specified for an object, the object is
13315     //   default-initialized; [...].
13316     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
13317     InitializationKind Kind
13318       = InitializationKind::CreateDefault(Var->getLocation());
13319 
13320     InitializationSequence InitSeq(*this, Entity, Kind, None);
13321     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13322 
13323     if (Init.get()) {
13324       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13325       // This is important for template substitution.
13326       Var->setInitStyle(VarDecl::CallInit);
13327     } else if (Init.isInvalid()) {
13328       // If default-init fails, attach a recovery-expr initializer to track
13329       // that initialization was attempted and failed.
13330       auto RecoveryExpr =
13331           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13332       if (RecoveryExpr.get())
13333         Var->setInit(RecoveryExpr.get());
13334     }
13335 
13336     CheckCompleteVariableDeclaration(Var);
13337   }
13338 }
13339 
13340 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13341   // If there is no declaration, there was an error parsing it. Ignore it.
13342   if (!D)
13343     return;
13344 
13345   VarDecl *VD = dyn_cast<VarDecl>(D);
13346   if (!VD) {
13347     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13348     D->setInvalidDecl();
13349     return;
13350   }
13351 
13352   VD->setCXXForRangeDecl(true);
13353 
13354   // for-range-declaration cannot be given a storage class specifier.
13355   int Error = -1;
13356   switch (VD->getStorageClass()) {
13357   case SC_None:
13358     break;
13359   case SC_Extern:
13360     Error = 0;
13361     break;
13362   case SC_Static:
13363     Error = 1;
13364     break;
13365   case SC_PrivateExtern:
13366     Error = 2;
13367     break;
13368   case SC_Auto:
13369     Error = 3;
13370     break;
13371   case SC_Register:
13372     Error = 4;
13373     break;
13374   }
13375 
13376   // for-range-declaration cannot be given a storage class specifier con't.
13377   switch (VD->getTSCSpec()) {
13378   case TSCS_thread_local:
13379     Error = 6;
13380     break;
13381   case TSCS___thread:
13382   case TSCS__Thread_local:
13383   case TSCS_unspecified:
13384     break;
13385   }
13386 
13387   if (Error != -1) {
13388     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13389         << VD << Error;
13390     D->setInvalidDecl();
13391   }
13392 }
13393 
13394 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13395                                             IdentifierInfo *Ident,
13396                                             ParsedAttributes &Attrs) {
13397   // C++1y [stmt.iter]p1:
13398   //   A range-based for statement of the form
13399   //      for ( for-range-identifier : for-range-initializer ) statement
13400   //   is equivalent to
13401   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13402   DeclSpec DS(Attrs.getPool().getFactory());
13403 
13404   const char *PrevSpec;
13405   unsigned DiagID;
13406   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13407                      getPrintingPolicy());
13408 
13409   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
13410   D.SetIdentifier(Ident, IdentLoc);
13411   D.takeAttributes(Attrs);
13412 
13413   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13414                 IdentLoc);
13415   Decl *Var = ActOnDeclarator(S, D);
13416   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13417   FinalizeDeclaration(Var);
13418   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13419                        Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13420                                                       : IdentLoc);
13421 }
13422 
13423 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13424   if (var->isInvalidDecl()) return;
13425 
13426   MaybeAddCUDAConstantAttr(var);
13427 
13428   if (getLangOpts().OpenCL) {
13429     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13430     // initialiser
13431     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13432         !var->hasInit()) {
13433       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13434           << 1 /*Init*/;
13435       var->setInvalidDecl();
13436       return;
13437     }
13438   }
13439 
13440   // In Objective-C, don't allow jumps past the implicit initialization of a
13441   // local retaining variable.
13442   if (getLangOpts().ObjC &&
13443       var->hasLocalStorage()) {
13444     switch (var->getType().getObjCLifetime()) {
13445     case Qualifiers::OCL_None:
13446     case Qualifiers::OCL_ExplicitNone:
13447     case Qualifiers::OCL_Autoreleasing:
13448       break;
13449 
13450     case Qualifiers::OCL_Weak:
13451     case Qualifiers::OCL_Strong:
13452       setFunctionHasBranchProtectedScope();
13453       break;
13454     }
13455   }
13456 
13457   if (var->hasLocalStorage() &&
13458       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13459     setFunctionHasBranchProtectedScope();
13460 
13461   // Warn about externally-visible variables being defined without a
13462   // prior declaration.  We only want to do this for global
13463   // declarations, but we also specifically need to avoid doing it for
13464   // class members because the linkage of an anonymous class can
13465   // change if it's later given a typedef name.
13466   if (var->isThisDeclarationADefinition() &&
13467       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13468       var->isExternallyVisible() && var->hasLinkage() &&
13469       !var->isInline() && !var->getDescribedVarTemplate() &&
13470       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13471       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13472       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13473                                   var->getLocation())) {
13474     // Find a previous declaration that's not a definition.
13475     VarDecl *prev = var->getPreviousDecl();
13476     while (prev && prev->isThisDeclarationADefinition())
13477       prev = prev->getPreviousDecl();
13478 
13479     if (!prev) {
13480       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13481       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13482           << /* variable */ 0;
13483     }
13484   }
13485 
13486   // Cache the result of checking for constant initialization.
13487   Optional<bool> CacheHasConstInit;
13488   const Expr *CacheCulprit = nullptr;
13489   auto checkConstInit = [&]() mutable {
13490     if (!CacheHasConstInit)
13491       CacheHasConstInit = var->getInit()->isConstantInitializer(
13492             Context, var->getType()->isReferenceType(), &CacheCulprit);
13493     return *CacheHasConstInit;
13494   };
13495 
13496   if (var->getTLSKind() == VarDecl::TLS_Static) {
13497     if (var->getType().isDestructedType()) {
13498       // GNU C++98 edits for __thread, [basic.start.term]p3:
13499       //   The type of an object with thread storage duration shall not
13500       //   have a non-trivial destructor.
13501       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13502       if (getLangOpts().CPlusPlus11)
13503         Diag(var->getLocation(), diag::note_use_thread_local);
13504     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13505       if (!checkConstInit()) {
13506         // GNU C++98 edits for __thread, [basic.start.init]p4:
13507         //   An object of thread storage duration shall not require dynamic
13508         //   initialization.
13509         // FIXME: Need strict checking here.
13510         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13511           << CacheCulprit->getSourceRange();
13512         if (getLangOpts().CPlusPlus11)
13513           Diag(var->getLocation(), diag::note_use_thread_local);
13514       }
13515     }
13516   }
13517 
13518 
13519   if (!var->getType()->isStructureType() && var->hasInit() &&
13520       isa<InitListExpr>(var->getInit())) {
13521     const auto *ILE = cast<InitListExpr>(var->getInit());
13522     unsigned NumInits = ILE->getNumInits();
13523     if (NumInits > 2)
13524       for (unsigned I = 0; I < NumInits; ++I) {
13525         const auto *Init = ILE->getInit(I);
13526         if (!Init)
13527           break;
13528         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13529         if (!SL)
13530           break;
13531 
13532         unsigned NumConcat = SL->getNumConcatenated();
13533         // Diagnose missing comma in string array initialization.
13534         // Do not warn when all the elements in the initializer are concatenated
13535         // together. Do not warn for macros too.
13536         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13537           bool OnlyOneMissingComma = true;
13538           for (unsigned J = I + 1; J < NumInits; ++J) {
13539             const auto *Init = ILE->getInit(J);
13540             if (!Init)
13541               break;
13542             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13543             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13544               OnlyOneMissingComma = false;
13545               break;
13546             }
13547           }
13548 
13549           if (OnlyOneMissingComma) {
13550             SmallVector<FixItHint, 1> Hints;
13551             for (unsigned i = 0; i < NumConcat - 1; ++i)
13552               Hints.push_back(FixItHint::CreateInsertion(
13553                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13554 
13555             Diag(SL->getStrTokenLoc(1),
13556                  diag::warn_concatenated_literal_array_init)
13557                 << Hints;
13558             Diag(SL->getBeginLoc(),
13559                  diag::note_concatenated_string_literal_silence);
13560           }
13561           // In any case, stop now.
13562           break;
13563         }
13564       }
13565   }
13566 
13567 
13568   QualType type = var->getType();
13569 
13570   if (var->hasAttr<BlocksAttr>())
13571     getCurFunction()->addByrefBlockVar(var);
13572 
13573   Expr *Init = var->getInit();
13574   bool GlobalStorage = var->hasGlobalStorage();
13575   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13576   QualType baseType = Context.getBaseElementType(type);
13577   bool HasConstInit = true;
13578 
13579   // Check whether the initializer is sufficiently constant.
13580   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13581       !Init->isValueDependent() &&
13582       (GlobalStorage || var->isConstexpr() ||
13583        var->mightBeUsableInConstantExpressions(Context))) {
13584     // If this variable might have a constant initializer or might be usable in
13585     // constant expressions, check whether or not it actually is now.  We can't
13586     // do this lazily, because the result might depend on things that change
13587     // later, such as which constexpr functions happen to be defined.
13588     SmallVector<PartialDiagnosticAt, 8> Notes;
13589     if (!getLangOpts().CPlusPlus11) {
13590       // Prior to C++11, in contexts where a constant initializer is required,
13591       // the set of valid constant initializers is described by syntactic rules
13592       // in [expr.const]p2-6.
13593       // FIXME: Stricter checking for these rules would be useful for constinit /
13594       // -Wglobal-constructors.
13595       HasConstInit = checkConstInit();
13596 
13597       // Compute and cache the constant value, and remember that we have a
13598       // constant initializer.
13599       if (HasConstInit) {
13600         (void)var->checkForConstantInitialization(Notes);
13601         Notes.clear();
13602       } else if (CacheCulprit) {
13603         Notes.emplace_back(CacheCulprit->getExprLoc(),
13604                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13605         Notes.back().second << CacheCulprit->getSourceRange();
13606       }
13607     } else {
13608       // Evaluate the initializer to see if it's a constant initializer.
13609       HasConstInit = var->checkForConstantInitialization(Notes);
13610     }
13611 
13612     if (HasConstInit) {
13613       // FIXME: Consider replacing the initializer with a ConstantExpr.
13614     } else if (var->isConstexpr()) {
13615       SourceLocation DiagLoc = var->getLocation();
13616       // If the note doesn't add any useful information other than a source
13617       // location, fold it into the primary diagnostic.
13618       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13619                                    diag::note_invalid_subexpr_in_const_expr) {
13620         DiagLoc = Notes[0].first;
13621         Notes.clear();
13622       }
13623       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13624           << var << Init->getSourceRange();
13625       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13626         Diag(Notes[I].first, Notes[I].second);
13627     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13628       auto *Attr = var->getAttr<ConstInitAttr>();
13629       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13630           << Init->getSourceRange();
13631       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13632           << Attr->getRange() << Attr->isConstinit();
13633       for (auto &it : Notes)
13634         Diag(it.first, it.second);
13635     } else if (IsGlobal &&
13636                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13637                                            var->getLocation())) {
13638       // Warn about globals which don't have a constant initializer.  Don't
13639       // warn about globals with a non-trivial destructor because we already
13640       // warned about them.
13641       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13642       if (!(RD && !RD->hasTrivialDestructor())) {
13643         // checkConstInit() here permits trivial default initialization even in
13644         // C++11 onwards, where such an initializer is not a constant initializer
13645         // but nonetheless doesn't require a global constructor.
13646         if (!checkConstInit())
13647           Diag(var->getLocation(), diag::warn_global_constructor)
13648               << Init->getSourceRange();
13649       }
13650     }
13651   }
13652 
13653   // Apply section attributes and pragmas to global variables.
13654   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13655       !inTemplateInstantiation()) {
13656     PragmaStack<StringLiteral *> *Stack = nullptr;
13657     int SectionFlags = ASTContext::PSF_Read;
13658     if (var->getType().isConstQualified()) {
13659       if (HasConstInit)
13660         Stack = &ConstSegStack;
13661       else {
13662         Stack = &BSSSegStack;
13663         SectionFlags |= ASTContext::PSF_Write;
13664       }
13665     } else if (var->hasInit() && HasConstInit) {
13666       Stack = &DataSegStack;
13667       SectionFlags |= ASTContext::PSF_Write;
13668     } else {
13669       Stack = &BSSSegStack;
13670       SectionFlags |= ASTContext::PSF_Write;
13671     }
13672     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13673       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13674         SectionFlags |= ASTContext::PSF_Implicit;
13675       UnifySection(SA->getName(), SectionFlags, var);
13676     } else if (Stack->CurrentValue) {
13677       SectionFlags |= ASTContext::PSF_Implicit;
13678       auto SectionName = Stack->CurrentValue->getString();
13679       var->addAttr(SectionAttr::CreateImplicit(
13680           Context, SectionName, Stack->CurrentPragmaLocation,
13681           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13682       if (UnifySection(SectionName, SectionFlags, var))
13683         var->dropAttr<SectionAttr>();
13684     }
13685 
13686     // Apply the init_seg attribute if this has an initializer.  If the
13687     // initializer turns out to not be dynamic, we'll end up ignoring this
13688     // attribute.
13689     if (CurInitSeg && var->getInit())
13690       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13691                                                CurInitSegLoc,
13692                                                AttributeCommonInfo::AS_Pragma));
13693   }
13694 
13695   // All the following checks are C++ only.
13696   if (!getLangOpts().CPlusPlus) {
13697     // If this variable must be emitted, add it as an initializer for the
13698     // current module.
13699     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13700       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13701     return;
13702   }
13703 
13704   // Require the destructor.
13705   if (!type->isDependentType())
13706     if (const RecordType *recordType = baseType->getAs<RecordType>())
13707       FinalizeVarWithDestructor(var, recordType);
13708 
13709   // If this variable must be emitted, add it as an initializer for the current
13710   // module.
13711   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13712     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13713 
13714   // Build the bindings if this is a structured binding declaration.
13715   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13716     CheckCompleteDecompositionDeclaration(DD);
13717 }
13718 
13719 /// Check if VD needs to be dllexport/dllimport due to being in a
13720 /// dllexport/import function.
13721 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13722   assert(VD->isStaticLocal());
13723 
13724   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13725 
13726   // Find outermost function when VD is in lambda function.
13727   while (FD && !getDLLAttr(FD) &&
13728          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13729          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13730     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13731   }
13732 
13733   if (!FD)
13734     return;
13735 
13736   // Static locals inherit dll attributes from their function.
13737   if (Attr *A = getDLLAttr(FD)) {
13738     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13739     NewAttr->setInherited(true);
13740     VD->addAttr(NewAttr);
13741   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13742     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13743     NewAttr->setInherited(true);
13744     VD->addAttr(NewAttr);
13745 
13746     // Export this function to enforce exporting this static variable even
13747     // if it is not used in this compilation unit.
13748     if (!FD->hasAttr<DLLExportAttr>())
13749       FD->addAttr(NewAttr);
13750 
13751   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13752     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13753     NewAttr->setInherited(true);
13754     VD->addAttr(NewAttr);
13755   }
13756 }
13757 
13758 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13759 /// any semantic actions necessary after any initializer has been attached.
13760 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13761   // Note that we are no longer parsing the initializer for this declaration.
13762   ParsingInitForAutoVars.erase(ThisDecl);
13763 
13764   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13765   if (!VD)
13766     return;
13767 
13768   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13769   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13770       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13771     if (PragmaClangBSSSection.Valid)
13772       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13773           Context, PragmaClangBSSSection.SectionName,
13774           PragmaClangBSSSection.PragmaLocation,
13775           AttributeCommonInfo::AS_Pragma));
13776     if (PragmaClangDataSection.Valid)
13777       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13778           Context, PragmaClangDataSection.SectionName,
13779           PragmaClangDataSection.PragmaLocation,
13780           AttributeCommonInfo::AS_Pragma));
13781     if (PragmaClangRodataSection.Valid)
13782       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13783           Context, PragmaClangRodataSection.SectionName,
13784           PragmaClangRodataSection.PragmaLocation,
13785           AttributeCommonInfo::AS_Pragma));
13786     if (PragmaClangRelroSection.Valid)
13787       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13788           Context, PragmaClangRelroSection.SectionName,
13789           PragmaClangRelroSection.PragmaLocation,
13790           AttributeCommonInfo::AS_Pragma));
13791   }
13792 
13793   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13794     for (auto *BD : DD->bindings()) {
13795       FinalizeDeclaration(BD);
13796     }
13797   }
13798 
13799   checkAttributesAfterMerging(*this, *VD);
13800 
13801   // Perform TLS alignment check here after attributes attached to the variable
13802   // which may affect the alignment have been processed. Only perform the check
13803   // if the target has a maximum TLS alignment (zero means no constraints).
13804   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13805     // Protect the check so that it's not performed on dependent types and
13806     // dependent alignments (we can't determine the alignment in that case).
13807     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13808       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13809       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13810         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13811           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13812           << (unsigned)MaxAlignChars.getQuantity();
13813       }
13814     }
13815   }
13816 
13817   if (VD->isStaticLocal())
13818     CheckStaticLocalForDllExport(VD);
13819 
13820   // Perform check for initializers of device-side global variables.
13821   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13822   // 7.5). We must also apply the same checks to all __shared__
13823   // variables whether they are local or not. CUDA also allows
13824   // constant initializers for __constant__ and __device__ variables.
13825   if (getLangOpts().CUDA)
13826     checkAllowedCUDAInitializer(VD);
13827 
13828   // Grab the dllimport or dllexport attribute off of the VarDecl.
13829   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13830 
13831   // Imported static data members cannot be defined out-of-line.
13832   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13833     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13834         VD->isThisDeclarationADefinition()) {
13835       // We allow definitions of dllimport class template static data members
13836       // with a warning.
13837       CXXRecordDecl *Context =
13838         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13839       bool IsClassTemplateMember =
13840           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13841           Context->getDescribedClassTemplate();
13842 
13843       Diag(VD->getLocation(),
13844            IsClassTemplateMember
13845                ? diag::warn_attribute_dllimport_static_field_definition
13846                : diag::err_attribute_dllimport_static_field_definition);
13847       Diag(IA->getLocation(), diag::note_attribute);
13848       if (!IsClassTemplateMember)
13849         VD->setInvalidDecl();
13850     }
13851   }
13852 
13853   // dllimport/dllexport variables cannot be thread local, their TLS index
13854   // isn't exported with the variable.
13855   if (DLLAttr && VD->getTLSKind()) {
13856     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13857     if (F && getDLLAttr(F)) {
13858       assert(VD->isStaticLocal());
13859       // But if this is a static local in a dlimport/dllexport function, the
13860       // function will never be inlined, which means the var would never be
13861       // imported, so having it marked import/export is safe.
13862     } else {
13863       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13864                                                                     << DLLAttr;
13865       VD->setInvalidDecl();
13866     }
13867   }
13868 
13869   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13870     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13871       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13872           << Attr;
13873       VD->dropAttr<UsedAttr>();
13874     }
13875   }
13876   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13877     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13878       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13879           << Attr;
13880       VD->dropAttr<RetainAttr>();
13881     }
13882   }
13883 
13884   const DeclContext *DC = VD->getDeclContext();
13885   // If there's a #pragma GCC visibility in scope, and this isn't a class
13886   // member, set the visibility of this variable.
13887   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13888     AddPushedVisibilityAttribute(VD);
13889 
13890   // FIXME: Warn on unused var template partial specializations.
13891   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13892     MarkUnusedFileScopedDecl(VD);
13893 
13894   // Now we have parsed the initializer and can update the table of magic
13895   // tag values.
13896   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13897       !VD->getType()->isIntegralOrEnumerationType())
13898     return;
13899 
13900   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13901     const Expr *MagicValueExpr = VD->getInit();
13902     if (!MagicValueExpr) {
13903       continue;
13904     }
13905     Optional<llvm::APSInt> MagicValueInt;
13906     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13907       Diag(I->getRange().getBegin(),
13908            diag::err_type_tag_for_datatype_not_ice)
13909         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13910       continue;
13911     }
13912     if (MagicValueInt->getActiveBits() > 64) {
13913       Diag(I->getRange().getBegin(),
13914            diag::err_type_tag_for_datatype_too_large)
13915         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13916       continue;
13917     }
13918     uint64_t MagicValue = MagicValueInt->getZExtValue();
13919     RegisterTypeTagForDatatype(I->getArgumentKind(),
13920                                MagicValue,
13921                                I->getMatchingCType(),
13922                                I->getLayoutCompatible(),
13923                                I->getMustBeNull());
13924   }
13925 }
13926 
13927 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13928   auto *VD = dyn_cast<VarDecl>(DD);
13929   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13930 }
13931 
13932 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13933                                                    ArrayRef<Decl *> Group) {
13934   SmallVector<Decl*, 8> Decls;
13935 
13936   if (DS.isTypeSpecOwned())
13937     Decls.push_back(DS.getRepAsDecl());
13938 
13939   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13940   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13941   bool DiagnosedMultipleDecomps = false;
13942   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13943   bool DiagnosedNonDeducedAuto = false;
13944 
13945   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13946     if (Decl *D = Group[i]) {
13947       // For declarators, there are some additional syntactic-ish checks we need
13948       // to perform.
13949       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13950         if (!FirstDeclaratorInGroup)
13951           FirstDeclaratorInGroup = DD;
13952         if (!FirstDecompDeclaratorInGroup)
13953           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13954         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13955             !hasDeducedAuto(DD))
13956           FirstNonDeducedAutoInGroup = DD;
13957 
13958         if (FirstDeclaratorInGroup != DD) {
13959           // A decomposition declaration cannot be combined with any other
13960           // declaration in the same group.
13961           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13962             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13963                  diag::err_decomp_decl_not_alone)
13964                 << FirstDeclaratorInGroup->getSourceRange()
13965                 << DD->getSourceRange();
13966             DiagnosedMultipleDecomps = true;
13967           }
13968 
13969           // A declarator that uses 'auto' in any way other than to declare a
13970           // variable with a deduced type cannot be combined with any other
13971           // declarator in the same group.
13972           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13973             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13974                  diag::err_auto_non_deduced_not_alone)
13975                 << FirstNonDeducedAutoInGroup->getType()
13976                        ->hasAutoForTrailingReturnType()
13977                 << FirstDeclaratorInGroup->getSourceRange()
13978                 << DD->getSourceRange();
13979             DiagnosedNonDeducedAuto = true;
13980           }
13981         }
13982       }
13983 
13984       Decls.push_back(D);
13985     }
13986   }
13987 
13988   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13989     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13990       handleTagNumbering(Tag, S);
13991       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13992           getLangOpts().CPlusPlus)
13993         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13994     }
13995   }
13996 
13997   return BuildDeclaratorGroup(Decls);
13998 }
13999 
14000 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14001 /// group, performing any necessary semantic checking.
14002 Sema::DeclGroupPtrTy
14003 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14004   // C++14 [dcl.spec.auto]p7: (DR1347)
14005   //   If the type that replaces the placeholder type is not the same in each
14006   //   deduction, the program is ill-formed.
14007   if (Group.size() > 1) {
14008     QualType Deduced;
14009     VarDecl *DeducedDecl = nullptr;
14010     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14011       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14012       if (!D || D->isInvalidDecl())
14013         break;
14014       DeducedType *DT = D->getType()->getContainedDeducedType();
14015       if (!DT || DT->getDeducedType().isNull())
14016         continue;
14017       if (Deduced.isNull()) {
14018         Deduced = DT->getDeducedType();
14019         DeducedDecl = D;
14020       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14021         auto *AT = dyn_cast<AutoType>(DT);
14022         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14023                         diag::err_auto_different_deductions)
14024                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14025                    << DeducedDecl->getDeclName() << DT->getDeducedType()
14026                    << D->getDeclName();
14027         if (DeducedDecl->hasInit())
14028           Dia << DeducedDecl->getInit()->getSourceRange();
14029         if (D->getInit())
14030           Dia << D->getInit()->getSourceRange();
14031         D->setInvalidDecl();
14032         break;
14033       }
14034     }
14035   }
14036 
14037   ActOnDocumentableDecls(Group);
14038 
14039   return DeclGroupPtrTy::make(
14040       DeclGroupRef::Create(Context, Group.data(), Group.size()));
14041 }
14042 
14043 void Sema::ActOnDocumentableDecl(Decl *D) {
14044   ActOnDocumentableDecls(D);
14045 }
14046 
14047 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14048   // Don't parse the comment if Doxygen diagnostics are ignored.
14049   if (Group.empty() || !Group[0])
14050     return;
14051 
14052   if (Diags.isIgnored(diag::warn_doc_param_not_found,
14053                       Group[0]->getLocation()) &&
14054       Diags.isIgnored(diag::warn_unknown_comment_command_name,
14055                       Group[0]->getLocation()))
14056     return;
14057 
14058   if (Group.size() >= 2) {
14059     // This is a decl group.  Normally it will contain only declarations
14060     // produced from declarator list.  But in case we have any definitions or
14061     // additional declaration references:
14062     //   'typedef struct S {} S;'
14063     //   'typedef struct S *S;'
14064     //   'struct S *pS;'
14065     // FinalizeDeclaratorGroup adds these as separate declarations.
14066     Decl *MaybeTagDecl = Group[0];
14067     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14068       Group = Group.slice(1);
14069     }
14070   }
14071 
14072   // FIMXE: We assume every Decl in the group is in the same file.
14073   // This is false when preprocessor constructs the group from decls in
14074   // different files (e. g. macros or #include).
14075   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14076 }
14077 
14078 /// Common checks for a parameter-declaration that should apply to both function
14079 /// parameters and non-type template parameters.
14080 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14081   // Check that there are no default arguments inside the type of this
14082   // parameter.
14083   if (getLangOpts().CPlusPlus)
14084     CheckExtraCXXDefaultArguments(D);
14085 
14086   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14087   if (D.getCXXScopeSpec().isSet()) {
14088     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14089       << D.getCXXScopeSpec().getRange();
14090   }
14091 
14092   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14093   // simple identifier except [...irrelevant cases...].
14094   switch (D.getName().getKind()) {
14095   case UnqualifiedIdKind::IK_Identifier:
14096     break;
14097 
14098   case UnqualifiedIdKind::IK_OperatorFunctionId:
14099   case UnqualifiedIdKind::IK_ConversionFunctionId:
14100   case UnqualifiedIdKind::IK_LiteralOperatorId:
14101   case UnqualifiedIdKind::IK_ConstructorName:
14102   case UnqualifiedIdKind::IK_DestructorName:
14103   case UnqualifiedIdKind::IK_ImplicitSelfParam:
14104   case UnqualifiedIdKind::IK_DeductionGuideName:
14105     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14106       << GetNameForDeclarator(D).getName();
14107     break;
14108 
14109   case UnqualifiedIdKind::IK_TemplateId:
14110   case UnqualifiedIdKind::IK_ConstructorTemplateId:
14111     // GetNameForDeclarator would not produce a useful name in this case.
14112     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14113     break;
14114   }
14115 }
14116 
14117 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14118 /// to introduce parameters into function prototype scope.
14119 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
14120   const DeclSpec &DS = D.getDeclSpec();
14121 
14122   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14123 
14124   // C++03 [dcl.stc]p2 also permits 'auto'.
14125   StorageClass SC = SC_None;
14126   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
14127     SC = SC_Register;
14128     // In C++11, the 'register' storage class specifier is deprecated.
14129     // In C++17, it is not allowed, but we tolerate it as an extension.
14130     if (getLangOpts().CPlusPlus11) {
14131       Diag(DS.getStorageClassSpecLoc(),
14132            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14133                                      : diag::warn_deprecated_register)
14134         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
14135     }
14136   } else if (getLangOpts().CPlusPlus &&
14137              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
14138     SC = SC_Auto;
14139   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
14140     Diag(DS.getStorageClassSpecLoc(),
14141          diag::err_invalid_storage_class_in_func_decl);
14142     D.getMutableDeclSpec().ClearStorageClassSpecs();
14143   }
14144 
14145   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
14146     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14147       << DeclSpec::getSpecifierName(TSCS);
14148   if (DS.isInlineSpecified())
14149     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14150         << getLangOpts().CPlusPlus17;
14151   if (DS.hasConstexprSpecifier())
14152     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14153         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14154 
14155   DiagnoseFunctionSpecifiers(DS);
14156 
14157   CheckFunctionOrTemplateParamDeclarator(S, D);
14158 
14159   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14160   QualType parmDeclType = TInfo->getType();
14161 
14162   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14163   IdentifierInfo *II = D.getIdentifier();
14164   if (II) {
14165     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14166                    ForVisibleRedeclaration);
14167     LookupName(R, S);
14168     if (R.isSingleResult()) {
14169       NamedDecl *PrevDecl = R.getFoundDecl();
14170       if (PrevDecl->isTemplateParameter()) {
14171         // Maybe we will complain about the shadowed template parameter.
14172         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14173         // Just pretend that we didn't see the previous declaration.
14174         PrevDecl = nullptr;
14175       } else if (S->isDeclScope(PrevDecl)) {
14176         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14177         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14178 
14179         // Recover by removing the name
14180         II = nullptr;
14181         D.SetIdentifier(nullptr, D.getIdentifierLoc());
14182         D.setInvalidType(true);
14183       }
14184     }
14185   }
14186 
14187   // Temporarily put parameter variables in the translation unit, not
14188   // the enclosing context.  This prevents them from accidentally
14189   // looking like class members in C++.
14190   ParmVarDecl *New =
14191       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14192                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14193 
14194   if (D.isInvalidType())
14195     New->setInvalidDecl();
14196 
14197   assert(S->isFunctionPrototypeScope());
14198   assert(S->getFunctionPrototypeDepth() >= 1);
14199   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14200                     S->getNextFunctionPrototypeIndex());
14201 
14202   // Add the parameter declaration into this scope.
14203   S->AddDecl(New);
14204   if (II)
14205     IdResolver.AddDecl(New);
14206 
14207   ProcessDeclAttributes(S, New, D);
14208 
14209   if (D.getDeclSpec().isModulePrivateSpecified())
14210     Diag(New->getLocation(), diag::err_module_private_local)
14211         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14212         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14213 
14214   if (New->hasAttr<BlocksAttr>()) {
14215     Diag(New->getLocation(), diag::err_block_on_nonlocal);
14216   }
14217 
14218   if (getLangOpts().OpenCL)
14219     deduceOpenCLAddressSpace(New);
14220 
14221   return New;
14222 }
14223 
14224 /// Synthesizes a variable for a parameter arising from a
14225 /// typedef.
14226 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
14227                                               SourceLocation Loc,
14228                                               QualType T) {
14229   /* FIXME: setting StartLoc == Loc.
14230      Would it be worth to modify callers so as to provide proper source
14231      location for the unnamed parameters, embedding the parameter's type? */
14232   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14233                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
14234                                            SC_None, nullptr);
14235   Param->setImplicit();
14236   return Param;
14237 }
14238 
14239 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
14240   // Don't diagnose unused-parameter errors in template instantiations; we
14241   // will already have done so in the template itself.
14242   if (inTemplateInstantiation())
14243     return;
14244 
14245   for (const ParmVarDecl *Parameter : Parameters) {
14246     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14247         !Parameter->hasAttr<UnusedAttr>()) {
14248       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14249         << Parameter->getDeclName();
14250     }
14251   }
14252 }
14253 
14254 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14255     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14256   if (LangOpts.NumLargeByValueCopy == 0) // No check.
14257     return;
14258 
14259   // Warn if the return value is pass-by-value and larger than the specified
14260   // threshold.
14261   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14262     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14263     if (Size > LangOpts.NumLargeByValueCopy)
14264       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14265   }
14266 
14267   // Warn if any parameter is pass-by-value and larger than the specified
14268   // threshold.
14269   for (const ParmVarDecl *Parameter : Parameters) {
14270     QualType T = Parameter->getType();
14271     if (T->isDependentType() || !T.isPODType(Context))
14272       continue;
14273     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14274     if (Size > LangOpts.NumLargeByValueCopy)
14275       Diag(Parameter->getLocation(), diag::warn_parameter_size)
14276           << Parameter << Size;
14277   }
14278 }
14279 
14280 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
14281                                   SourceLocation NameLoc, IdentifierInfo *Name,
14282                                   QualType T, TypeSourceInfo *TSInfo,
14283                                   StorageClass SC) {
14284   // In ARC, infer a lifetime qualifier for appropriate parameter types.
14285   if (getLangOpts().ObjCAutoRefCount &&
14286       T.getObjCLifetime() == Qualifiers::OCL_None &&
14287       T->isObjCLifetimeType()) {
14288 
14289     Qualifiers::ObjCLifetime lifetime;
14290 
14291     // Special cases for arrays:
14292     //   - if it's const, use __unsafe_unretained
14293     //   - otherwise, it's an error
14294     if (T->isArrayType()) {
14295       if (!T.isConstQualified()) {
14296         if (DelayedDiagnostics.shouldDelayDiagnostics())
14297           DelayedDiagnostics.add(
14298               sema::DelayedDiagnostic::makeForbiddenType(
14299               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14300         else
14301           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14302               << TSInfo->getTypeLoc().getSourceRange();
14303       }
14304       lifetime = Qualifiers::OCL_ExplicitNone;
14305     } else {
14306       lifetime = T->getObjCARCImplicitLifetime();
14307     }
14308     T = Context.getLifetimeQualifiedType(T, lifetime);
14309   }
14310 
14311   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14312                                          Context.getAdjustedParameterType(T),
14313                                          TSInfo, SC, nullptr);
14314 
14315   // Make a note if we created a new pack in the scope of a lambda, so that
14316   // we know that references to that pack must also be expanded within the
14317   // lambda scope.
14318   if (New->isParameterPack())
14319     if (auto *LSI = getEnclosingLambda())
14320       LSI->LocalPacks.push_back(New);
14321 
14322   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14323       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
14324     checkNonTrivialCUnion(New->getType(), New->getLocation(),
14325                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14326 
14327   // Parameters can not be abstract class types.
14328   // For record types, this is done by the AbstractClassUsageDiagnoser once
14329   // the class has been completely parsed.
14330   if (!CurContext->isRecord() &&
14331       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14332                              AbstractParamType))
14333     New->setInvalidDecl();
14334 
14335   // Parameter declarators cannot be interface types. All ObjC objects are
14336   // passed by reference.
14337   if (T->isObjCObjectType()) {
14338     SourceLocation TypeEndLoc =
14339         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14340     Diag(NameLoc,
14341          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14342       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14343     T = Context.getObjCObjectPointerType(T);
14344     New->setType(T);
14345   }
14346 
14347   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14348   // duration shall not be qualified by an address-space qualifier."
14349   // Since all parameters have automatic store duration, they can not have
14350   // an address space.
14351   if (T.getAddressSpace() != LangAS::Default &&
14352       // OpenCL allows function arguments declared to be an array of a type
14353       // to be qualified with an address space.
14354       !(getLangOpts().OpenCL &&
14355         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14356     Diag(NameLoc, diag::err_arg_with_address_space);
14357     New->setInvalidDecl();
14358   }
14359 
14360   // PPC MMA non-pointer types are not allowed as function argument types.
14361   if (Context.getTargetInfo().getTriple().isPPC64() &&
14362       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14363     New->setInvalidDecl();
14364   }
14365 
14366   return New;
14367 }
14368 
14369 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14370                                            SourceLocation LocAfterDecls) {
14371   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14372 
14373   // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14374   // in the declaration list shall have at least one declarator, those
14375   // declarators shall only declare identifiers from the identifier list, and
14376   // every identifier in the identifier list shall be declared.
14377   //
14378   // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14379   // identifiers it names shall be declared in the declaration list."
14380   //
14381   // This is why we only diagnose in C99 and later. Note, the other conditions
14382   // listed are checked elsewhere.
14383   if (!FTI.hasPrototype) {
14384     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14385       --i;
14386       if (FTI.Params[i].Param == nullptr) {
14387         if (getLangOpts().C99) {
14388           SmallString<256> Code;
14389           llvm::raw_svector_ostream(Code)
14390               << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14391           Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14392               << FTI.Params[i].Ident
14393               << FixItHint::CreateInsertion(LocAfterDecls, Code);
14394         }
14395 
14396         // Implicitly declare the argument as type 'int' for lack of a better
14397         // type.
14398         AttributeFactory attrs;
14399         DeclSpec DS(attrs);
14400         const char* PrevSpec; // unused
14401         unsigned DiagID; // unused
14402         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14403                            DiagID, Context.getPrintingPolicy());
14404         // Use the identifier location for the type source range.
14405         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14406         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14407         Declarator ParamD(DS, ParsedAttributesView::none(),
14408                           DeclaratorContext::KNRTypeList);
14409         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14410         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14411       }
14412     }
14413   }
14414 }
14415 
14416 Decl *
14417 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14418                               MultiTemplateParamsArg TemplateParameterLists,
14419                               SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
14420   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14421   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14422   Scope *ParentScope = FnBodyScope->getParent();
14423 
14424   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14425   // we define a non-templated function definition, we will create a declaration
14426   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14427   // The base function declaration will have the equivalent of an `omp declare
14428   // variant` annotation which specifies the mangled definition as a
14429   // specialization function under the OpenMP context defined as part of the
14430   // `omp begin declare variant`.
14431   SmallVector<FunctionDecl *, 4> Bases;
14432   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14433     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14434         ParentScope, D, TemplateParameterLists, Bases);
14435 
14436   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14437   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14438   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
14439 
14440   if (!Bases.empty())
14441     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14442 
14443   return Dcl;
14444 }
14445 
14446 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14447   Consumer.HandleInlineFunctionDefinition(D);
14448 }
14449 
14450 static bool
14451 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14452                                 const FunctionDecl *&PossiblePrototype) {
14453   // Don't warn about invalid declarations.
14454   if (FD->isInvalidDecl())
14455     return false;
14456 
14457   // Or declarations that aren't global.
14458   if (!FD->isGlobal())
14459     return false;
14460 
14461   // Don't warn about C++ member functions.
14462   if (isa<CXXMethodDecl>(FD))
14463     return false;
14464 
14465   // Don't warn about 'main'.
14466   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14467     if (IdentifierInfo *II = FD->getIdentifier())
14468       if (II->isStr("main") || II->isStr("efi_main"))
14469         return false;
14470 
14471   // Don't warn about inline functions.
14472   if (FD->isInlined())
14473     return false;
14474 
14475   // Don't warn about function templates.
14476   if (FD->getDescribedFunctionTemplate())
14477     return false;
14478 
14479   // Don't warn about function template specializations.
14480   if (FD->isFunctionTemplateSpecialization())
14481     return false;
14482 
14483   // Don't warn for OpenCL kernels.
14484   if (FD->hasAttr<OpenCLKernelAttr>())
14485     return false;
14486 
14487   // Don't warn on explicitly deleted functions.
14488   if (FD->isDeleted())
14489     return false;
14490 
14491   // Don't warn on implicitly local functions (such as having local-typed
14492   // parameters).
14493   if (!FD->isExternallyVisible())
14494     return false;
14495 
14496   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14497        Prev; Prev = Prev->getPreviousDecl()) {
14498     // Ignore any declarations that occur in function or method
14499     // scope, because they aren't visible from the header.
14500     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14501       continue;
14502 
14503     PossiblePrototype = Prev;
14504     return Prev->getType()->isFunctionNoProtoType();
14505   }
14506 
14507   return true;
14508 }
14509 
14510 void
14511 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14512                                    const FunctionDecl *EffectiveDefinition,
14513                                    SkipBodyInfo *SkipBody) {
14514   const FunctionDecl *Definition = EffectiveDefinition;
14515   if (!Definition &&
14516       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14517     return;
14518 
14519   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14520     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14521       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14522         // A merged copy of the same function, instantiated as a member of
14523         // the same class, is OK.
14524         if (declaresSameEntity(OrigFD, OrigDef) &&
14525             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14526                                cast<Decl>(FD->getLexicalDeclContext())))
14527           return;
14528       }
14529     }
14530   }
14531 
14532   if (canRedefineFunction(Definition, getLangOpts()))
14533     return;
14534 
14535   // Don't emit an error when this is redefinition of a typo-corrected
14536   // definition.
14537   if (TypoCorrectedFunctionDefinitions.count(Definition))
14538     return;
14539 
14540   // If we don't have a visible definition of the function, and it's inline or
14541   // a template, skip the new definition.
14542   if (SkipBody && !hasVisibleDefinition(Definition) &&
14543       (Definition->getFormalLinkage() == InternalLinkage ||
14544        Definition->isInlined() ||
14545        Definition->getDescribedFunctionTemplate() ||
14546        Definition->getNumTemplateParameterLists())) {
14547     SkipBody->ShouldSkip = true;
14548     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14549     if (auto *TD = Definition->getDescribedFunctionTemplate())
14550       makeMergedDefinitionVisible(TD);
14551     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14552     return;
14553   }
14554 
14555   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14556       Definition->getStorageClass() == SC_Extern)
14557     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14558         << FD << getLangOpts().CPlusPlus;
14559   else
14560     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14561 
14562   Diag(Definition->getLocation(), diag::note_previous_definition);
14563   FD->setInvalidDecl();
14564 }
14565 
14566 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14567                                    Sema &S) {
14568   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14569 
14570   LambdaScopeInfo *LSI = S.PushLambdaScope();
14571   LSI->CallOperator = CallOperator;
14572   LSI->Lambda = LambdaClass;
14573   LSI->ReturnType = CallOperator->getReturnType();
14574   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14575 
14576   if (LCD == LCD_None)
14577     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14578   else if (LCD == LCD_ByCopy)
14579     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14580   else if (LCD == LCD_ByRef)
14581     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14582   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14583 
14584   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14585   LSI->Mutable = !CallOperator->isConst();
14586 
14587   // Add the captures to the LSI so they can be noted as already
14588   // captured within tryCaptureVar.
14589   auto I = LambdaClass->field_begin();
14590   for (const auto &C : LambdaClass->captures()) {
14591     if (C.capturesVariable()) {
14592       VarDecl *VD = C.getCapturedVar();
14593       if (VD->isInitCapture())
14594         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14595       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14596       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14597           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14598           /*EllipsisLoc*/C.isPackExpansion()
14599                          ? C.getEllipsisLoc() : SourceLocation(),
14600           I->getType(), /*Invalid*/false);
14601 
14602     } else if (C.capturesThis()) {
14603       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14604                           C.getCaptureKind() == LCK_StarThis);
14605     } else {
14606       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14607                              I->getType());
14608     }
14609     ++I;
14610   }
14611 }
14612 
14613 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14614                                     SkipBodyInfo *SkipBody,
14615                                     FnBodyKind BodyKind) {
14616   if (!D) {
14617     // Parsing the function declaration failed in some way. Push on a fake scope
14618     // anyway so we can try to parse the function body.
14619     PushFunctionScope();
14620     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14621     return D;
14622   }
14623 
14624   FunctionDecl *FD = nullptr;
14625 
14626   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14627     FD = FunTmpl->getTemplatedDecl();
14628   else
14629     FD = cast<FunctionDecl>(D);
14630 
14631   // Do not push if it is a lambda because one is already pushed when building
14632   // the lambda in ActOnStartOfLambdaDefinition().
14633   if (!isLambdaCallOperator(FD))
14634     PushExpressionEvaluationContext(
14635         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14636                           : ExprEvalContexts.back().Context);
14637 
14638   // Check for defining attributes before the check for redefinition.
14639   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14640     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14641     FD->dropAttr<AliasAttr>();
14642     FD->setInvalidDecl();
14643   }
14644   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14645     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14646     FD->dropAttr<IFuncAttr>();
14647     FD->setInvalidDecl();
14648   }
14649 
14650   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14651     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14652         Ctor->isDefaultConstructor() &&
14653         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14654       // If this is an MS ABI dllexport default constructor, instantiate any
14655       // default arguments.
14656       InstantiateDefaultCtorDefaultArgs(Ctor);
14657     }
14658   }
14659 
14660   // See if this is a redefinition. If 'will have body' (or similar) is already
14661   // set, then these checks were already performed when it was set.
14662   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14663       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14664     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14665 
14666     // If we're skipping the body, we're done. Don't enter the scope.
14667     if (SkipBody && SkipBody->ShouldSkip)
14668       return D;
14669   }
14670 
14671   // Mark this function as "will have a body eventually".  This lets users to
14672   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14673   // this function.
14674   FD->setWillHaveBody();
14675 
14676   // If we are instantiating a generic lambda call operator, push
14677   // a LambdaScopeInfo onto the function stack.  But use the information
14678   // that's already been calculated (ActOnLambdaExpr) to prime the current
14679   // LambdaScopeInfo.
14680   // When the template operator is being specialized, the LambdaScopeInfo,
14681   // has to be properly restored so that tryCaptureVariable doesn't try
14682   // and capture any new variables. In addition when calculating potential
14683   // captures during transformation of nested lambdas, it is necessary to
14684   // have the LSI properly restored.
14685   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14686     assert(inTemplateInstantiation() &&
14687            "There should be an active template instantiation on the stack "
14688            "when instantiating a generic lambda!");
14689     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14690   } else {
14691     // Enter a new function scope
14692     PushFunctionScope();
14693   }
14694 
14695   // Builtin functions cannot be defined.
14696   if (unsigned BuiltinID = FD->getBuiltinID()) {
14697     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14698         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14699       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14700       FD->setInvalidDecl();
14701     }
14702   }
14703 
14704   // The return type of a function definition must be complete (C99 6.9.1p3),
14705   // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
14706   QualType ResultType = FD->getReturnType();
14707   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14708       !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
14709       RequireCompleteType(FD->getLocation(), ResultType,
14710                           diag::err_func_def_incomplete_result))
14711     FD->setInvalidDecl();
14712 
14713   if (FnBodyScope)
14714     PushDeclContext(FnBodyScope, FD);
14715 
14716   // Check the validity of our function parameters
14717   if (BodyKind != FnBodyKind::Delete)
14718     CheckParmsForFunctionDef(FD->parameters(),
14719                              /*CheckParameterNames=*/true);
14720 
14721   // Add non-parameter declarations already in the function to the current
14722   // scope.
14723   if (FnBodyScope) {
14724     for (Decl *NPD : FD->decls()) {
14725       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14726       if (!NonParmDecl)
14727         continue;
14728       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14729              "parameters should not be in newly created FD yet");
14730 
14731       // If the decl has a name, make it accessible in the current scope.
14732       if (NonParmDecl->getDeclName())
14733         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14734 
14735       // Similarly, dive into enums and fish their constants out, making them
14736       // accessible in this scope.
14737       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14738         for (auto *EI : ED->enumerators())
14739           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14740       }
14741     }
14742   }
14743 
14744   // Introduce our parameters into the function scope
14745   for (auto Param : FD->parameters()) {
14746     Param->setOwningFunction(FD);
14747 
14748     // If this has an identifier, add it to the scope stack.
14749     if (Param->getIdentifier() && FnBodyScope) {
14750       CheckShadow(FnBodyScope, Param);
14751 
14752       PushOnScopeChains(Param, FnBodyScope);
14753     }
14754   }
14755 
14756   // Ensure that the function's exception specification is instantiated.
14757   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14758     ResolveExceptionSpec(D->getLocation(), FPT);
14759 
14760   // dllimport cannot be applied to non-inline function definitions.
14761   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14762       !FD->isTemplateInstantiation()) {
14763     assert(!FD->hasAttr<DLLExportAttr>());
14764     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14765     FD->setInvalidDecl();
14766     return D;
14767   }
14768   // We want to attach documentation to original Decl (which might be
14769   // a function template).
14770   ActOnDocumentableDecl(D);
14771   if (getCurLexicalContext()->isObjCContainer() &&
14772       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14773       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14774     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14775 
14776   return D;
14777 }
14778 
14779 /// Given the set of return statements within a function body,
14780 /// compute the variables that are subject to the named return value
14781 /// optimization.
14782 ///
14783 /// Each of the variables that is subject to the named return value
14784 /// optimization will be marked as NRVO variables in the AST, and any
14785 /// return statement that has a marked NRVO variable as its NRVO candidate can
14786 /// use the named return value optimization.
14787 ///
14788 /// This function applies a very simplistic algorithm for NRVO: if every return
14789 /// statement in the scope of a variable has the same NRVO candidate, that
14790 /// candidate is an NRVO variable.
14791 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14792   ReturnStmt **Returns = Scope->Returns.data();
14793 
14794   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14795     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14796       if (!NRVOCandidate->isNRVOVariable())
14797         Returns[I]->setNRVOCandidate(nullptr);
14798     }
14799   }
14800 }
14801 
14802 bool Sema::canDelayFunctionBody(const Declarator &D) {
14803   // We can't delay parsing the body of a constexpr function template (yet).
14804   if (D.getDeclSpec().hasConstexprSpecifier())
14805     return false;
14806 
14807   // We can't delay parsing the body of a function template with a deduced
14808   // return type (yet).
14809   if (D.getDeclSpec().hasAutoTypeSpec()) {
14810     // If the placeholder introduces a non-deduced trailing return type,
14811     // we can still delay parsing it.
14812     if (D.getNumTypeObjects()) {
14813       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14814       if (Outer.Kind == DeclaratorChunk::Function &&
14815           Outer.Fun.hasTrailingReturnType()) {
14816         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14817         return Ty.isNull() || !Ty->isUndeducedType();
14818       }
14819     }
14820     return false;
14821   }
14822 
14823   return true;
14824 }
14825 
14826 bool Sema::canSkipFunctionBody(Decl *D) {
14827   // We cannot skip the body of a function (or function template) which is
14828   // constexpr, since we may need to evaluate its body in order to parse the
14829   // rest of the file.
14830   // We cannot skip the body of a function with an undeduced return type,
14831   // because any callers of that function need to know the type.
14832   if (const FunctionDecl *FD = D->getAsFunction()) {
14833     if (FD->isConstexpr())
14834       return false;
14835     // We can't simply call Type::isUndeducedType here, because inside template
14836     // auto can be deduced to a dependent type, which is not considered
14837     // "undeduced".
14838     if (FD->getReturnType()->getContainedDeducedType())
14839       return false;
14840   }
14841   return Consumer.shouldSkipFunctionBody(D);
14842 }
14843 
14844 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14845   if (!Decl)
14846     return nullptr;
14847   if (FunctionDecl *FD = Decl->getAsFunction())
14848     FD->setHasSkippedBody();
14849   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14850     MD->setHasSkippedBody();
14851   return Decl;
14852 }
14853 
14854 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14855   return ActOnFinishFunctionBody(D, BodyArg, false);
14856 }
14857 
14858 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14859 /// body.
14860 class ExitFunctionBodyRAII {
14861 public:
14862   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14863   ~ExitFunctionBodyRAII() {
14864     if (!IsLambda)
14865       S.PopExpressionEvaluationContext();
14866   }
14867 
14868 private:
14869   Sema &S;
14870   bool IsLambda = false;
14871 };
14872 
14873 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14874   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14875 
14876   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14877     if (EscapeInfo.count(BD))
14878       return EscapeInfo[BD];
14879 
14880     bool R = false;
14881     const BlockDecl *CurBD = BD;
14882 
14883     do {
14884       R = !CurBD->doesNotEscape();
14885       if (R)
14886         break;
14887       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14888     } while (CurBD);
14889 
14890     return EscapeInfo[BD] = R;
14891   };
14892 
14893   // If the location where 'self' is implicitly retained is inside a escaping
14894   // block, emit a diagnostic.
14895   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14896        S.ImplicitlyRetainedSelfLocs)
14897     if (IsOrNestedInEscapingBlock(P.second))
14898       S.Diag(P.first, diag::warn_implicitly_retains_self)
14899           << FixItHint::CreateInsertion(P.first, "self->");
14900 }
14901 
14902 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14903                                     bool IsInstantiation) {
14904   FunctionScopeInfo *FSI = getCurFunction();
14905   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14906 
14907   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14908     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14909 
14910   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14911   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14912 
14913   if (getLangOpts().Coroutines && FSI->isCoroutine())
14914     CheckCompletedCoroutineBody(FD, Body);
14915 
14916   {
14917     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14918     // one is already popped when finishing the lambda in BuildLambdaExpr().
14919     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14920     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14921 
14922     if (FD) {
14923       FD->setBody(Body);
14924       FD->setWillHaveBody(false);
14925 
14926       if (getLangOpts().CPlusPlus14) {
14927         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14928             FD->getReturnType()->isUndeducedType()) {
14929           // For a function with a deduced result type to return void,
14930           // the result type as written must be 'auto' or 'decltype(auto)',
14931           // possibly cv-qualified or constrained, but not ref-qualified.
14932           if (!FD->getReturnType()->getAs<AutoType>()) {
14933             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14934                 << FD->getReturnType();
14935             FD->setInvalidDecl();
14936           } else {
14937             // Falling off the end of the function is the same as 'return;'.
14938             Expr *Dummy = nullptr;
14939             if (DeduceFunctionTypeFromReturnExpr(
14940                     FD, dcl->getLocation(), Dummy,
14941                     FD->getReturnType()->getAs<AutoType>()))
14942               FD->setInvalidDecl();
14943           }
14944         }
14945       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14946         // In C++11, we don't use 'auto' deduction rules for lambda call
14947         // operators because we don't support return type deduction.
14948         auto *LSI = getCurLambda();
14949         if (LSI->HasImplicitReturnType) {
14950           deduceClosureReturnType(*LSI);
14951 
14952           // C++11 [expr.prim.lambda]p4:
14953           //   [...] if there are no return statements in the compound-statement
14954           //   [the deduced type is] the type void
14955           QualType RetType =
14956               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14957 
14958           // Update the return type to the deduced type.
14959           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14960           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14961                                               Proto->getExtProtoInfo()));
14962         }
14963       }
14964 
14965       // If the function implicitly returns zero (like 'main') or is naked,
14966       // don't complain about missing return statements.
14967       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14968         WP.disableCheckFallThrough();
14969 
14970       // MSVC permits the use of pure specifier (=0) on function definition,
14971       // defined at class scope, warn about this non-standard construct.
14972       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14973         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14974 
14975       if (!FD->isInvalidDecl()) {
14976         // Don't diagnose unused parameters of defaulted, deleted or naked
14977         // functions.
14978         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14979             !FD->hasAttr<NakedAttr>())
14980           DiagnoseUnusedParameters(FD->parameters());
14981         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14982                                                FD->getReturnType(), FD);
14983 
14984         // If this is a structor, we need a vtable.
14985         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14986           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14987         else if (CXXDestructorDecl *Destructor =
14988                      dyn_cast<CXXDestructorDecl>(FD))
14989           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14990 
14991         // Try to apply the named return value optimization. We have to check
14992         // if we can do this here because lambdas keep return statements around
14993         // to deduce an implicit return type.
14994         if (FD->getReturnType()->isRecordType() &&
14995             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14996           computeNRVO(Body, FSI);
14997       }
14998 
14999       // GNU warning -Wmissing-prototypes:
15000       //   Warn if a global function is defined without a previous
15001       //   prototype declaration. This warning is issued even if the
15002       //   definition itself provides a prototype. The aim is to detect
15003       //   global functions that fail to be declared in header files.
15004       const FunctionDecl *PossiblePrototype = nullptr;
15005       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15006         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15007 
15008         if (PossiblePrototype) {
15009           // We found a declaration that is not a prototype,
15010           // but that could be a zero-parameter prototype
15011           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15012             TypeLoc TL = TI->getTypeLoc();
15013             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15014               Diag(PossiblePrototype->getLocation(),
15015                    diag::note_declaration_not_a_prototype)
15016                   << (FD->getNumParams() != 0)
15017                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15018                                                     FTL.getRParenLoc(), "void")
15019                                               : FixItHint{});
15020           }
15021         } else {
15022           // Returns true if the token beginning at this Loc is `const`.
15023           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15024                                   const LangOptions &LangOpts) {
15025             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15026             if (LocInfo.first.isInvalid())
15027               return false;
15028 
15029             bool Invalid = false;
15030             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15031             if (Invalid)
15032               return false;
15033 
15034             if (LocInfo.second > Buffer.size())
15035               return false;
15036 
15037             const char *LexStart = Buffer.data() + LocInfo.second;
15038             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15039 
15040             return StartTok.consume_front("const") &&
15041                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
15042                     StartTok.startswith("/*") || StartTok.startswith("//"));
15043           };
15044 
15045           auto findBeginLoc = [&]() {
15046             // If the return type has `const` qualifier, we want to insert
15047             // `static` before `const` (and not before the typename).
15048             if ((FD->getReturnType()->isAnyPointerType() &&
15049                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
15050                 FD->getReturnType().isConstQualified()) {
15051               // But only do this if we can determine where the `const` is.
15052 
15053               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15054                                getLangOpts()))
15055 
15056                 return FD->getBeginLoc();
15057             }
15058             return FD->getTypeSpecStartLoc();
15059           };
15060           Diag(FD->getTypeSpecStartLoc(),
15061                diag::note_static_for_internal_linkage)
15062               << /* function */ 1
15063               << (FD->getStorageClass() == SC_None
15064                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15065                       : FixItHint{});
15066         }
15067       }
15068 
15069       // If the function being defined does not have a prototype, then we may
15070       // need to diagnose it as changing behavior in C2x because we now know
15071       // whether the function accepts arguments or not. This only handles the
15072       // case where the definition has no prototype but does have parameters
15073       // and either there is no previous potential prototype, or the previous
15074       // potential prototype also has no actual prototype. This handles cases
15075       // like:
15076       //   void f(); void f(a) int a; {}
15077       //   void g(a) int a; {}
15078       // See MergeFunctionDecl() for other cases of the behavior change
15079       // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15080       // type without a prototype.
15081       if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15082           (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15083                                   !PossiblePrototype->isImplicit()))) {
15084         // The function definition has parameters, so this will change behavior
15085         // in C2x. If there is a possible prototype, it comes before the
15086         // function definition.
15087         // FIXME: The declaration may have already been diagnosed as being
15088         // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15089         // there's no way to test for the "changes behavior" condition in
15090         // SemaType.cpp when forming the declaration's function type. So, we do
15091         // this awkward dance instead.
15092         //
15093         // If we have a possible prototype and it declares a function with a
15094         // prototype, we don't want to diagnose it; if we have a possible
15095         // prototype and it has no prototype, it may have already been
15096         // diagnosed in SemaType.cpp as deprecated depending on whether
15097         // -Wstrict-prototypes is enabled. If we already warned about it being
15098         // deprecated, add a note that it also changes behavior. If we didn't
15099         // warn about it being deprecated (because the diagnostic is not
15100         // enabled), warn now that it is deprecated and changes behavior.
15101 
15102         // This K&R C function definition definitely changes behavior in C2x,
15103         // so diagnose it.
15104         Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15105             << /*definition*/ 1 << /* not supported in C2x */ 0;
15106 
15107         // If we have a possible prototype for the function which is a user-
15108         // visible declaration, we already tested that it has no prototype.
15109         // This will change behavior in C2x. This gets a warning rather than a
15110         // note because it's the same behavior-changing problem as with the
15111         // definition.
15112         if (PossiblePrototype)
15113           Diag(PossiblePrototype->getLocation(),
15114                diag::warn_non_prototype_changes_behavior)
15115               << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15116               << /*definition*/ 1;
15117       }
15118 
15119       // Warn on CPUDispatch with an actual body.
15120       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15121         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15122           if (!CmpndBody->body_empty())
15123             Diag(CmpndBody->body_front()->getBeginLoc(),
15124                  diag::warn_dispatch_body_ignored);
15125 
15126       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15127         const CXXMethodDecl *KeyFunction;
15128         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15129             MD->isVirtual() &&
15130             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15131             MD == KeyFunction->getCanonicalDecl()) {
15132           // Update the key-function state if necessary for this ABI.
15133           if (FD->isInlined() &&
15134               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15135             Context.setNonKeyFunction(MD);
15136 
15137             // If the newly-chosen key function is already defined, then we
15138             // need to mark the vtable as used retroactively.
15139             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15140             const FunctionDecl *Definition;
15141             if (KeyFunction && KeyFunction->isDefined(Definition))
15142               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15143           } else {
15144             // We just defined they key function; mark the vtable as used.
15145             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15146           }
15147         }
15148       }
15149 
15150       assert(
15151           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15152           "Function parsing confused");
15153     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15154       assert(MD == getCurMethodDecl() && "Method parsing confused");
15155       MD->setBody(Body);
15156       if (!MD->isInvalidDecl()) {
15157         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
15158                                                MD->getReturnType(), MD);
15159 
15160         if (Body)
15161           computeNRVO(Body, FSI);
15162       }
15163       if (FSI->ObjCShouldCallSuper) {
15164         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15165             << MD->getSelector().getAsString();
15166         FSI->ObjCShouldCallSuper = false;
15167       }
15168       if (FSI->ObjCWarnForNoDesignatedInitChain) {
15169         const ObjCMethodDecl *InitMethod = nullptr;
15170         bool isDesignated =
15171             MD->isDesignatedInitializerForTheInterface(&InitMethod);
15172         assert(isDesignated && InitMethod);
15173         (void)isDesignated;
15174 
15175         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15176           auto IFace = MD->getClassInterface();
15177           if (!IFace)
15178             return false;
15179           auto SuperD = IFace->getSuperClass();
15180           if (!SuperD)
15181             return false;
15182           return SuperD->getIdentifier() ==
15183                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15184         };
15185         // Don't issue this warning for unavailable inits or direct subclasses
15186         // of NSObject.
15187         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15188           Diag(MD->getLocation(),
15189                diag::warn_objc_designated_init_missing_super_call);
15190           Diag(InitMethod->getLocation(),
15191                diag::note_objc_designated_init_marked_here);
15192         }
15193         FSI->ObjCWarnForNoDesignatedInitChain = false;
15194       }
15195       if (FSI->ObjCWarnForNoInitDelegation) {
15196         // Don't issue this warning for unavaialable inits.
15197         if (!MD->isUnavailable())
15198           Diag(MD->getLocation(),
15199                diag::warn_objc_secondary_init_missing_init_call);
15200         FSI->ObjCWarnForNoInitDelegation = false;
15201       }
15202 
15203       diagnoseImplicitlyRetainedSelf(*this);
15204     } else {
15205       // Parsing the function declaration failed in some way. Pop the fake scope
15206       // we pushed on.
15207       PopFunctionScopeInfo(ActivePolicy, dcl);
15208       return nullptr;
15209     }
15210 
15211     if (Body && FSI->HasPotentialAvailabilityViolations)
15212       DiagnoseUnguardedAvailabilityViolations(dcl);
15213 
15214     assert(!FSI->ObjCShouldCallSuper &&
15215            "This should only be set for ObjC methods, which should have been "
15216            "handled in the block above.");
15217 
15218     // Verify and clean out per-function state.
15219     if (Body && (!FD || !FD->isDefaulted())) {
15220       // C++ constructors that have function-try-blocks can't have return
15221       // statements in the handlers of that block. (C++ [except.handle]p14)
15222       // Verify this.
15223       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15224         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15225 
15226       // Verify that gotos and switch cases don't jump into scopes illegally.
15227       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15228         DiagnoseInvalidJumps(Body);
15229 
15230       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15231         if (!Destructor->getParent()->isDependentType())
15232           CheckDestructor(Destructor);
15233 
15234         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15235                                                Destructor->getParent());
15236       }
15237 
15238       // If any errors have occurred, clear out any temporaries that may have
15239       // been leftover. This ensures that these temporaries won't be picked up
15240       // for deletion in some later function.
15241       if (hasUncompilableErrorOccurred() ||
15242           getDiagnostics().getSuppressAllDiagnostics()) {
15243         DiscardCleanupsInEvaluationContext();
15244       }
15245       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15246         // Since the body is valid, issue any analysis-based warnings that are
15247         // enabled.
15248         ActivePolicy = &WP;
15249       }
15250 
15251       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15252           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15253         FD->setInvalidDecl();
15254 
15255       if (FD && FD->hasAttr<NakedAttr>()) {
15256         for (const Stmt *S : Body->children()) {
15257           // Allow local register variables without initializer as they don't
15258           // require prologue.
15259           bool RegisterVariables = false;
15260           if (auto *DS = dyn_cast<DeclStmt>(S)) {
15261             for (const auto *Decl : DS->decls()) {
15262               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15263                 RegisterVariables =
15264                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15265                 if (!RegisterVariables)
15266                   break;
15267               }
15268             }
15269           }
15270           if (RegisterVariables)
15271             continue;
15272           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15273             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15274             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15275             FD->setInvalidDecl();
15276             break;
15277           }
15278         }
15279       }
15280 
15281       assert(ExprCleanupObjects.size() ==
15282                  ExprEvalContexts.back().NumCleanupObjects &&
15283              "Leftover temporaries in function");
15284       assert(!Cleanup.exprNeedsCleanups() &&
15285              "Unaccounted cleanups in function");
15286       assert(MaybeODRUseExprs.empty() &&
15287              "Leftover expressions for odr-use checking");
15288     }
15289   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15290     // the declaration context below. Otherwise, we're unable to transform
15291     // 'this' expressions when transforming immediate context functions.
15292 
15293   if (!IsInstantiation)
15294     PopDeclContext();
15295 
15296   PopFunctionScopeInfo(ActivePolicy, dcl);
15297   // If any errors have occurred, clear out any temporaries that may have
15298   // been leftover. This ensures that these temporaries won't be picked up for
15299   // deletion in some later function.
15300   if (hasUncompilableErrorOccurred()) {
15301     DiscardCleanupsInEvaluationContext();
15302   }
15303 
15304   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15305                                   !LangOpts.OMPTargetTriples.empty())) ||
15306              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15307     auto ES = getEmissionStatus(FD);
15308     if (ES == Sema::FunctionEmissionStatus::Emitted ||
15309         ES == Sema::FunctionEmissionStatus::Unknown)
15310       DeclsToCheckForDeferredDiags.insert(FD);
15311   }
15312 
15313   if (FD && !FD->isDeleted())
15314     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15315 
15316   return dcl;
15317 }
15318 
15319 /// When we finish delayed parsing of an attribute, we must attach it to the
15320 /// relevant Decl.
15321 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
15322                                        ParsedAttributes &Attrs) {
15323   // Always attach attributes to the underlying decl.
15324   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15325     D = TD->getTemplatedDecl();
15326   ProcessDeclAttributeList(S, D, Attrs);
15327 
15328   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15329     if (Method->isStatic())
15330       checkThisInStaticMemberFunctionAttributes(Method);
15331 }
15332 
15333 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15334 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15335 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
15336                                           IdentifierInfo &II, Scope *S) {
15337   // It is not valid to implicitly define a function in C2x.
15338   assert(LangOpts.implicitFunctionsAllowed() &&
15339          "Implicit function declarations aren't allowed in this language mode");
15340 
15341   // Find the scope in which the identifier is injected and the corresponding
15342   // DeclContext.
15343   // FIXME: C89 does not say what happens if there is no enclosing block scope.
15344   // In that case, we inject the declaration into the translation unit scope
15345   // instead.
15346   Scope *BlockScope = S;
15347   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15348     BlockScope = BlockScope->getParent();
15349 
15350   Scope *ContextScope = BlockScope;
15351   while (!ContextScope->getEntity())
15352     ContextScope = ContextScope->getParent();
15353   ContextRAII SavedContext(*this, ContextScope->getEntity());
15354 
15355   // Before we produce a declaration for an implicitly defined
15356   // function, see whether there was a locally-scoped declaration of
15357   // this name as a function or variable. If so, use that
15358   // (non-visible) declaration, and complain about it.
15359   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15360   if (ExternCPrev) {
15361     // We still need to inject the function into the enclosing block scope so
15362     // that later (non-call) uses can see it.
15363     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15364 
15365     // C89 footnote 38:
15366     //   If in fact it is not defined as having type "function returning int",
15367     //   the behavior is undefined.
15368     if (!isa<FunctionDecl>(ExternCPrev) ||
15369         !Context.typesAreCompatible(
15370             cast<FunctionDecl>(ExternCPrev)->getType(),
15371             Context.getFunctionNoProtoType(Context.IntTy))) {
15372       Diag(Loc, diag::ext_use_out_of_scope_declaration)
15373           << ExternCPrev << !getLangOpts().C99;
15374       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15375       return ExternCPrev;
15376     }
15377   }
15378 
15379   // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15380   unsigned diag_id;
15381   if (II.getName().startswith("__builtin_"))
15382     diag_id = diag::warn_builtin_unknown;
15383   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15384   else if (getLangOpts().C99)
15385     diag_id = diag::ext_implicit_function_decl_c99;
15386   else
15387     diag_id = diag::warn_implicit_function_decl;
15388 
15389   TypoCorrection Corrected;
15390   // Because typo correction is expensive, only do it if the implicit
15391   // function declaration is going to be treated as an error.
15392   //
15393   // Perform the corection before issuing the main diagnostic, as some consumers
15394   // use typo-correction callbacks to enhance the main diagnostic.
15395   if (S && !ExternCPrev &&
15396       (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15397     DeclFilterCCC<FunctionDecl> CCC{};
15398     Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15399                             S, nullptr, CCC, CTK_NonError);
15400   }
15401 
15402   Diag(Loc, diag_id) << &II;
15403   if (Corrected) {
15404     // If the correction is going to suggest an implicitly defined function,
15405     // skip the correction as not being a particularly good idea.
15406     bool Diagnose = true;
15407     if (const auto *D = Corrected.getCorrectionDecl())
15408       Diagnose = !D->isImplicit();
15409     if (Diagnose)
15410       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15411                    /*ErrorRecovery*/ false);
15412   }
15413 
15414   // If we found a prior declaration of this function, don't bother building
15415   // another one. We've already pushed that one into scope, so there's nothing
15416   // more to do.
15417   if (ExternCPrev)
15418     return ExternCPrev;
15419 
15420   // Set a Declarator for the implicit definition: int foo();
15421   const char *Dummy;
15422   AttributeFactory attrFactory;
15423   DeclSpec DS(attrFactory);
15424   unsigned DiagID;
15425   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15426                                   Context.getPrintingPolicy());
15427   (void)Error; // Silence warning.
15428   assert(!Error && "Error setting up implicit decl!");
15429   SourceLocation NoLoc;
15430   Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
15431   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15432                                              /*IsAmbiguous=*/false,
15433                                              /*LParenLoc=*/NoLoc,
15434                                              /*Params=*/nullptr,
15435                                              /*NumParams=*/0,
15436                                              /*EllipsisLoc=*/NoLoc,
15437                                              /*RParenLoc=*/NoLoc,
15438                                              /*RefQualifierIsLvalueRef=*/true,
15439                                              /*RefQualifierLoc=*/NoLoc,
15440                                              /*MutableLoc=*/NoLoc, EST_None,
15441                                              /*ESpecRange=*/SourceRange(),
15442                                              /*Exceptions=*/nullptr,
15443                                              /*ExceptionRanges=*/nullptr,
15444                                              /*NumExceptions=*/0,
15445                                              /*NoexceptExpr=*/nullptr,
15446                                              /*ExceptionSpecTokens=*/nullptr,
15447                                              /*DeclsInPrototype=*/None, Loc,
15448                                              Loc, D),
15449                 std::move(DS.getAttributes()), SourceLocation());
15450   D.SetIdentifier(&II, Loc);
15451 
15452   // Insert this function into the enclosing block scope.
15453   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15454   FD->setImplicit();
15455 
15456   AddKnownFunctionAttributes(FD);
15457 
15458   return FD;
15459 }
15460 
15461 /// If this function is a C++ replaceable global allocation function
15462 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15463 /// adds any function attributes that we know a priori based on the standard.
15464 ///
15465 /// We need to check for duplicate attributes both here and where user-written
15466 /// attributes are applied to declarations.
15467 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15468     FunctionDecl *FD) {
15469   if (FD->isInvalidDecl())
15470     return;
15471 
15472   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15473       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15474     return;
15475 
15476   Optional<unsigned> AlignmentParam;
15477   bool IsNothrow = false;
15478   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15479     return;
15480 
15481   // C++2a [basic.stc.dynamic.allocation]p4:
15482   //   An allocation function that has a non-throwing exception specification
15483   //   indicates failure by returning a null pointer value. Any other allocation
15484   //   function never returns a null pointer value and indicates failure only by
15485   //   throwing an exception [...]
15486   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15487     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15488 
15489   // C++2a [basic.stc.dynamic.allocation]p2:
15490   //   An allocation function attempts to allocate the requested amount of
15491   //   storage. [...] If the request succeeds, the value returned by a
15492   //   replaceable allocation function is a [...] pointer value p0 different
15493   //   from any previously returned value p1 [...]
15494   //
15495   // However, this particular information is being added in codegen,
15496   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15497 
15498   // C++2a [basic.stc.dynamic.allocation]p2:
15499   //   An allocation function attempts to allocate the requested amount of
15500   //   storage. If it is successful, it returns the address of the start of a
15501   //   block of storage whose length in bytes is at least as large as the
15502   //   requested size.
15503   if (!FD->hasAttr<AllocSizeAttr>()) {
15504     FD->addAttr(AllocSizeAttr::CreateImplicit(
15505         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15506         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15507   }
15508 
15509   // C++2a [basic.stc.dynamic.allocation]p3:
15510   //   For an allocation function [...], the pointer returned on a successful
15511   //   call shall represent the address of storage that is aligned as follows:
15512   //   (3.1) If the allocation function takes an argument of type
15513   //         std​::​align_­val_­t, the storage will have the alignment
15514   //         specified by the value of this argument.
15515   if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
15516     FD->addAttr(AllocAlignAttr::CreateImplicit(
15517         Context, ParamIdx(AlignmentParam.value(), FD), FD->getLocation()));
15518   }
15519 
15520   // FIXME:
15521   // C++2a [basic.stc.dynamic.allocation]p3:
15522   //   For an allocation function [...], the pointer returned on a successful
15523   //   call shall represent the address of storage that is aligned as follows:
15524   //   (3.2) Otherwise, if the allocation function is named operator new[],
15525   //         the storage is aligned for any object that does not have
15526   //         new-extended alignment ([basic.align]) and is no larger than the
15527   //         requested size.
15528   //   (3.3) Otherwise, the storage is aligned for any object that does not
15529   //         have new-extended alignment and is of the requested size.
15530 }
15531 
15532 /// Adds any function attributes that we know a priori based on
15533 /// the declaration of this function.
15534 ///
15535 /// These attributes can apply both to implicitly-declared builtins
15536 /// (like __builtin___printf_chk) or to library-declared functions
15537 /// like NSLog or printf.
15538 ///
15539 /// We need to check for duplicate attributes both here and where user-written
15540 /// attributes are applied to declarations.
15541 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15542   if (FD->isInvalidDecl())
15543     return;
15544 
15545   // If this is a built-in function, map its builtin attributes to
15546   // actual attributes.
15547   if (unsigned BuiltinID = FD->getBuiltinID()) {
15548     // Handle printf-formatting attributes.
15549     unsigned FormatIdx;
15550     bool HasVAListArg;
15551     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15552       if (!FD->hasAttr<FormatAttr>()) {
15553         const char *fmt = "printf";
15554         unsigned int NumParams = FD->getNumParams();
15555         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15556             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15557           fmt = "NSString";
15558         FD->addAttr(FormatAttr::CreateImplicit(Context,
15559                                                &Context.Idents.get(fmt),
15560                                                FormatIdx+1,
15561                                                HasVAListArg ? 0 : FormatIdx+2,
15562                                                FD->getLocation()));
15563       }
15564     }
15565     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15566                                              HasVAListArg)) {
15567      if (!FD->hasAttr<FormatAttr>())
15568        FD->addAttr(FormatAttr::CreateImplicit(Context,
15569                                               &Context.Idents.get("scanf"),
15570                                               FormatIdx+1,
15571                                               HasVAListArg ? 0 : FormatIdx+2,
15572                                               FD->getLocation()));
15573     }
15574 
15575     // Handle automatically recognized callbacks.
15576     SmallVector<int, 4> Encoding;
15577     if (!FD->hasAttr<CallbackAttr>() &&
15578         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15579       FD->addAttr(CallbackAttr::CreateImplicit(
15580           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15581 
15582     // Mark const if we don't care about errno and that is the only thing
15583     // preventing the function from being const. This allows IRgen to use LLVM
15584     // intrinsics for such functions.
15585     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15586         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15587       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15588 
15589     // We make "fma" on GNU or Windows const because we know it does not set
15590     // errno in those environments even though it could set errno based on the
15591     // C standard.
15592     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15593     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15594         !FD->hasAttr<ConstAttr>()) {
15595       switch (BuiltinID) {
15596       case Builtin::BI__builtin_fma:
15597       case Builtin::BI__builtin_fmaf:
15598       case Builtin::BI__builtin_fmal:
15599       case Builtin::BIfma:
15600       case Builtin::BIfmaf:
15601       case Builtin::BIfmal:
15602         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15603         break;
15604       default:
15605         break;
15606       }
15607     }
15608 
15609     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15610         !FD->hasAttr<ReturnsTwiceAttr>())
15611       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15612                                          FD->getLocation()));
15613     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15614       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15615     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15616       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15617     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15618       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15619     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15620         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15621       // Add the appropriate attribute, depending on the CUDA compilation mode
15622       // and which target the builtin belongs to. For example, during host
15623       // compilation, aux builtins are __device__, while the rest are __host__.
15624       if (getLangOpts().CUDAIsDevice !=
15625           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15626         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15627       else
15628         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15629     }
15630 
15631     // Add known guaranteed alignment for allocation functions.
15632     switch (BuiltinID) {
15633     case Builtin::BImemalign:
15634     case Builtin::BIaligned_alloc:
15635       if (!FD->hasAttr<AllocAlignAttr>())
15636         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15637                                                    FD->getLocation()));
15638       break;
15639     default:
15640       break;
15641     }
15642 
15643     // Add allocsize attribute for allocation functions.
15644     switch (BuiltinID) {
15645     case Builtin::BIcalloc:
15646       FD->addAttr(AllocSizeAttr::CreateImplicit(
15647           Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15648       break;
15649     case Builtin::BImemalign:
15650     case Builtin::BIaligned_alloc:
15651     case Builtin::BIrealloc:
15652       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15653                                                 ParamIdx(), FD->getLocation()));
15654       break;
15655     case Builtin::BImalloc:
15656       FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15657                                                 ParamIdx(), FD->getLocation()));
15658       break;
15659     default:
15660       break;
15661     }
15662   }
15663 
15664   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15665 
15666   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15667   // throw, add an implicit nothrow attribute to any extern "C" function we come
15668   // across.
15669   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15670       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15671     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15672     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15673       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15674   }
15675 
15676   IdentifierInfo *Name = FD->getIdentifier();
15677   if (!Name)
15678     return;
15679   if ((!getLangOpts().CPlusPlus &&
15680        FD->getDeclContext()->isTranslationUnit()) ||
15681       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15682        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15683        LinkageSpecDecl::lang_c)) {
15684     // Okay: this could be a libc/libm/Objective-C function we know
15685     // about.
15686   } else
15687     return;
15688 
15689   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15690     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15691     // target-specific builtins, perhaps?
15692     if (!FD->hasAttr<FormatAttr>())
15693       FD->addAttr(FormatAttr::CreateImplicit(Context,
15694                                              &Context.Idents.get("printf"), 2,
15695                                              Name->isStr("vasprintf") ? 0 : 3,
15696                                              FD->getLocation()));
15697   }
15698 
15699   if (Name->isStr("__CFStringMakeConstantString")) {
15700     // We already have a __builtin___CFStringMakeConstantString,
15701     // but builds that use -fno-constant-cfstrings don't go through that.
15702     if (!FD->hasAttr<FormatArgAttr>())
15703       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15704                                                 FD->getLocation()));
15705   }
15706 }
15707 
15708 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15709                                     TypeSourceInfo *TInfo) {
15710   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15711   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15712 
15713   if (!TInfo) {
15714     assert(D.isInvalidType() && "no declarator info for valid type");
15715     TInfo = Context.getTrivialTypeSourceInfo(T);
15716   }
15717 
15718   // Scope manipulation handled by caller.
15719   TypedefDecl *NewTD =
15720       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15721                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15722 
15723   // Bail out immediately if we have an invalid declaration.
15724   if (D.isInvalidType()) {
15725     NewTD->setInvalidDecl();
15726     return NewTD;
15727   }
15728 
15729   if (D.getDeclSpec().isModulePrivateSpecified()) {
15730     if (CurContext->isFunctionOrMethod())
15731       Diag(NewTD->getLocation(), diag::err_module_private_local)
15732           << 2 << NewTD
15733           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15734           << FixItHint::CreateRemoval(
15735                  D.getDeclSpec().getModulePrivateSpecLoc());
15736     else
15737       NewTD->setModulePrivate();
15738   }
15739 
15740   // C++ [dcl.typedef]p8:
15741   //   If the typedef declaration defines an unnamed class (or
15742   //   enum), the first typedef-name declared by the declaration
15743   //   to be that class type (or enum type) is used to denote the
15744   //   class type (or enum type) for linkage purposes only.
15745   // We need to check whether the type was declared in the declaration.
15746   switch (D.getDeclSpec().getTypeSpecType()) {
15747   case TST_enum:
15748   case TST_struct:
15749   case TST_interface:
15750   case TST_union:
15751   case TST_class: {
15752     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15753     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15754     break;
15755   }
15756 
15757   default:
15758     break;
15759   }
15760 
15761   return NewTD;
15762 }
15763 
15764 /// Check that this is a valid underlying type for an enum declaration.
15765 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15766   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15767   QualType T = TI->getType();
15768 
15769   if (T->isDependentType())
15770     return false;
15771 
15772   // This doesn't use 'isIntegralType' despite the error message mentioning
15773   // integral type because isIntegralType would also allow enum types in C.
15774   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15775     if (BT->isInteger())
15776       return false;
15777 
15778   if (T->isBitIntType())
15779     return false;
15780 
15781   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15782 }
15783 
15784 /// Check whether this is a valid redeclaration of a previous enumeration.
15785 /// \return true if the redeclaration was invalid.
15786 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15787                                   QualType EnumUnderlyingTy, bool IsFixed,
15788                                   const EnumDecl *Prev) {
15789   if (IsScoped != Prev->isScoped()) {
15790     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15791       << Prev->isScoped();
15792     Diag(Prev->getLocation(), diag::note_previous_declaration);
15793     return true;
15794   }
15795 
15796   if (IsFixed && Prev->isFixed()) {
15797     if (!EnumUnderlyingTy->isDependentType() &&
15798         !Prev->getIntegerType()->isDependentType() &&
15799         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15800                                         Prev->getIntegerType())) {
15801       // TODO: Highlight the underlying type of the redeclaration.
15802       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15803         << EnumUnderlyingTy << Prev->getIntegerType();
15804       Diag(Prev->getLocation(), diag::note_previous_declaration)
15805           << Prev->getIntegerTypeRange();
15806       return true;
15807     }
15808   } else if (IsFixed != Prev->isFixed()) {
15809     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15810       << Prev->isFixed();
15811     Diag(Prev->getLocation(), diag::note_previous_declaration);
15812     return true;
15813   }
15814 
15815   return false;
15816 }
15817 
15818 /// Get diagnostic %select index for tag kind for
15819 /// redeclaration diagnostic message.
15820 /// WARNING: Indexes apply to particular diagnostics only!
15821 ///
15822 /// \returns diagnostic %select index.
15823 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15824   switch (Tag) {
15825   case TTK_Struct: return 0;
15826   case TTK_Interface: return 1;
15827   case TTK_Class:  return 2;
15828   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15829   }
15830 }
15831 
15832 /// Determine if tag kind is a class-key compatible with
15833 /// class for redeclaration (class, struct, or __interface).
15834 ///
15835 /// \returns true iff the tag kind is compatible.
15836 static bool isClassCompatTagKind(TagTypeKind Tag)
15837 {
15838   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15839 }
15840 
15841 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15842                                              TagTypeKind TTK) {
15843   if (isa<TypedefDecl>(PrevDecl))
15844     return NTK_Typedef;
15845   else if (isa<TypeAliasDecl>(PrevDecl))
15846     return NTK_TypeAlias;
15847   else if (isa<ClassTemplateDecl>(PrevDecl))
15848     return NTK_Template;
15849   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15850     return NTK_TypeAliasTemplate;
15851   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15852     return NTK_TemplateTemplateArgument;
15853   switch (TTK) {
15854   case TTK_Struct:
15855   case TTK_Interface:
15856   case TTK_Class:
15857     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15858   case TTK_Union:
15859     return NTK_NonUnion;
15860   case TTK_Enum:
15861     return NTK_NonEnum;
15862   }
15863   llvm_unreachable("invalid TTK");
15864 }
15865 
15866 /// Determine whether a tag with a given kind is acceptable
15867 /// as a redeclaration of the given tag declaration.
15868 ///
15869 /// \returns true if the new tag kind is acceptable, false otherwise.
15870 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15871                                         TagTypeKind NewTag, bool isDefinition,
15872                                         SourceLocation NewTagLoc,
15873                                         const IdentifierInfo *Name) {
15874   // C++ [dcl.type.elab]p3:
15875   //   The class-key or enum keyword present in the
15876   //   elaborated-type-specifier shall agree in kind with the
15877   //   declaration to which the name in the elaborated-type-specifier
15878   //   refers. This rule also applies to the form of
15879   //   elaborated-type-specifier that declares a class-name or
15880   //   friend class since it can be construed as referring to the
15881   //   definition of the class. Thus, in any
15882   //   elaborated-type-specifier, the enum keyword shall be used to
15883   //   refer to an enumeration (7.2), the union class-key shall be
15884   //   used to refer to a union (clause 9), and either the class or
15885   //   struct class-key shall be used to refer to a class (clause 9)
15886   //   declared using the class or struct class-key.
15887   TagTypeKind OldTag = Previous->getTagKind();
15888   if (OldTag != NewTag &&
15889       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15890     return false;
15891 
15892   // Tags are compatible, but we might still want to warn on mismatched tags.
15893   // Non-class tags can't be mismatched at this point.
15894   if (!isClassCompatTagKind(NewTag))
15895     return true;
15896 
15897   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15898   // by our warning analysis. We don't want to warn about mismatches with (eg)
15899   // declarations in system headers that are designed to be specialized, but if
15900   // a user asks us to warn, we should warn if their code contains mismatched
15901   // declarations.
15902   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15903     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15904                                       Loc);
15905   };
15906   if (IsIgnoredLoc(NewTagLoc))
15907     return true;
15908 
15909   auto IsIgnored = [&](const TagDecl *Tag) {
15910     return IsIgnoredLoc(Tag->getLocation());
15911   };
15912   while (IsIgnored(Previous)) {
15913     Previous = Previous->getPreviousDecl();
15914     if (!Previous)
15915       return true;
15916     OldTag = Previous->getTagKind();
15917   }
15918 
15919   bool isTemplate = false;
15920   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15921     isTemplate = Record->getDescribedClassTemplate();
15922 
15923   if (inTemplateInstantiation()) {
15924     if (OldTag != NewTag) {
15925       // In a template instantiation, do not offer fix-its for tag mismatches
15926       // since they usually mess up the template instead of fixing the problem.
15927       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15928         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15929         << getRedeclDiagFromTagKind(OldTag);
15930       // FIXME: Note previous location?
15931     }
15932     return true;
15933   }
15934 
15935   if (isDefinition) {
15936     // On definitions, check all previous tags and issue a fix-it for each
15937     // one that doesn't match the current tag.
15938     if (Previous->getDefinition()) {
15939       // Don't suggest fix-its for redefinitions.
15940       return true;
15941     }
15942 
15943     bool previousMismatch = false;
15944     for (const TagDecl *I : Previous->redecls()) {
15945       if (I->getTagKind() != NewTag) {
15946         // Ignore previous declarations for which the warning was disabled.
15947         if (IsIgnored(I))
15948           continue;
15949 
15950         if (!previousMismatch) {
15951           previousMismatch = true;
15952           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15953             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15954             << getRedeclDiagFromTagKind(I->getTagKind());
15955         }
15956         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15957           << getRedeclDiagFromTagKind(NewTag)
15958           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15959                TypeWithKeyword::getTagTypeKindName(NewTag));
15960       }
15961     }
15962     return true;
15963   }
15964 
15965   // Identify the prevailing tag kind: this is the kind of the definition (if
15966   // there is a non-ignored definition), or otherwise the kind of the prior
15967   // (non-ignored) declaration.
15968   const TagDecl *PrevDef = Previous->getDefinition();
15969   if (PrevDef && IsIgnored(PrevDef))
15970     PrevDef = nullptr;
15971   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15972   if (Redecl->getTagKind() != NewTag) {
15973     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15974       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15975       << getRedeclDiagFromTagKind(OldTag);
15976     Diag(Redecl->getLocation(), diag::note_previous_use);
15977 
15978     // If there is a previous definition, suggest a fix-it.
15979     if (PrevDef) {
15980       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15981         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15982         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15983              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15984     }
15985   }
15986 
15987   return true;
15988 }
15989 
15990 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15991 /// from an outer enclosing namespace or file scope inside a friend declaration.
15992 /// This should provide the commented out code in the following snippet:
15993 ///   namespace N {
15994 ///     struct X;
15995 ///     namespace M {
15996 ///       struct Y { friend struct /*N::*/ X; };
15997 ///     }
15998 ///   }
15999 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
16000                                          SourceLocation NameLoc) {
16001   // While the decl is in a namespace, do repeated lookup of that name and see
16002   // if we get the same namespace back.  If we do not, continue until
16003   // translation unit scope, at which point we have a fully qualified NNS.
16004   SmallVector<IdentifierInfo *, 4> Namespaces;
16005   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16006   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16007     // This tag should be declared in a namespace, which can only be enclosed by
16008     // other namespaces.  Bail if there's an anonymous namespace in the chain.
16009     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16010     if (!Namespace || Namespace->isAnonymousNamespace())
16011       return FixItHint();
16012     IdentifierInfo *II = Namespace->getIdentifier();
16013     Namespaces.push_back(II);
16014     NamedDecl *Lookup = SemaRef.LookupSingleName(
16015         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16016     if (Lookup == Namespace)
16017       break;
16018   }
16019 
16020   // Once we have all the namespaces, reverse them to go outermost first, and
16021   // build an NNS.
16022   SmallString<64> Insertion;
16023   llvm::raw_svector_ostream OS(Insertion);
16024   if (DC->isTranslationUnit())
16025     OS << "::";
16026   std::reverse(Namespaces.begin(), Namespaces.end());
16027   for (auto *II : Namespaces)
16028     OS << II->getName() << "::";
16029   return FixItHint::CreateInsertion(NameLoc, Insertion);
16030 }
16031 
16032 /// Determine whether a tag originally declared in context \p OldDC can
16033 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16034 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16035 /// using-declaration).
16036 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
16037                                          DeclContext *NewDC) {
16038   OldDC = OldDC->getRedeclContext();
16039   NewDC = NewDC->getRedeclContext();
16040 
16041   if (OldDC->Equals(NewDC))
16042     return true;
16043 
16044   // In MSVC mode, we allow a redeclaration if the contexts are related (either
16045   // encloses the other).
16046   if (S.getLangOpts().MSVCCompat &&
16047       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16048     return true;
16049 
16050   return false;
16051 }
16052 
16053 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
16054 /// former case, Name will be non-null.  In the later case, Name will be null.
16055 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16056 /// reference/declaration/definition of a tag.
16057 ///
16058 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16059 /// trailing-type-specifier) other than one in an alias-declaration.
16060 ///
16061 /// \param SkipBody If non-null, will be set to indicate if the caller should
16062 /// skip the definition of this tag and treat it as if it were a declaration.
16063 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
16064                      SourceLocation KWLoc, CXXScopeSpec &SS,
16065                      IdentifierInfo *Name, SourceLocation NameLoc,
16066                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
16067                      SourceLocation ModulePrivateLoc,
16068                      MultiTemplateParamsArg TemplateParameterLists,
16069                      bool &OwnedDecl, bool &IsDependent,
16070                      SourceLocation ScopedEnumKWLoc,
16071                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16072                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16073                      SkipBodyInfo *SkipBody) {
16074   // If this is not a definition, it must have a name.
16075   IdentifierInfo *OrigName = Name;
16076   assert((Name != nullptr || TUK == TUK_Definition) &&
16077          "Nameless record must be a definition!");
16078   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16079 
16080   OwnedDecl = false;
16081   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16082   bool ScopedEnum = ScopedEnumKWLoc.isValid();
16083 
16084   // FIXME: Check member specializations more carefully.
16085   bool isMemberSpecialization = false;
16086   bool Invalid = false;
16087 
16088   // We only need to do this matching if we have template parameters
16089   // or a scope specifier, which also conveniently avoids this work
16090   // for non-C++ cases.
16091   if (TemplateParameterLists.size() > 0 ||
16092       (SS.isNotEmpty() && TUK != TUK_Reference)) {
16093     if (TemplateParameterList *TemplateParams =
16094             MatchTemplateParametersToScopeSpecifier(
16095                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16096                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16097       if (Kind == TTK_Enum) {
16098         Diag(KWLoc, diag::err_enum_template);
16099         return nullptr;
16100       }
16101 
16102       if (TemplateParams->size() > 0) {
16103         // This is a declaration or definition of a class template (which may
16104         // be a member of another template).
16105 
16106         if (Invalid)
16107           return nullptr;
16108 
16109         OwnedDecl = false;
16110         DeclResult Result = CheckClassTemplate(
16111             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16112             AS, ModulePrivateLoc,
16113             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16114             TemplateParameterLists.data(), SkipBody);
16115         return Result.get();
16116       } else {
16117         // The "template<>" header is extraneous.
16118         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16119           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16120         isMemberSpecialization = true;
16121       }
16122     }
16123 
16124     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16125         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16126       return nullptr;
16127   }
16128 
16129   // Figure out the underlying type if this a enum declaration. We need to do
16130   // this early, because it's needed to detect if this is an incompatible
16131   // redeclaration.
16132   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16133   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16134 
16135   if (Kind == TTK_Enum) {
16136     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16137       // No underlying type explicitly specified, or we failed to parse the
16138       // type, default to int.
16139       EnumUnderlying = Context.IntTy.getTypePtr();
16140     } else if (UnderlyingType.get()) {
16141       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16142       // integral type; any cv-qualification is ignored.
16143       TypeSourceInfo *TI = nullptr;
16144       GetTypeFromParser(UnderlyingType.get(), &TI);
16145       EnumUnderlying = TI;
16146 
16147       if (CheckEnumUnderlyingType(TI))
16148         // Recover by falling back to int.
16149         EnumUnderlying = Context.IntTy.getTypePtr();
16150 
16151       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
16152                                           UPPC_FixedUnderlyingType))
16153         EnumUnderlying = Context.IntTy.getTypePtr();
16154 
16155     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16156       // For MSVC ABI compatibility, unfixed enums must use an underlying type
16157       // of 'int'. However, if this is an unfixed forward declaration, don't set
16158       // the underlying type unless the user enables -fms-compatibility. This
16159       // makes unfixed forward declared enums incomplete and is more conforming.
16160       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16161         EnumUnderlying = Context.IntTy.getTypePtr();
16162     }
16163   }
16164 
16165   DeclContext *SearchDC = CurContext;
16166   DeclContext *DC = CurContext;
16167   bool isStdBadAlloc = false;
16168   bool isStdAlignValT = false;
16169 
16170   RedeclarationKind Redecl = forRedeclarationInCurContext();
16171   if (TUK == TUK_Friend || TUK == TUK_Reference)
16172     Redecl = NotForRedeclaration;
16173 
16174   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16175   /// implemented asks for structural equivalence checking, the returned decl
16176   /// here is passed back to the parser, allowing the tag body to be parsed.
16177   auto createTagFromNewDecl = [&]() -> TagDecl * {
16178     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16179     // If there is an identifier, use the location of the identifier as the
16180     // location of the decl, otherwise use the location of the struct/union
16181     // keyword.
16182     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16183     TagDecl *New = nullptr;
16184 
16185     if (Kind == TTK_Enum) {
16186       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16187                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16188       // If this is an undefined enum, bail.
16189       if (TUK != TUK_Definition && !Invalid)
16190         return nullptr;
16191       if (EnumUnderlying) {
16192         EnumDecl *ED = cast<EnumDecl>(New);
16193         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16194           ED->setIntegerTypeSourceInfo(TI);
16195         else
16196           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16197         ED->setPromotionType(ED->getIntegerType());
16198       }
16199     } else { // struct/union
16200       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16201                                nullptr);
16202     }
16203 
16204     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16205       // Add alignment attributes if necessary; these attributes are checked
16206       // when the ASTContext lays out the structure.
16207       //
16208       // It is important for implementing the correct semantics that this
16209       // happen here (in ActOnTag). The #pragma pack stack is
16210       // maintained as a result of parser callbacks which can occur at
16211       // many points during the parsing of a struct declaration (because
16212       // the #pragma tokens are effectively skipped over during the
16213       // parsing of the struct).
16214       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16215         AddAlignmentAttributesForRecord(RD);
16216         AddMsStructLayoutForRecord(RD);
16217       }
16218     }
16219     New->setLexicalDeclContext(CurContext);
16220     return New;
16221   };
16222 
16223   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16224   if (Name && SS.isNotEmpty()) {
16225     // We have a nested-name tag ('struct foo::bar').
16226 
16227     // Check for invalid 'foo::'.
16228     if (SS.isInvalid()) {
16229       Name = nullptr;
16230       goto CreateNewDecl;
16231     }
16232 
16233     // If this is a friend or a reference to a class in a dependent
16234     // context, don't try to make a decl for it.
16235     if (TUK == TUK_Friend || TUK == TUK_Reference) {
16236       DC = computeDeclContext(SS, false);
16237       if (!DC) {
16238         IsDependent = true;
16239         return nullptr;
16240       }
16241     } else {
16242       DC = computeDeclContext(SS, true);
16243       if (!DC) {
16244         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16245           << SS.getRange();
16246         return nullptr;
16247       }
16248     }
16249 
16250     if (RequireCompleteDeclContext(SS, DC))
16251       return nullptr;
16252 
16253     SearchDC = DC;
16254     // Look-up name inside 'foo::'.
16255     LookupQualifiedName(Previous, DC);
16256 
16257     if (Previous.isAmbiguous())
16258       return nullptr;
16259 
16260     if (Previous.empty()) {
16261       // Name lookup did not find anything. However, if the
16262       // nested-name-specifier refers to the current instantiation,
16263       // and that current instantiation has any dependent base
16264       // classes, we might find something at instantiation time: treat
16265       // this as a dependent elaborated-type-specifier.
16266       // But this only makes any sense for reference-like lookups.
16267       if (Previous.wasNotFoundInCurrentInstantiation() &&
16268           (TUK == TUK_Reference || TUK == TUK_Friend)) {
16269         IsDependent = true;
16270         return nullptr;
16271       }
16272 
16273       // A tag 'foo::bar' must already exist.
16274       Diag(NameLoc, diag::err_not_tag_in_scope)
16275         << Kind << Name << DC << SS.getRange();
16276       Name = nullptr;
16277       Invalid = true;
16278       goto CreateNewDecl;
16279     }
16280   } else if (Name) {
16281     // C++14 [class.mem]p14:
16282     //   If T is the name of a class, then each of the following shall have a
16283     //   name different from T:
16284     //    -- every member of class T that is itself a type
16285     if (TUK != TUK_Reference && TUK != TUK_Friend &&
16286         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16287       return nullptr;
16288 
16289     // If this is a named struct, check to see if there was a previous forward
16290     // declaration or definition.
16291     // FIXME: We're looking into outer scopes here, even when we
16292     // shouldn't be. Doing so can result in ambiguities that we
16293     // shouldn't be diagnosing.
16294     LookupName(Previous, S);
16295 
16296     // When declaring or defining a tag, ignore ambiguities introduced
16297     // by types using'ed into this scope.
16298     if (Previous.isAmbiguous() &&
16299         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16300       LookupResult::Filter F = Previous.makeFilter();
16301       while (F.hasNext()) {
16302         NamedDecl *ND = F.next();
16303         if (!ND->getDeclContext()->getRedeclContext()->Equals(
16304                 SearchDC->getRedeclContext()))
16305           F.erase();
16306       }
16307       F.done();
16308     }
16309 
16310     // C++11 [namespace.memdef]p3:
16311     //   If the name in a friend declaration is neither qualified nor
16312     //   a template-id and the declaration is a function or an
16313     //   elaborated-type-specifier, the lookup to determine whether
16314     //   the entity has been previously declared shall not consider
16315     //   any scopes outside the innermost enclosing namespace.
16316     //
16317     // MSVC doesn't implement the above rule for types, so a friend tag
16318     // declaration may be a redeclaration of a type declared in an enclosing
16319     // scope.  They do implement this rule for friend functions.
16320     //
16321     // Does it matter that this should be by scope instead of by
16322     // semantic context?
16323     if (!Previous.empty() && TUK == TUK_Friend) {
16324       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16325       LookupResult::Filter F = Previous.makeFilter();
16326       bool FriendSawTagOutsideEnclosingNamespace = false;
16327       while (F.hasNext()) {
16328         NamedDecl *ND = F.next();
16329         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
16330         if (DC->isFileContext() &&
16331             !EnclosingNS->Encloses(ND->getDeclContext())) {
16332           if (getLangOpts().MSVCCompat)
16333             FriendSawTagOutsideEnclosingNamespace = true;
16334           else
16335             F.erase();
16336         }
16337       }
16338       F.done();
16339 
16340       // Diagnose this MSVC extension in the easy case where lookup would have
16341       // unambiguously found something outside the enclosing namespace.
16342       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16343         NamedDecl *ND = Previous.getFoundDecl();
16344         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16345             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16346       }
16347     }
16348 
16349     // Note:  there used to be some attempt at recovery here.
16350     if (Previous.isAmbiguous())
16351       return nullptr;
16352 
16353     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16354       // FIXME: This makes sure that we ignore the contexts associated
16355       // with C structs, unions, and enums when looking for a matching
16356       // tag declaration or definition. See the similar lookup tweak
16357       // in Sema::LookupName; is there a better way to deal with this?
16358       while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
16359         SearchDC = SearchDC->getParent();
16360     } else if (getLangOpts().CPlusPlus) {
16361       // Inside ObjCContainer want to keep it as a lexical decl context but go
16362       // past it (most often to TranslationUnit) to find the semantic decl
16363       // context.
16364       while (isa<ObjCContainerDecl>(SearchDC))
16365         SearchDC = SearchDC->getParent();
16366     }
16367   } else if (getLangOpts().CPlusPlus) {
16368     // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16369     // TagDecl the same way as we skip it for named TagDecl.
16370     while (isa<ObjCContainerDecl>(SearchDC))
16371       SearchDC = SearchDC->getParent();
16372   }
16373 
16374   if (Previous.isSingleResult() &&
16375       Previous.getFoundDecl()->isTemplateParameter()) {
16376     // Maybe we will complain about the shadowed template parameter.
16377     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16378     // Just pretend that we didn't see the previous declaration.
16379     Previous.clear();
16380   }
16381 
16382   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16383       DC->Equals(getStdNamespace())) {
16384     if (Name->isStr("bad_alloc")) {
16385       // This is a declaration of or a reference to "std::bad_alloc".
16386       isStdBadAlloc = true;
16387 
16388       // If std::bad_alloc has been implicitly declared (but made invisible to
16389       // name lookup), fill in this implicit declaration as the previous
16390       // declaration, so that the declarations get chained appropriately.
16391       if (Previous.empty() && StdBadAlloc)
16392         Previous.addDecl(getStdBadAlloc());
16393     } else if (Name->isStr("align_val_t")) {
16394       isStdAlignValT = true;
16395       if (Previous.empty() && StdAlignValT)
16396         Previous.addDecl(getStdAlignValT());
16397     }
16398   }
16399 
16400   // If we didn't find a previous declaration, and this is a reference
16401   // (or friend reference), move to the correct scope.  In C++, we
16402   // also need to do a redeclaration lookup there, just in case
16403   // there's a shadow friend decl.
16404   if (Name && Previous.empty() &&
16405       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16406     if (Invalid) goto CreateNewDecl;
16407     assert(SS.isEmpty());
16408 
16409     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16410       // C++ [basic.scope.pdecl]p5:
16411       //   -- for an elaborated-type-specifier of the form
16412       //
16413       //          class-key identifier
16414       //
16415       //      if the elaborated-type-specifier is used in the
16416       //      decl-specifier-seq or parameter-declaration-clause of a
16417       //      function defined in namespace scope, the identifier is
16418       //      declared as a class-name in the namespace that contains
16419       //      the declaration; otherwise, except as a friend
16420       //      declaration, the identifier is declared in the smallest
16421       //      non-class, non-function-prototype scope that contains the
16422       //      declaration.
16423       //
16424       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16425       // C structs and unions.
16426       //
16427       // It is an error in C++ to declare (rather than define) an enum
16428       // type, including via an elaborated type specifier.  We'll
16429       // diagnose that later; for now, declare the enum in the same
16430       // scope as we would have picked for any other tag type.
16431       //
16432       // GNU C also supports this behavior as part of its incomplete
16433       // enum types extension, while GNU C++ does not.
16434       //
16435       // Find the context where we'll be declaring the tag.
16436       // FIXME: We would like to maintain the current DeclContext as the
16437       // lexical context,
16438       SearchDC = getTagInjectionContext(SearchDC);
16439 
16440       // Find the scope where we'll be declaring the tag.
16441       S = getTagInjectionScope(S, getLangOpts());
16442     } else {
16443       assert(TUK == TUK_Friend);
16444       // C++ [namespace.memdef]p3:
16445       //   If a friend declaration in a non-local class first declares a
16446       //   class or function, the friend class or function is a member of
16447       //   the innermost enclosing namespace.
16448       SearchDC = SearchDC->getEnclosingNamespaceContext();
16449     }
16450 
16451     // In C++, we need to do a redeclaration lookup to properly
16452     // diagnose some problems.
16453     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16454     // hidden declaration so that we don't get ambiguity errors when using a
16455     // type declared by an elaborated-type-specifier.  In C that is not correct
16456     // and we should instead merge compatible types found by lookup.
16457     if (getLangOpts().CPlusPlus) {
16458       // FIXME: This can perform qualified lookups into function contexts,
16459       // which are meaningless.
16460       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16461       LookupQualifiedName(Previous, SearchDC);
16462     } else {
16463       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16464       LookupName(Previous, S);
16465     }
16466   }
16467 
16468   // If we have a known previous declaration to use, then use it.
16469   if (Previous.empty() && SkipBody && SkipBody->Previous)
16470     Previous.addDecl(SkipBody->Previous);
16471 
16472   if (!Previous.empty()) {
16473     NamedDecl *PrevDecl = Previous.getFoundDecl();
16474     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16475 
16476     // It's okay to have a tag decl in the same scope as a typedef
16477     // which hides a tag decl in the same scope.  Finding this
16478     // with a redeclaration lookup can only actually happen in C++.
16479     //
16480     // This is also okay for elaborated-type-specifiers, which is
16481     // technically forbidden by the current standard but which is
16482     // okay according to the likely resolution of an open issue;
16483     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16484     if (getLangOpts().CPlusPlus) {
16485       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16486         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16487           TagDecl *Tag = TT->getDecl();
16488           if (Tag->getDeclName() == Name &&
16489               Tag->getDeclContext()->getRedeclContext()
16490                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16491             PrevDecl = Tag;
16492             Previous.clear();
16493             Previous.addDecl(Tag);
16494             Previous.resolveKind();
16495           }
16496         }
16497       }
16498     }
16499 
16500     // If this is a redeclaration of a using shadow declaration, it must
16501     // declare a tag in the same context. In MSVC mode, we allow a
16502     // redefinition if either context is within the other.
16503     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16504       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16505       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16506           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16507           !(OldTag && isAcceptableTagRedeclContext(
16508                           *this, OldTag->getDeclContext(), SearchDC))) {
16509         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16510         Diag(Shadow->getTargetDecl()->getLocation(),
16511              diag::note_using_decl_target);
16512         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16513             << 0;
16514         // Recover by ignoring the old declaration.
16515         Previous.clear();
16516         goto CreateNewDecl;
16517       }
16518     }
16519 
16520     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16521       // If this is a use of a previous tag, or if the tag is already declared
16522       // in the same scope (so that the definition/declaration completes or
16523       // rementions the tag), reuse the decl.
16524       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16525           isDeclInScope(DirectPrevDecl, SearchDC, S,
16526                         SS.isNotEmpty() || isMemberSpecialization)) {
16527         // Make sure that this wasn't declared as an enum and now used as a
16528         // struct or something similar.
16529         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16530                                           TUK == TUK_Definition, KWLoc,
16531                                           Name)) {
16532           bool SafeToContinue
16533             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16534                Kind != TTK_Enum);
16535           if (SafeToContinue)
16536             Diag(KWLoc, diag::err_use_with_wrong_tag)
16537               << Name
16538               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16539                                               PrevTagDecl->getKindName());
16540           else
16541             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16542           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16543 
16544           if (SafeToContinue)
16545             Kind = PrevTagDecl->getTagKind();
16546           else {
16547             // Recover by making this an anonymous redefinition.
16548             Name = nullptr;
16549             Previous.clear();
16550             Invalid = true;
16551           }
16552         }
16553 
16554         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16555           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16556           if (TUK == TUK_Reference || TUK == TUK_Friend)
16557             return PrevTagDecl;
16558 
16559           QualType EnumUnderlyingTy;
16560           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16561             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16562           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16563             EnumUnderlyingTy = QualType(T, 0);
16564 
16565           // All conflicts with previous declarations are recovered by
16566           // returning the previous declaration, unless this is a definition,
16567           // in which case we want the caller to bail out.
16568           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16569                                      ScopedEnum, EnumUnderlyingTy,
16570                                      IsFixed, PrevEnum))
16571             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16572         }
16573 
16574         // C++11 [class.mem]p1:
16575         //   A member shall not be declared twice in the member-specification,
16576         //   except that a nested class or member class template can be declared
16577         //   and then later defined.
16578         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16579             S->isDeclScope(PrevDecl)) {
16580           Diag(NameLoc, diag::ext_member_redeclared);
16581           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16582         }
16583 
16584         if (!Invalid) {
16585           // If this is a use, just return the declaration we found, unless
16586           // we have attributes.
16587           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16588             if (!Attrs.empty()) {
16589               // FIXME: Diagnose these attributes. For now, we create a new
16590               // declaration to hold them.
16591             } else if (TUK == TUK_Reference &&
16592                        (PrevTagDecl->getFriendObjectKind() ==
16593                             Decl::FOK_Undeclared ||
16594                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16595                        SS.isEmpty()) {
16596               // This declaration is a reference to an existing entity, but
16597               // has different visibility from that entity: it either makes
16598               // a friend visible or it makes a type visible in a new module.
16599               // In either case, create a new declaration. We only do this if
16600               // the declaration would have meant the same thing if no prior
16601               // declaration were found, that is, if it was found in the same
16602               // scope where we would have injected a declaration.
16603               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16604                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16605                 return PrevTagDecl;
16606               // This is in the injected scope, create a new declaration in
16607               // that scope.
16608               S = getTagInjectionScope(S, getLangOpts());
16609             } else {
16610               return PrevTagDecl;
16611             }
16612           }
16613 
16614           // Diagnose attempts to redefine a tag.
16615           if (TUK == TUK_Definition) {
16616             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16617               // If we're defining a specialization and the previous definition
16618               // is from an implicit instantiation, don't emit an error
16619               // here; we'll catch this in the general case below.
16620               bool IsExplicitSpecializationAfterInstantiation = false;
16621               if (isMemberSpecialization) {
16622                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16623                   IsExplicitSpecializationAfterInstantiation =
16624                     RD->getTemplateSpecializationKind() !=
16625                     TSK_ExplicitSpecialization;
16626                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16627                   IsExplicitSpecializationAfterInstantiation =
16628                     ED->getTemplateSpecializationKind() !=
16629                     TSK_ExplicitSpecialization;
16630               }
16631 
16632               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16633               // not keep more that one definition around (merge them). However,
16634               // ensure the decl passes the structural compatibility check in
16635               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16636               NamedDecl *Hidden = nullptr;
16637               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16638                 // There is a definition of this tag, but it is not visible. We
16639                 // explicitly make use of C++'s one definition rule here, and
16640                 // assume that this definition is identical to the hidden one
16641                 // we already have. Make the existing definition visible and
16642                 // use it in place of this one.
16643                 if (!getLangOpts().CPlusPlus) {
16644                   // Postpone making the old definition visible until after we
16645                   // complete parsing the new one and do the structural
16646                   // comparison.
16647                   SkipBody->CheckSameAsPrevious = true;
16648                   SkipBody->New = createTagFromNewDecl();
16649                   SkipBody->Previous = Def;
16650                   return Def;
16651                 } else {
16652                   SkipBody->ShouldSkip = true;
16653                   SkipBody->Previous = Def;
16654                   makeMergedDefinitionVisible(Hidden);
16655                   // Carry on and handle it like a normal definition. We'll
16656                   // skip starting the definitiion later.
16657                 }
16658               } else if (!IsExplicitSpecializationAfterInstantiation) {
16659                 // A redeclaration in function prototype scope in C isn't
16660                 // visible elsewhere, so merely issue a warning.
16661                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16662                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16663                 else
16664                   Diag(NameLoc, diag::err_redefinition) << Name;
16665                 notePreviousDefinition(Def,
16666                                        NameLoc.isValid() ? NameLoc : KWLoc);
16667                 // If this is a redefinition, recover by making this
16668                 // struct be anonymous, which will make any later
16669                 // references get the previous definition.
16670                 Name = nullptr;
16671                 Previous.clear();
16672                 Invalid = true;
16673               }
16674             } else {
16675               // If the type is currently being defined, complain
16676               // about a nested redefinition.
16677               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16678               if (TD->isBeingDefined()) {
16679                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16680                 Diag(PrevTagDecl->getLocation(),
16681                      diag::note_previous_definition);
16682                 Name = nullptr;
16683                 Previous.clear();
16684                 Invalid = true;
16685               }
16686             }
16687 
16688             // Okay, this is definition of a previously declared or referenced
16689             // tag. We're going to create a new Decl for it.
16690           }
16691 
16692           // Okay, we're going to make a redeclaration.  If this is some kind
16693           // of reference, make sure we build the redeclaration in the same DC
16694           // as the original, and ignore the current access specifier.
16695           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16696             SearchDC = PrevTagDecl->getDeclContext();
16697             AS = AS_none;
16698           }
16699         }
16700         // If we get here we have (another) forward declaration or we
16701         // have a definition.  Just create a new decl.
16702 
16703       } else {
16704         // If we get here, this is a definition of a new tag type in a nested
16705         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16706         // new decl/type.  We set PrevDecl to NULL so that the entities
16707         // have distinct types.
16708         Previous.clear();
16709       }
16710       // If we get here, we're going to create a new Decl. If PrevDecl
16711       // is non-NULL, it's a definition of the tag declared by
16712       // PrevDecl. If it's NULL, we have a new definition.
16713 
16714     // Otherwise, PrevDecl is not a tag, but was found with tag
16715     // lookup.  This is only actually possible in C++, where a few
16716     // things like templates still live in the tag namespace.
16717     } else {
16718       // Use a better diagnostic if an elaborated-type-specifier
16719       // found the wrong kind of type on the first
16720       // (non-redeclaration) lookup.
16721       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16722           !Previous.isForRedeclaration()) {
16723         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16724         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16725                                                        << Kind;
16726         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16727         Invalid = true;
16728 
16729       // Otherwise, only diagnose if the declaration is in scope.
16730       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16731                                 SS.isNotEmpty() || isMemberSpecialization)) {
16732         // do nothing
16733 
16734       // Diagnose implicit declarations introduced by elaborated types.
16735       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16736         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16737         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16738         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16739         Invalid = true;
16740 
16741       // Otherwise it's a declaration.  Call out a particularly common
16742       // case here.
16743       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16744         unsigned Kind = 0;
16745         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16746         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16747           << Name << Kind << TND->getUnderlyingType();
16748         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16749         Invalid = true;
16750 
16751       // Otherwise, diagnose.
16752       } else {
16753         // The tag name clashes with something else in the target scope,
16754         // issue an error and recover by making this tag be anonymous.
16755         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16756         notePreviousDefinition(PrevDecl, NameLoc);
16757         Name = nullptr;
16758         Invalid = true;
16759       }
16760 
16761       // The existing declaration isn't relevant to us; we're in a
16762       // new scope, so clear out the previous declaration.
16763       Previous.clear();
16764     }
16765   }
16766 
16767 CreateNewDecl:
16768 
16769   TagDecl *PrevDecl = nullptr;
16770   if (Previous.isSingleResult())
16771     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16772 
16773   // If there is an identifier, use the location of the identifier as the
16774   // location of the decl, otherwise use the location of the struct/union
16775   // keyword.
16776   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16777 
16778   // Otherwise, create a new declaration. If there is a previous
16779   // declaration of the same entity, the two will be linked via
16780   // PrevDecl.
16781   TagDecl *New;
16782 
16783   if (Kind == TTK_Enum) {
16784     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16785     // enum X { A, B, C } D;    D should chain to X.
16786     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16787                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16788                            ScopedEnumUsesClassTag, IsFixed);
16789 
16790     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16791       StdAlignValT = cast<EnumDecl>(New);
16792 
16793     // If this is an undefined enum, warn.
16794     if (TUK != TUK_Definition && !Invalid) {
16795       TagDecl *Def;
16796       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16797         // C++0x: 7.2p2: opaque-enum-declaration.
16798         // Conflicts are diagnosed above. Do nothing.
16799       }
16800       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16801         Diag(Loc, diag::ext_forward_ref_enum_def)
16802           << New;
16803         Diag(Def->getLocation(), diag::note_previous_definition);
16804       } else {
16805         unsigned DiagID = diag::ext_forward_ref_enum;
16806         if (getLangOpts().MSVCCompat)
16807           DiagID = diag::ext_ms_forward_ref_enum;
16808         else if (getLangOpts().CPlusPlus)
16809           DiagID = diag::err_forward_ref_enum;
16810         Diag(Loc, DiagID);
16811       }
16812     }
16813 
16814     if (EnumUnderlying) {
16815       EnumDecl *ED = cast<EnumDecl>(New);
16816       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16817         ED->setIntegerTypeSourceInfo(TI);
16818       else
16819         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16820       ED->setPromotionType(ED->getIntegerType());
16821       assert(ED->isComplete() && "enum with type should be complete");
16822     }
16823   } else {
16824     // struct/union/class
16825 
16826     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16827     // struct X { int A; } D;    D should chain to X.
16828     if (getLangOpts().CPlusPlus) {
16829       // FIXME: Look for a way to use RecordDecl for simple structs.
16830       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16831                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16832 
16833       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16834         StdBadAlloc = cast<CXXRecordDecl>(New);
16835     } else
16836       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16837                                cast_or_null<RecordDecl>(PrevDecl));
16838   }
16839 
16840   // C++11 [dcl.type]p3:
16841   //   A type-specifier-seq shall not define a class or enumeration [...].
16842   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16843       TUK == TUK_Definition) {
16844     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16845       << Context.getTagDeclType(New);
16846     Invalid = true;
16847   }
16848 
16849   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16850       DC->getDeclKind() == Decl::Enum) {
16851     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16852       << Context.getTagDeclType(New);
16853     Invalid = true;
16854   }
16855 
16856   // Maybe add qualifier info.
16857   if (SS.isNotEmpty()) {
16858     if (SS.isSet()) {
16859       // If this is either a declaration or a definition, check the
16860       // nested-name-specifier against the current context.
16861       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16862           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16863                                        isMemberSpecialization))
16864         Invalid = true;
16865 
16866       New->setQualifierInfo(SS.getWithLocInContext(Context));
16867       if (TemplateParameterLists.size() > 0) {
16868         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16869       }
16870     }
16871     else
16872       Invalid = true;
16873   }
16874 
16875   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16876     // Add alignment attributes if necessary; these attributes are checked when
16877     // the ASTContext lays out the structure.
16878     //
16879     // It is important for implementing the correct semantics that this
16880     // happen here (in ActOnTag). The #pragma pack stack is
16881     // maintained as a result of parser callbacks which can occur at
16882     // many points during the parsing of a struct declaration (because
16883     // the #pragma tokens are effectively skipped over during the
16884     // parsing of the struct).
16885     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16886       AddAlignmentAttributesForRecord(RD);
16887       AddMsStructLayoutForRecord(RD);
16888     }
16889   }
16890 
16891   if (ModulePrivateLoc.isValid()) {
16892     if (isMemberSpecialization)
16893       Diag(New->getLocation(), diag::err_module_private_specialization)
16894         << 2
16895         << FixItHint::CreateRemoval(ModulePrivateLoc);
16896     // __module_private__ does not apply to local classes. However, we only
16897     // diagnose this as an error when the declaration specifiers are
16898     // freestanding. Here, we just ignore the __module_private__.
16899     else if (!SearchDC->isFunctionOrMethod())
16900       New->setModulePrivate();
16901   }
16902 
16903   // If this is a specialization of a member class (of a class template),
16904   // check the specialization.
16905   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16906     Invalid = true;
16907 
16908   // If we're declaring or defining a tag in function prototype scope in C,
16909   // note that this type can only be used within the function and add it to
16910   // the list of decls to inject into the function definition scope.
16911   if ((Name || Kind == TTK_Enum) &&
16912       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16913     if (getLangOpts().CPlusPlus) {
16914       // C++ [dcl.fct]p6:
16915       //   Types shall not be defined in return or parameter types.
16916       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16917         Diag(Loc, diag::err_type_defined_in_param_type)
16918             << Name;
16919         Invalid = true;
16920       }
16921     } else if (!PrevDecl) {
16922       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16923     }
16924   }
16925 
16926   if (Invalid)
16927     New->setInvalidDecl();
16928 
16929   // Set the lexical context. If the tag has a C++ scope specifier, the
16930   // lexical context will be different from the semantic context.
16931   New->setLexicalDeclContext(CurContext);
16932 
16933   // Mark this as a friend decl if applicable.
16934   // In Microsoft mode, a friend declaration also acts as a forward
16935   // declaration so we always pass true to setObjectOfFriendDecl to make
16936   // the tag name visible.
16937   if (TUK == TUK_Friend)
16938     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16939 
16940   // Set the access specifier.
16941   if (!Invalid && SearchDC->isRecord())
16942     SetMemberAccessSpecifier(New, PrevDecl, AS);
16943 
16944   if (PrevDecl)
16945     CheckRedeclarationInModule(New, PrevDecl);
16946 
16947   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16948     New->startDefinition();
16949 
16950   ProcessDeclAttributeList(S, New, Attrs);
16951   AddPragmaAttributes(S, New);
16952 
16953   // If this has an identifier, add it to the scope stack.
16954   if (TUK == TUK_Friend) {
16955     // We might be replacing an existing declaration in the lookup tables;
16956     // if so, borrow its access specifier.
16957     if (PrevDecl)
16958       New->setAccess(PrevDecl->getAccess());
16959 
16960     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16961     DC->makeDeclVisibleInContext(New);
16962     if (Name) // can be null along some error paths
16963       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16964         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16965   } else if (Name) {
16966     S = getNonFieldDeclScope(S);
16967     PushOnScopeChains(New, S, true);
16968   } else {
16969     CurContext->addDecl(New);
16970   }
16971 
16972   // If this is the C FILE type, notify the AST context.
16973   if (IdentifierInfo *II = New->getIdentifier())
16974     if (!New->isInvalidDecl() &&
16975         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16976         II->isStr("FILE"))
16977       Context.setFILEDecl(New);
16978 
16979   if (PrevDecl)
16980     mergeDeclAttributes(New, PrevDecl);
16981 
16982   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16983     inferGslOwnerPointerAttribute(CXXRD);
16984 
16985   // If there's a #pragma GCC visibility in scope, set the visibility of this
16986   // record.
16987   AddPushedVisibilityAttribute(New);
16988 
16989   if (isMemberSpecialization && !New->isInvalidDecl())
16990     CompleteMemberSpecialization(New, Previous);
16991 
16992   OwnedDecl = true;
16993   // In C++, don't return an invalid declaration. We can't recover well from
16994   // the cases where we make the type anonymous.
16995   if (Invalid && getLangOpts().CPlusPlus) {
16996     if (New->isBeingDefined())
16997       if (auto RD = dyn_cast<RecordDecl>(New))
16998         RD->completeDefinition();
16999     return nullptr;
17000   } else if (SkipBody && SkipBody->ShouldSkip) {
17001     return SkipBody->Previous;
17002   } else {
17003     return New;
17004   }
17005 }
17006 
17007 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
17008   AdjustDeclIfTemplate(TagD);
17009   TagDecl *Tag = cast<TagDecl>(TagD);
17010 
17011   // Enter the tag context.
17012   PushDeclContext(S, Tag);
17013 
17014   ActOnDocumentableDecl(TagD);
17015 
17016   // If there's a #pragma GCC visibility in scope, set the visibility of this
17017   // record.
17018   AddPushedVisibilityAttribute(Tag);
17019 }
17020 
17021 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
17022   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17023     return false;
17024 
17025   // Make the previous decl visible.
17026   makeMergedDefinitionVisible(SkipBody.Previous);
17027   return true;
17028 }
17029 
17030 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
17031   assert(IDecl->getLexicalParent() == CurContext &&
17032       "The next DeclContext should be lexically contained in the current one.");
17033   CurContext = IDecl;
17034 }
17035 
17036 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
17037                                            SourceLocation FinalLoc,
17038                                            bool IsFinalSpelledSealed,
17039                                            bool IsAbstract,
17040                                            SourceLocation LBraceLoc) {
17041   AdjustDeclIfTemplate(TagD);
17042   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17043 
17044   FieldCollector->StartClass();
17045 
17046   if (!Record->getIdentifier())
17047     return;
17048 
17049   if (IsAbstract)
17050     Record->markAbstract();
17051 
17052   if (FinalLoc.isValid()) {
17053     Record->addAttr(FinalAttr::Create(
17054         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
17055         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
17056   }
17057   // C++ [class]p2:
17058   //   [...] The class-name is also inserted into the scope of the
17059   //   class itself; this is known as the injected-class-name. For
17060   //   purposes of access checking, the injected-class-name is treated
17061   //   as if it were a public member name.
17062   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17063       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17064       Record->getLocation(), Record->getIdentifier(),
17065       /*PrevDecl=*/nullptr,
17066       /*DelayTypeCreation=*/true);
17067   Context.getTypeDeclType(InjectedClassName, Record);
17068   InjectedClassName->setImplicit();
17069   InjectedClassName->setAccess(AS_public);
17070   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17071       InjectedClassName->setDescribedClassTemplate(Template);
17072   PushOnScopeChains(InjectedClassName, S);
17073   assert(InjectedClassName->isInjectedClassName() &&
17074          "Broken injected-class-name");
17075 }
17076 
17077 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
17078                                     SourceRange BraceRange) {
17079   AdjustDeclIfTemplate(TagD);
17080   TagDecl *Tag = cast<TagDecl>(TagD);
17081   Tag->setBraceRange(BraceRange);
17082 
17083   // Make sure we "complete" the definition even it is invalid.
17084   if (Tag->isBeingDefined()) {
17085     assert(Tag->isInvalidDecl() && "We should already have completed it");
17086     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17087       RD->completeDefinition();
17088   }
17089 
17090   if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17091     FieldCollector->FinishClass();
17092     if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17093       auto *Def = RD->getDefinition();
17094       assert(Def && "The record is expected to have a completed definition");
17095       unsigned NumInitMethods = 0;
17096       for (auto *Method : Def->methods()) {
17097         if (!Method->getIdentifier())
17098             continue;
17099         if (Method->getName() == "__init")
17100           NumInitMethods++;
17101       }
17102       if (NumInitMethods > 1 || !Def->hasInitMethod())
17103         Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17104     }
17105   }
17106 
17107   // Exit this scope of this tag's definition.
17108   PopDeclContext();
17109 
17110   if (getCurLexicalContext()->isObjCContainer() &&
17111       Tag->getDeclContext()->isFileContext())
17112     Tag->setTopLevelDeclInObjCContainer();
17113 
17114   // Notify the consumer that we've defined a tag.
17115   if (!Tag->isInvalidDecl())
17116     Consumer.HandleTagDeclDefinition(Tag);
17117 
17118   // Clangs implementation of #pragma align(packed) differs in bitfield layout
17119   // from XLs and instead matches the XL #pragma pack(1) behavior.
17120   if (Context.getTargetInfo().getTriple().isOSAIX() &&
17121       AlignPackStack.hasValue()) {
17122     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17123     // Only diagnose #pragma align(packed).
17124     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17125       return;
17126     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17127     if (!RD)
17128       return;
17129     // Only warn if there is at least 1 bitfield member.
17130     if (llvm::any_of(RD->fields(),
17131                      [](const FieldDecl *FD) { return FD->isBitField(); }))
17132       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17133   }
17134 }
17135 
17136 void Sema::ActOnObjCContainerFinishDefinition() {
17137   // Exit this scope of this interface definition.
17138   PopDeclContext();
17139 }
17140 
17141 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
17142   assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17143   OriginalLexicalContext = ObjCCtx;
17144   ActOnObjCContainerFinishDefinition();
17145 }
17146 
17147 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
17148   ActOnObjCContainerStartDefinition(ObjCCtx);
17149   OriginalLexicalContext = nullptr;
17150 }
17151 
17152 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
17153   AdjustDeclIfTemplate(TagD);
17154   TagDecl *Tag = cast<TagDecl>(TagD);
17155   Tag->setInvalidDecl();
17156 
17157   // Make sure we "complete" the definition even it is invalid.
17158   if (Tag->isBeingDefined()) {
17159     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17160       RD->completeDefinition();
17161   }
17162 
17163   // We're undoing ActOnTagStartDefinition here, not
17164   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17165   // the FieldCollector.
17166 
17167   PopDeclContext();
17168 }
17169 
17170 // Note that FieldName may be null for anonymous bitfields.
17171 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
17172                                 IdentifierInfo *FieldName, QualType FieldTy,
17173                                 bool IsMsStruct, Expr *BitWidth) {
17174   assert(BitWidth);
17175   if (BitWidth->containsErrors())
17176     return ExprError();
17177 
17178   // C99 6.7.2.1p4 - verify the field type.
17179   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17180   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17181     // Handle incomplete and sizeless types with a specific error.
17182     if (RequireCompleteSizedType(FieldLoc, FieldTy,
17183                                  diag::err_field_incomplete_or_sizeless))
17184       return ExprError();
17185     if (FieldName)
17186       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17187         << FieldName << FieldTy << BitWidth->getSourceRange();
17188     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17189       << FieldTy << BitWidth->getSourceRange();
17190   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17191                                              UPPC_BitFieldWidth))
17192     return ExprError();
17193 
17194   // If the bit-width is type- or value-dependent, don't try to check
17195   // it now.
17196   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17197     return BitWidth;
17198 
17199   llvm::APSInt Value;
17200   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
17201   if (ICE.isInvalid())
17202     return ICE;
17203   BitWidth = ICE.get();
17204 
17205   // Zero-width bitfield is ok for anonymous field.
17206   if (Value == 0 && FieldName)
17207     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17208 
17209   if (Value.isSigned() && Value.isNegative()) {
17210     if (FieldName)
17211       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17212                << FieldName << toString(Value, 10);
17213     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17214       << toString(Value, 10);
17215   }
17216 
17217   // The size of the bit-field must not exceed our maximum permitted object
17218   // size.
17219   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17220     return Diag(FieldLoc, diag::err_bitfield_too_wide)
17221            << !FieldName << FieldName << toString(Value, 10);
17222   }
17223 
17224   if (!FieldTy->isDependentType()) {
17225     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17226     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17227     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17228 
17229     // Over-wide bitfields are an error in C or when using the MSVC bitfield
17230     // ABI.
17231     bool CStdConstraintViolation =
17232         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17233     bool MSBitfieldViolation =
17234         Value.ugt(TypeStorageSize) &&
17235         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17236     if (CStdConstraintViolation || MSBitfieldViolation) {
17237       unsigned DiagWidth =
17238           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17239       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17240              << (bool)FieldName << FieldName << toString(Value, 10)
17241              << !CStdConstraintViolation << DiagWidth;
17242     }
17243 
17244     // Warn on types where the user might conceivably expect to get all
17245     // specified bits as value bits: that's all integral types other than
17246     // 'bool'.
17247     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17248       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17249           << FieldName << toString(Value, 10)
17250           << (unsigned)TypeWidth;
17251     }
17252   }
17253 
17254   return BitWidth;
17255 }
17256 
17257 /// ActOnField - Each field of a C struct/union is passed into this in order
17258 /// to create a FieldDecl object for it.
17259 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
17260                        Declarator &D, Expr *BitfieldWidth) {
17261   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17262                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17263                                /*InitStyle=*/ICIS_NoInit, AS_public);
17264   return Res;
17265 }
17266 
17267 /// HandleField - Analyze a field of a C struct or a C++ data member.
17268 ///
17269 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
17270                              SourceLocation DeclStart,
17271                              Declarator &D, Expr *BitWidth,
17272                              InClassInitStyle InitStyle,
17273                              AccessSpecifier AS) {
17274   if (D.isDecompositionDeclarator()) {
17275     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
17276     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17277       << Decomp.getSourceRange();
17278     return nullptr;
17279   }
17280 
17281   IdentifierInfo *II = D.getIdentifier();
17282   SourceLocation Loc = DeclStart;
17283   if (II) Loc = D.getIdentifierLoc();
17284 
17285   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17286   QualType T = TInfo->getType();
17287   if (getLangOpts().CPlusPlus) {
17288     CheckExtraCXXDefaultArguments(D);
17289 
17290     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17291                                         UPPC_DataMemberType)) {
17292       D.setInvalidType();
17293       T = Context.IntTy;
17294       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17295     }
17296   }
17297 
17298   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17299 
17300   if (D.getDeclSpec().isInlineSpecified())
17301     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17302         << getLangOpts().CPlusPlus17;
17303   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17304     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17305          diag::err_invalid_thread)
17306       << DeclSpec::getSpecifierName(TSCS);
17307 
17308   // Check to see if this name was declared as a member previously
17309   NamedDecl *PrevDecl = nullptr;
17310   LookupResult Previous(*this, II, Loc, LookupMemberName,
17311                         ForVisibleRedeclaration);
17312   LookupName(Previous, S);
17313   switch (Previous.getResultKind()) {
17314     case LookupResult::Found:
17315     case LookupResult::FoundUnresolvedValue:
17316       PrevDecl = Previous.getAsSingle<NamedDecl>();
17317       break;
17318 
17319     case LookupResult::FoundOverloaded:
17320       PrevDecl = Previous.getRepresentativeDecl();
17321       break;
17322 
17323     case LookupResult::NotFound:
17324     case LookupResult::NotFoundInCurrentInstantiation:
17325     case LookupResult::Ambiguous:
17326       break;
17327   }
17328   Previous.suppressDiagnostics();
17329 
17330   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17331     // Maybe we will complain about the shadowed template parameter.
17332     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17333     // Just pretend that we didn't see the previous declaration.
17334     PrevDecl = nullptr;
17335   }
17336 
17337   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17338     PrevDecl = nullptr;
17339 
17340   bool Mutable
17341     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
17342   SourceLocation TSSL = D.getBeginLoc();
17343   FieldDecl *NewFD
17344     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17345                      TSSL, AS, PrevDecl, &D);
17346 
17347   if (NewFD->isInvalidDecl())
17348     Record->setInvalidDecl();
17349 
17350   if (D.getDeclSpec().isModulePrivateSpecified())
17351     NewFD->setModulePrivate();
17352 
17353   if (NewFD->isInvalidDecl() && PrevDecl) {
17354     // Don't introduce NewFD into scope; there's already something
17355     // with the same name in the same scope.
17356   } else if (II) {
17357     PushOnScopeChains(NewFD, S);
17358   } else
17359     Record->addDecl(NewFD);
17360 
17361   return NewFD;
17362 }
17363 
17364 /// Build a new FieldDecl and check its well-formedness.
17365 ///
17366 /// This routine builds a new FieldDecl given the fields name, type,
17367 /// record, etc. \p PrevDecl should refer to any previous declaration
17368 /// with the same name and in the same scope as the field to be
17369 /// created.
17370 ///
17371 /// \returns a new FieldDecl.
17372 ///
17373 /// \todo The Declarator argument is a hack. It will be removed once
17374 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
17375                                 TypeSourceInfo *TInfo,
17376                                 RecordDecl *Record, SourceLocation Loc,
17377                                 bool Mutable, Expr *BitWidth,
17378                                 InClassInitStyle InitStyle,
17379                                 SourceLocation TSSL,
17380                                 AccessSpecifier AS, NamedDecl *PrevDecl,
17381                                 Declarator *D) {
17382   IdentifierInfo *II = Name.getAsIdentifierInfo();
17383   bool InvalidDecl = false;
17384   if (D) InvalidDecl = D->isInvalidType();
17385 
17386   // If we receive a broken type, recover by assuming 'int' and
17387   // marking this declaration as invalid.
17388   if (T.isNull() || T->containsErrors()) {
17389     InvalidDecl = true;
17390     T = Context.IntTy;
17391   }
17392 
17393   QualType EltTy = Context.getBaseElementType(T);
17394   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17395     if (RequireCompleteSizedType(Loc, EltTy,
17396                                  diag::err_field_incomplete_or_sizeless)) {
17397       // Fields of incomplete type force their record to be invalid.
17398       Record->setInvalidDecl();
17399       InvalidDecl = true;
17400     } else {
17401       NamedDecl *Def;
17402       EltTy->isIncompleteType(&Def);
17403       if (Def && Def->isInvalidDecl()) {
17404         Record->setInvalidDecl();
17405         InvalidDecl = true;
17406       }
17407     }
17408   }
17409 
17410   // TR 18037 does not allow fields to be declared with address space
17411   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17412       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17413     Diag(Loc, diag::err_field_with_address_space);
17414     Record->setInvalidDecl();
17415     InvalidDecl = true;
17416   }
17417 
17418   if (LangOpts.OpenCL) {
17419     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17420     // used as structure or union field: image, sampler, event or block types.
17421     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17422         T->isBlockPointerType()) {
17423       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17424       Record->setInvalidDecl();
17425       InvalidDecl = true;
17426     }
17427     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17428     // is enabled.
17429     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17430                         "__cl_clang_bitfields", LangOpts)) {
17431       Diag(Loc, diag::err_opencl_bitfields);
17432       InvalidDecl = true;
17433     }
17434   }
17435 
17436   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17437   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17438       T.hasQualifiers()) {
17439     InvalidDecl = true;
17440     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17441   }
17442 
17443   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17444   // than a variably modified type.
17445   if (!InvalidDecl && T->isVariablyModifiedType()) {
17446     if (!tryToFixVariablyModifiedVarType(
17447             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17448       InvalidDecl = true;
17449   }
17450 
17451   // Fields can not have abstract class types
17452   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17453                                              diag::err_abstract_type_in_decl,
17454                                              AbstractFieldType))
17455     InvalidDecl = true;
17456 
17457   if (InvalidDecl)
17458     BitWidth = nullptr;
17459   // If this is declared as a bit-field, check the bit-field.
17460   if (BitWidth) {
17461     BitWidth =
17462         VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
17463     if (!BitWidth) {
17464       InvalidDecl = true;
17465       BitWidth = nullptr;
17466     }
17467   }
17468 
17469   // Check that 'mutable' is consistent with the type of the declaration.
17470   if (!InvalidDecl && Mutable) {
17471     unsigned DiagID = 0;
17472     if (T->isReferenceType())
17473       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17474                                         : diag::err_mutable_reference;
17475     else if (T.isConstQualified())
17476       DiagID = diag::err_mutable_const;
17477 
17478     if (DiagID) {
17479       SourceLocation ErrLoc = Loc;
17480       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17481         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17482       Diag(ErrLoc, DiagID);
17483       if (DiagID != diag::ext_mutable_reference) {
17484         Mutable = false;
17485         InvalidDecl = true;
17486       }
17487     }
17488   }
17489 
17490   // C++11 [class.union]p8 (DR1460):
17491   //   At most one variant member of a union may have a
17492   //   brace-or-equal-initializer.
17493   if (InitStyle != ICIS_NoInit)
17494     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17495 
17496   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17497                                        BitWidth, Mutable, InitStyle);
17498   if (InvalidDecl)
17499     NewFD->setInvalidDecl();
17500 
17501   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17502     Diag(Loc, diag::err_duplicate_member) << II;
17503     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17504     NewFD->setInvalidDecl();
17505   }
17506 
17507   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17508     if (Record->isUnion()) {
17509       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17510         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17511         if (RDecl->getDefinition()) {
17512           // C++ [class.union]p1: An object of a class with a non-trivial
17513           // constructor, a non-trivial copy constructor, a non-trivial
17514           // destructor, or a non-trivial copy assignment operator
17515           // cannot be a member of a union, nor can an array of such
17516           // objects.
17517           if (CheckNontrivialField(NewFD))
17518             NewFD->setInvalidDecl();
17519         }
17520       }
17521 
17522       // C++ [class.union]p1: If a union contains a member of reference type,
17523       // the program is ill-formed, except when compiling with MSVC extensions
17524       // enabled.
17525       if (EltTy->isReferenceType()) {
17526         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17527                                     diag::ext_union_member_of_reference_type :
17528                                     diag::err_union_member_of_reference_type)
17529           << NewFD->getDeclName() << EltTy;
17530         if (!getLangOpts().MicrosoftExt)
17531           NewFD->setInvalidDecl();
17532       }
17533     }
17534   }
17535 
17536   // FIXME: We need to pass in the attributes given an AST
17537   // representation, not a parser representation.
17538   if (D) {
17539     // FIXME: The current scope is almost... but not entirely... correct here.
17540     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17541 
17542     if (NewFD->hasAttrs())
17543       CheckAlignasUnderalignment(NewFD);
17544   }
17545 
17546   // In auto-retain/release, infer strong retension for fields of
17547   // retainable type.
17548   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17549     NewFD->setInvalidDecl();
17550 
17551   if (T.isObjCGCWeak())
17552     Diag(Loc, diag::warn_attribute_weak_on_field);
17553 
17554   // PPC MMA non-pointer types are not allowed as field types.
17555   if (Context.getTargetInfo().getTriple().isPPC64() &&
17556       CheckPPCMMAType(T, NewFD->getLocation()))
17557     NewFD->setInvalidDecl();
17558 
17559   NewFD->setAccess(AS);
17560   return NewFD;
17561 }
17562 
17563 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17564   assert(FD);
17565   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17566 
17567   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17568     return false;
17569 
17570   QualType EltTy = Context.getBaseElementType(FD->getType());
17571   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17572     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17573     if (RDecl->getDefinition()) {
17574       // We check for copy constructors before constructors
17575       // because otherwise we'll never get complaints about
17576       // copy constructors.
17577 
17578       CXXSpecialMember member = CXXInvalid;
17579       // We're required to check for any non-trivial constructors. Since the
17580       // implicit default constructor is suppressed if there are any
17581       // user-declared constructors, we just need to check that there is a
17582       // trivial default constructor and a trivial copy constructor. (We don't
17583       // worry about move constructors here, since this is a C++98 check.)
17584       if (RDecl->hasNonTrivialCopyConstructor())
17585         member = CXXCopyConstructor;
17586       else if (!RDecl->hasTrivialDefaultConstructor())
17587         member = CXXDefaultConstructor;
17588       else if (RDecl->hasNonTrivialCopyAssignment())
17589         member = CXXCopyAssignment;
17590       else if (RDecl->hasNonTrivialDestructor())
17591         member = CXXDestructor;
17592 
17593       if (member != CXXInvalid) {
17594         if (!getLangOpts().CPlusPlus11 &&
17595             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17596           // Objective-C++ ARC: it is an error to have a non-trivial field of
17597           // a union. However, system headers in Objective-C programs
17598           // occasionally have Objective-C lifetime objects within unions,
17599           // and rather than cause the program to fail, we make those
17600           // members unavailable.
17601           SourceLocation Loc = FD->getLocation();
17602           if (getSourceManager().isInSystemHeader(Loc)) {
17603             if (!FD->hasAttr<UnavailableAttr>())
17604               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17605                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17606             return false;
17607           }
17608         }
17609 
17610         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17611                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17612                diag::err_illegal_union_or_anon_struct_member)
17613           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17614         DiagnoseNontrivial(RDecl, member);
17615         return !getLangOpts().CPlusPlus11;
17616       }
17617     }
17618   }
17619 
17620   return false;
17621 }
17622 
17623 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17624 ///  AST enum value.
17625 static ObjCIvarDecl::AccessControl
17626 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17627   switch (ivarVisibility) {
17628   default: llvm_unreachable("Unknown visitibility kind");
17629   case tok::objc_private: return ObjCIvarDecl::Private;
17630   case tok::objc_public: return ObjCIvarDecl::Public;
17631   case tok::objc_protected: return ObjCIvarDecl::Protected;
17632   case tok::objc_package: return ObjCIvarDecl::Package;
17633   }
17634 }
17635 
17636 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17637 /// in order to create an IvarDecl object for it.
17638 Decl *Sema::ActOnIvar(Scope *S,
17639                                 SourceLocation DeclStart,
17640                                 Declarator &D, Expr *BitfieldWidth,
17641                                 tok::ObjCKeywordKind Visibility) {
17642 
17643   IdentifierInfo *II = D.getIdentifier();
17644   Expr *BitWidth = (Expr*)BitfieldWidth;
17645   SourceLocation Loc = DeclStart;
17646   if (II) Loc = D.getIdentifierLoc();
17647 
17648   // FIXME: Unnamed fields can be handled in various different ways, for
17649   // example, unnamed unions inject all members into the struct namespace!
17650 
17651   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17652   QualType T = TInfo->getType();
17653 
17654   if (BitWidth) {
17655     // 6.7.2.1p3, 6.7.2.1p4
17656     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17657     if (!BitWidth)
17658       D.setInvalidType();
17659   } else {
17660     // Not a bitfield.
17661 
17662     // validate II.
17663 
17664   }
17665   if (T->isReferenceType()) {
17666     Diag(Loc, diag::err_ivar_reference_type);
17667     D.setInvalidType();
17668   }
17669   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17670   // than a variably modified type.
17671   else if (T->isVariablyModifiedType()) {
17672     if (!tryToFixVariablyModifiedVarType(
17673             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17674       D.setInvalidType();
17675   }
17676 
17677   // Get the visibility (access control) for this ivar.
17678   ObjCIvarDecl::AccessControl ac =
17679     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17680                                         : ObjCIvarDecl::None;
17681   // Must set ivar's DeclContext to its enclosing interface.
17682   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17683   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17684     return nullptr;
17685   ObjCContainerDecl *EnclosingContext;
17686   if (ObjCImplementationDecl *IMPDecl =
17687       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17688     if (LangOpts.ObjCRuntime.isFragile()) {
17689     // Case of ivar declared in an implementation. Context is that of its class.
17690       EnclosingContext = IMPDecl->getClassInterface();
17691       assert(EnclosingContext && "Implementation has no class interface!");
17692     }
17693     else
17694       EnclosingContext = EnclosingDecl;
17695   } else {
17696     if (ObjCCategoryDecl *CDecl =
17697         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17698       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17699         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17700         return nullptr;
17701       }
17702     }
17703     EnclosingContext = EnclosingDecl;
17704   }
17705 
17706   // Construct the decl.
17707   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17708                                              DeclStart, Loc, II, T,
17709                                              TInfo, ac, (Expr *)BitfieldWidth);
17710 
17711   if (II) {
17712     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17713                                            ForVisibleRedeclaration);
17714     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17715         && !isa<TagDecl>(PrevDecl)) {
17716       Diag(Loc, diag::err_duplicate_member) << II;
17717       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17718       NewID->setInvalidDecl();
17719     }
17720   }
17721 
17722   // Process attributes attached to the ivar.
17723   ProcessDeclAttributes(S, NewID, D);
17724 
17725   if (D.isInvalidType())
17726     NewID->setInvalidDecl();
17727 
17728   // In ARC, infer 'retaining' for ivars of retainable type.
17729   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17730     NewID->setInvalidDecl();
17731 
17732   if (D.getDeclSpec().isModulePrivateSpecified())
17733     NewID->setModulePrivate();
17734 
17735   if (II) {
17736     // FIXME: When interfaces are DeclContexts, we'll need to add
17737     // these to the interface.
17738     S->AddDecl(NewID);
17739     IdResolver.AddDecl(NewID);
17740   }
17741 
17742   if (LangOpts.ObjCRuntime.isNonFragile() &&
17743       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17744     Diag(Loc, diag::warn_ivars_in_interface);
17745 
17746   return NewID;
17747 }
17748 
17749 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17750 /// class and class extensions. For every class \@interface and class
17751 /// extension \@interface, if the last ivar is a bitfield of any type,
17752 /// then add an implicit `char :0` ivar to the end of that interface.
17753 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17754                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17755   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17756     return;
17757 
17758   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17759   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17760 
17761   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17762     return;
17763   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17764   if (!ID) {
17765     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17766       if (!CD->IsClassExtension())
17767         return;
17768     }
17769     // No need to add this to end of @implementation.
17770     else
17771       return;
17772   }
17773   // All conditions are met. Add a new bitfield to the tail end of ivars.
17774   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17775   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17776 
17777   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17778                               DeclLoc, DeclLoc, nullptr,
17779                               Context.CharTy,
17780                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17781                                                                DeclLoc),
17782                               ObjCIvarDecl::Private, BW,
17783                               true);
17784   AllIvarDecls.push_back(Ivar);
17785 }
17786 
17787 namespace {
17788 /// [class.dtor]p4:
17789 ///   At the end of the definition of a class, overload resolution is
17790 ///   performed among the prospective destructors declared in that class with
17791 ///   an empty argument list to select the destructor for the class, also
17792 ///   known as the selected destructor.
17793 ///
17794 /// We do the overload resolution here, then mark the selected constructor in the AST.
17795 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
17796 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
17797   if (!Record->hasUserDeclaredDestructor()) {
17798     return;
17799   }
17800 
17801   SourceLocation Loc = Record->getLocation();
17802   OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
17803 
17804   for (auto *Decl : Record->decls()) {
17805     if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
17806       if (DD->isInvalidDecl())
17807         continue;
17808       S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
17809                              OCS);
17810       assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
17811     }
17812   }
17813 
17814   if (OCS.empty()) {
17815     return;
17816   }
17817   OverloadCandidateSet::iterator Best;
17818   unsigned Msg = 0;
17819   OverloadCandidateDisplayKind DisplayKind;
17820 
17821   switch (OCS.BestViableFunction(S, Loc, Best)) {
17822   case OR_Success:
17823   case OR_Deleted:
17824     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
17825     break;
17826 
17827   case OR_Ambiguous:
17828     Msg = diag::err_ambiguous_destructor;
17829     DisplayKind = OCD_AmbiguousCandidates;
17830     break;
17831 
17832   case OR_No_Viable_Function:
17833     Msg = diag::err_no_viable_destructor;
17834     DisplayKind = OCD_AllCandidates;
17835     break;
17836   }
17837 
17838   if (Msg) {
17839     // OpenCL have got their own thing going with destructors. It's slightly broken,
17840     // but we allow it.
17841     if (!S.LangOpts.OpenCL) {
17842       PartialDiagnostic Diag = S.PDiag(Msg) << Record;
17843       OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
17844       Record->setInvalidDecl();
17845     }
17846     // It's a bit hacky: At this point we've raised an error but we want the
17847     // rest of the compiler to continue somehow working. However almost
17848     // everything we'll try to do with the class will depend on there being a
17849     // destructor. So let's pretend the first one is selected and hope for the
17850     // best.
17851     Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
17852   }
17853 }
17854 } // namespace
17855 
17856 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17857                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17858                        SourceLocation RBrac,
17859                        const ParsedAttributesView &Attrs) {
17860   assert(EnclosingDecl && "missing record or interface decl");
17861 
17862   // If this is an Objective-C @implementation or category and we have
17863   // new fields here we should reset the layout of the interface since
17864   // it will now change.
17865   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17866     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17867     switch (DC->getKind()) {
17868     default: break;
17869     case Decl::ObjCCategory:
17870       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17871       break;
17872     case Decl::ObjCImplementation:
17873       Context.
17874         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17875       break;
17876     }
17877   }
17878 
17879   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17880   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17881 
17882   if (CXXRecord && !CXXRecord->isDependentType())
17883     ComputeSelectedDestructor(*this, CXXRecord);
17884 
17885   // Start counting up the number of named members; make sure to include
17886   // members of anonymous structs and unions in the total.
17887   unsigned NumNamedMembers = 0;
17888   if (Record) {
17889     for (const auto *I : Record->decls()) {
17890       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17891         if (IFD->getDeclName())
17892           ++NumNamedMembers;
17893     }
17894   }
17895 
17896   // Verify that all the fields are okay.
17897   SmallVector<FieldDecl*, 32> RecFields;
17898 
17899   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17900        i != end; ++i) {
17901     FieldDecl *FD = cast<FieldDecl>(*i);
17902 
17903     // Get the type for the field.
17904     const Type *FDTy = FD->getType().getTypePtr();
17905 
17906     if (!FD->isAnonymousStructOrUnion()) {
17907       // Remember all fields written by the user.
17908       RecFields.push_back(FD);
17909     }
17910 
17911     // If the field is already invalid for some reason, don't emit more
17912     // diagnostics about it.
17913     if (FD->isInvalidDecl()) {
17914       EnclosingDecl->setInvalidDecl();
17915       continue;
17916     }
17917 
17918     // C99 6.7.2.1p2:
17919     //   A structure or union shall not contain a member with
17920     //   incomplete or function type (hence, a structure shall not
17921     //   contain an instance of itself, but may contain a pointer to
17922     //   an instance of itself), except that the last member of a
17923     //   structure with more than one named member may have incomplete
17924     //   array type; such a structure (and any union containing,
17925     //   possibly recursively, a member that is such a structure)
17926     //   shall not be a member of a structure or an element of an
17927     //   array.
17928     bool IsLastField = (i + 1 == Fields.end());
17929     if (FDTy->isFunctionType()) {
17930       // Field declared as a function.
17931       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17932         << FD->getDeclName();
17933       FD->setInvalidDecl();
17934       EnclosingDecl->setInvalidDecl();
17935       continue;
17936     } else if (FDTy->isIncompleteArrayType() &&
17937                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17938       if (Record) {
17939         // Flexible array member.
17940         // Microsoft and g++ is more permissive regarding flexible array.
17941         // It will accept flexible array in union and also
17942         // as the sole element of a struct/class.
17943         unsigned DiagID = 0;
17944         if (!Record->isUnion() && !IsLastField) {
17945           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17946             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17947           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17948           FD->setInvalidDecl();
17949           EnclosingDecl->setInvalidDecl();
17950           continue;
17951         } else if (Record->isUnion())
17952           DiagID = getLangOpts().MicrosoftExt
17953                        ? diag::ext_flexible_array_union_ms
17954                        : getLangOpts().CPlusPlus
17955                              ? diag::ext_flexible_array_union_gnu
17956                              : diag::err_flexible_array_union;
17957         else if (NumNamedMembers < 1)
17958           DiagID = getLangOpts().MicrosoftExt
17959                        ? diag::ext_flexible_array_empty_aggregate_ms
17960                        : getLangOpts().CPlusPlus
17961                              ? diag::ext_flexible_array_empty_aggregate_gnu
17962                              : diag::err_flexible_array_empty_aggregate;
17963 
17964         if (DiagID)
17965           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17966                                           << Record->getTagKind();
17967         // While the layout of types that contain virtual bases is not specified
17968         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17969         // virtual bases after the derived members.  This would make a flexible
17970         // array member declared at the end of an object not adjacent to the end
17971         // of the type.
17972         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17973           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17974               << FD->getDeclName() << Record->getTagKind();
17975         if (!getLangOpts().C99)
17976           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17977             << FD->getDeclName() << Record->getTagKind();
17978 
17979         // If the element type has a non-trivial destructor, we would not
17980         // implicitly destroy the elements, so disallow it for now.
17981         //
17982         // FIXME: GCC allows this. We should probably either implicitly delete
17983         // the destructor of the containing class, or just allow this.
17984         QualType BaseElem = Context.getBaseElementType(FD->getType());
17985         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17986           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17987             << FD->getDeclName() << FD->getType();
17988           FD->setInvalidDecl();
17989           EnclosingDecl->setInvalidDecl();
17990           continue;
17991         }
17992         // Okay, we have a legal flexible array member at the end of the struct.
17993         Record->setHasFlexibleArrayMember(true);
17994       } else {
17995         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17996         // unless they are followed by another ivar. That check is done
17997         // elsewhere, after synthesized ivars are known.
17998       }
17999     } else if (!FDTy->isDependentType() &&
18000                RequireCompleteSizedType(
18001                    FD->getLocation(), FD->getType(),
18002                    diag::err_field_incomplete_or_sizeless)) {
18003       // Incomplete type
18004       FD->setInvalidDecl();
18005       EnclosingDecl->setInvalidDecl();
18006       continue;
18007     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18008       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18009         // A type which contains a flexible array member is considered to be a
18010         // flexible array member.
18011         Record->setHasFlexibleArrayMember(true);
18012         if (!Record->isUnion()) {
18013           // If this is a struct/class and this is not the last element, reject
18014           // it.  Note that GCC supports variable sized arrays in the middle of
18015           // structures.
18016           if (!IsLastField)
18017             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18018               << FD->getDeclName() << FD->getType();
18019           else {
18020             // We support flexible arrays at the end of structs in
18021             // other structs as an extension.
18022             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18023               << FD->getDeclName();
18024           }
18025         }
18026       }
18027       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18028           RequireNonAbstractType(FD->getLocation(), FD->getType(),
18029                                  diag::err_abstract_type_in_decl,
18030                                  AbstractIvarType)) {
18031         // Ivars can not have abstract class types
18032         FD->setInvalidDecl();
18033       }
18034       if (Record && FDTTy->getDecl()->hasObjectMember())
18035         Record->setHasObjectMember(true);
18036       if (Record && FDTTy->getDecl()->hasVolatileMember())
18037         Record->setHasVolatileMember(true);
18038     } else if (FDTy->isObjCObjectType()) {
18039       /// A field cannot be an Objective-c object
18040       Diag(FD->getLocation(), diag::err_statically_allocated_object)
18041         << FixItHint::CreateInsertion(FD->getLocation(), "*");
18042       QualType T = Context.getObjCObjectPointerType(FD->getType());
18043       FD->setType(T);
18044     } else if (Record && Record->isUnion() &&
18045                FD->getType().hasNonTrivialObjCLifetime() &&
18046                getSourceManager().isInSystemHeader(FD->getLocation()) &&
18047                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18048                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
18049                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
18050       // For backward compatibility, fields of C unions declared in system
18051       // headers that have non-trivial ObjC ownership qualifications are marked
18052       // as unavailable unless the qualifier is explicit and __strong. This can
18053       // break ABI compatibility between programs compiled with ARC and MRR, but
18054       // is a better option than rejecting programs using those unions under
18055       // ARC.
18056       FD->addAttr(UnavailableAttr::CreateImplicit(
18057           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18058           FD->getLocation()));
18059     } else if (getLangOpts().ObjC &&
18060                getLangOpts().getGC() != LangOptions::NonGC && Record &&
18061                !Record->hasObjectMember()) {
18062       if (FD->getType()->isObjCObjectPointerType() ||
18063           FD->getType().isObjCGCStrong())
18064         Record->setHasObjectMember(true);
18065       else if (Context.getAsArrayType(FD->getType())) {
18066         QualType BaseType = Context.getBaseElementType(FD->getType());
18067         if (BaseType->isRecordType() &&
18068             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18069           Record->setHasObjectMember(true);
18070         else if (BaseType->isObjCObjectPointerType() ||
18071                  BaseType.isObjCGCStrong())
18072                Record->setHasObjectMember(true);
18073       }
18074     }
18075 
18076     if (Record && !getLangOpts().CPlusPlus &&
18077         !shouldIgnoreForRecordTriviality(FD)) {
18078       QualType FT = FD->getType();
18079       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
18080         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18081         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18082             Record->isUnion())
18083           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18084       }
18085       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
18086       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
18087         Record->setNonTrivialToPrimitiveCopy(true);
18088         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18089           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18090       }
18091       if (FT.isDestructedType()) {
18092         Record->setNonTrivialToPrimitiveDestroy(true);
18093         Record->setParamDestroyedInCallee(true);
18094         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18095           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18096       }
18097 
18098       if (const auto *RT = FT->getAs<RecordType>()) {
18099         if (RT->getDecl()->getArgPassingRestrictions() ==
18100             RecordDecl::APK_CanNeverPassInRegs)
18101           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18102       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
18103         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18104     }
18105 
18106     if (Record && FD->getType().isVolatileQualified())
18107       Record->setHasVolatileMember(true);
18108     // Keep track of the number of named members.
18109     if (FD->getIdentifier())
18110       ++NumNamedMembers;
18111   }
18112 
18113   // Okay, we successfully defined 'Record'.
18114   if (Record) {
18115     bool Completed = false;
18116     if (CXXRecord) {
18117       if (!CXXRecord->isInvalidDecl()) {
18118         // Set access bits correctly on the directly-declared conversions.
18119         for (CXXRecordDecl::conversion_iterator
18120                I = CXXRecord->conversion_begin(),
18121                E = CXXRecord->conversion_end(); I != E; ++I)
18122           I.setAccess((*I)->getAccess());
18123       }
18124 
18125       // Add any implicitly-declared members to this class.
18126       AddImplicitlyDeclaredMembersToClass(CXXRecord);
18127 
18128       if (!CXXRecord->isDependentType()) {
18129         if (!CXXRecord->isInvalidDecl()) {
18130           // If we have virtual base classes, we may end up finding multiple
18131           // final overriders for a given virtual function. Check for this
18132           // problem now.
18133           if (CXXRecord->getNumVBases()) {
18134             CXXFinalOverriderMap FinalOverriders;
18135             CXXRecord->getFinalOverriders(FinalOverriders);
18136 
18137             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18138                                              MEnd = FinalOverriders.end();
18139                  M != MEnd; ++M) {
18140               for (OverridingMethods::iterator SO = M->second.begin(),
18141                                             SOEnd = M->second.end();
18142                    SO != SOEnd; ++SO) {
18143                 assert(SO->second.size() > 0 &&
18144                        "Virtual function without overriding functions?");
18145                 if (SO->second.size() == 1)
18146                   continue;
18147 
18148                 // C++ [class.virtual]p2:
18149                 //   In a derived class, if a virtual member function of a base
18150                 //   class subobject has more than one final overrider the
18151                 //   program is ill-formed.
18152                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18153                   << (const NamedDecl *)M->first << Record;
18154                 Diag(M->first->getLocation(),
18155                      diag::note_overridden_virtual_function);
18156                 for (OverridingMethods::overriding_iterator
18157                           OM = SO->second.begin(),
18158                        OMEnd = SO->second.end();
18159                      OM != OMEnd; ++OM)
18160                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
18161                     << (const NamedDecl *)M->first << OM->Method->getParent();
18162 
18163                 Record->setInvalidDecl();
18164               }
18165             }
18166             CXXRecord->completeDefinition(&FinalOverriders);
18167             Completed = true;
18168           }
18169         }
18170       }
18171     }
18172 
18173     if (!Completed)
18174       Record->completeDefinition();
18175 
18176     // Handle attributes before checking the layout.
18177     ProcessDeclAttributeList(S, Record, Attrs);
18178 
18179     // Check to see if a FieldDecl is a pointer to a function.
18180     auto IsFunctionPointer = [&](const Decl *D) {
18181       const FieldDecl *FD = dyn_cast<FieldDecl>(D);
18182       if (!FD)
18183         return false;
18184       QualType FieldType = FD->getType().getDesugaredType(Context);
18185       if (isa<PointerType>(FieldType)) {
18186         QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
18187         return PointeeType.getDesugaredType(Context)->isFunctionType();
18188       }
18189       return false;
18190     };
18191 
18192     // Maybe randomize the record's decls. We automatically randomize a record
18193     // of function pointers, unless it has the "no_randomize_layout" attribute.
18194     if (!getLangOpts().CPlusPlus &&
18195         (Record->hasAttr<RandomizeLayoutAttr>() ||
18196          (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
18197           llvm::all_of(Record->decls(), IsFunctionPointer))) &&
18198         !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
18199         !Record->isRandomized()) {
18200       SmallVector<Decl *, 32> NewDeclOrdering;
18201       if (randstruct::randomizeStructureLayout(Context, Record,
18202                                                NewDeclOrdering))
18203         Record->reorderDecls(NewDeclOrdering);
18204     }
18205 
18206     // We may have deferred checking for a deleted destructor. Check now.
18207     if (CXXRecord) {
18208       auto *Dtor = CXXRecord->getDestructor();
18209       if (Dtor && Dtor->isImplicit() &&
18210           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
18211         CXXRecord->setImplicitDestructorIsDeleted();
18212         SetDeclDeleted(Dtor, CXXRecord->getLocation());
18213       }
18214     }
18215 
18216     if (Record->hasAttrs()) {
18217       CheckAlignasUnderalignment(Record);
18218 
18219       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
18220         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
18221                                            IA->getRange(), IA->getBestCase(),
18222                                            IA->getInheritanceModel());
18223     }
18224 
18225     // Check if the structure/union declaration is a type that can have zero
18226     // size in C. For C this is a language extension, for C++ it may cause
18227     // compatibility problems.
18228     bool CheckForZeroSize;
18229     if (!getLangOpts().CPlusPlus) {
18230       CheckForZeroSize = true;
18231     } else {
18232       // For C++ filter out types that cannot be referenced in C code.
18233       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
18234       CheckForZeroSize =
18235           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
18236           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
18237           CXXRecord->isCLike();
18238     }
18239     if (CheckForZeroSize) {
18240       bool ZeroSize = true;
18241       bool IsEmpty = true;
18242       unsigned NonBitFields = 0;
18243       for (RecordDecl::field_iterator I = Record->field_begin(),
18244                                       E = Record->field_end();
18245            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
18246         IsEmpty = false;
18247         if (I->isUnnamedBitfield()) {
18248           if (!I->isZeroLengthBitField(Context))
18249             ZeroSize = false;
18250         } else {
18251           ++NonBitFields;
18252           QualType FieldType = I->getType();
18253           if (FieldType->isIncompleteType() ||
18254               !Context.getTypeSizeInChars(FieldType).isZero())
18255             ZeroSize = false;
18256         }
18257       }
18258 
18259       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18260       // allowed in C++, but warn if its declaration is inside
18261       // extern "C" block.
18262       if (ZeroSize) {
18263         Diag(RecLoc, getLangOpts().CPlusPlus ?
18264                          diag::warn_zero_size_struct_union_in_extern_c :
18265                          diag::warn_zero_size_struct_union_compat)
18266           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
18267       }
18268 
18269       // Structs without named members are extension in C (C99 6.7.2.1p7),
18270       // but are accepted by GCC.
18271       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
18272         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
18273                                diag::ext_no_named_members_in_struct_union)
18274           << Record->isUnion();
18275       }
18276     }
18277   } else {
18278     ObjCIvarDecl **ClsFields =
18279       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
18280     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
18281       ID->setEndOfDefinitionLoc(RBrac);
18282       // Add ivar's to class's DeclContext.
18283       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18284         ClsFields[i]->setLexicalDeclContext(ID);
18285         ID->addDecl(ClsFields[i]);
18286       }
18287       // Must enforce the rule that ivars in the base classes may not be
18288       // duplicates.
18289       if (ID->getSuperClass())
18290         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
18291     } else if (ObjCImplementationDecl *IMPDecl =
18292                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18293       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
18294       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
18295         // Ivar declared in @implementation never belongs to the implementation.
18296         // Only it is in implementation's lexical context.
18297         ClsFields[I]->setLexicalDeclContext(IMPDecl);
18298       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
18299       IMPDecl->setIvarLBraceLoc(LBrac);
18300       IMPDecl->setIvarRBraceLoc(RBrac);
18301     } else if (ObjCCategoryDecl *CDecl =
18302                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18303       // case of ivars in class extension; all other cases have been
18304       // reported as errors elsewhere.
18305       // FIXME. Class extension does not have a LocEnd field.
18306       // CDecl->setLocEnd(RBrac);
18307       // Add ivar's to class extension's DeclContext.
18308       // Diagnose redeclaration of private ivars.
18309       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
18310       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
18311         if (IDecl) {
18312           if (const ObjCIvarDecl *ClsIvar =
18313               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
18314             Diag(ClsFields[i]->getLocation(),
18315                  diag::err_duplicate_ivar_declaration);
18316             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
18317             continue;
18318           }
18319           for (const auto *Ext : IDecl->known_extensions()) {
18320             if (const ObjCIvarDecl *ClsExtIvar
18321                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18322               Diag(ClsFields[i]->getLocation(),
18323                    diag::err_duplicate_ivar_declaration);
18324               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18325               continue;
18326             }
18327           }
18328         }
18329         ClsFields[i]->setLexicalDeclContext(CDecl);
18330         CDecl->addDecl(ClsFields[i]);
18331       }
18332       CDecl->setIvarLBraceLoc(LBrac);
18333       CDecl->setIvarRBraceLoc(RBrac);
18334     }
18335   }
18336 }
18337 
18338 /// Determine whether the given integral value is representable within
18339 /// the given type T.
18340 static bool isRepresentableIntegerValue(ASTContext &Context,
18341                                         llvm::APSInt &Value,
18342                                         QualType T) {
18343   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18344          "Integral type required!");
18345   unsigned BitWidth = Context.getIntWidth(T);
18346 
18347   if (Value.isUnsigned() || Value.isNonNegative()) {
18348     if (T->isSignedIntegerOrEnumerationType())
18349       --BitWidth;
18350     return Value.getActiveBits() <= BitWidth;
18351   }
18352   return Value.getMinSignedBits() <= BitWidth;
18353 }
18354 
18355 // Given an integral type, return the next larger integral type
18356 // (or a NULL type of no such type exists).
18357 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
18358   // FIXME: Int128/UInt128 support, which also needs to be introduced into
18359   // enum checking below.
18360   assert((T->isIntegralType(Context) ||
18361          T->isEnumeralType()) && "Integral type required!");
18362   const unsigned NumTypes = 4;
18363   QualType SignedIntegralTypes[NumTypes] = {
18364     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18365   };
18366   QualType UnsignedIntegralTypes[NumTypes] = {
18367     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18368     Context.UnsignedLongLongTy
18369   };
18370 
18371   unsigned BitWidth = Context.getTypeSize(T);
18372   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18373                                                         : UnsignedIntegralTypes;
18374   for (unsigned I = 0; I != NumTypes; ++I)
18375     if (Context.getTypeSize(Types[I]) > BitWidth)
18376       return Types[I];
18377 
18378   return QualType();
18379 }
18380 
18381 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
18382                                           EnumConstantDecl *LastEnumConst,
18383                                           SourceLocation IdLoc,
18384                                           IdentifierInfo *Id,
18385                                           Expr *Val) {
18386   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18387   llvm::APSInt EnumVal(IntWidth);
18388   QualType EltTy;
18389 
18390   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18391     Val = nullptr;
18392 
18393   if (Val)
18394     Val = DefaultLvalueConversion(Val).get();
18395 
18396   if (Val) {
18397     if (Enum->isDependentType() || Val->isTypeDependent() ||
18398         Val->containsErrors())
18399       EltTy = Context.DependentTy;
18400     else {
18401       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18402       // underlying type, but do allow it in all other contexts.
18403       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18404         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18405         // constant-expression in the enumerator-definition shall be a converted
18406         // constant expression of the underlying type.
18407         EltTy = Enum->getIntegerType();
18408         ExprResult Converted =
18409           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18410                                            CCEK_Enumerator);
18411         if (Converted.isInvalid())
18412           Val = nullptr;
18413         else
18414           Val = Converted.get();
18415       } else if (!Val->isValueDependent() &&
18416                  !(Val =
18417                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18418                            .get())) {
18419         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18420       } else {
18421         if (Enum->isComplete()) {
18422           EltTy = Enum->getIntegerType();
18423 
18424           // In Obj-C and Microsoft mode, require the enumeration value to be
18425           // representable in the underlying type of the enumeration. In C++11,
18426           // we perform a non-narrowing conversion as part of converted constant
18427           // expression checking.
18428           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18429             if (Context.getTargetInfo()
18430                     .getTriple()
18431                     .isWindowsMSVCEnvironment()) {
18432               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18433             } else {
18434               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18435             }
18436           }
18437 
18438           // Cast to the underlying type.
18439           Val = ImpCastExprToType(Val, EltTy,
18440                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
18441                                                          : CK_IntegralCast)
18442                     .get();
18443         } else if (getLangOpts().CPlusPlus) {
18444           // C++11 [dcl.enum]p5:
18445           //   If the underlying type is not fixed, the type of each enumerator
18446           //   is the type of its initializing value:
18447           //     - If an initializer is specified for an enumerator, the
18448           //       initializing value has the same type as the expression.
18449           EltTy = Val->getType();
18450         } else {
18451           // C99 6.7.2.2p2:
18452           //   The expression that defines the value of an enumeration constant
18453           //   shall be an integer constant expression that has a value
18454           //   representable as an int.
18455 
18456           // Complain if the value is not representable in an int.
18457           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18458             Diag(IdLoc, diag::ext_enum_value_not_int)
18459               << toString(EnumVal, 10) << Val->getSourceRange()
18460               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18461           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18462             // Force the type of the expression to 'int'.
18463             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18464           }
18465           EltTy = Val->getType();
18466         }
18467       }
18468     }
18469   }
18470 
18471   if (!Val) {
18472     if (Enum->isDependentType())
18473       EltTy = Context.DependentTy;
18474     else if (!LastEnumConst) {
18475       // C++0x [dcl.enum]p5:
18476       //   If the underlying type is not fixed, the type of each enumerator
18477       //   is the type of its initializing value:
18478       //     - If no initializer is specified for the first enumerator, the
18479       //       initializing value has an unspecified integral type.
18480       //
18481       // GCC uses 'int' for its unspecified integral type, as does
18482       // C99 6.7.2.2p3.
18483       if (Enum->isFixed()) {
18484         EltTy = Enum->getIntegerType();
18485       }
18486       else {
18487         EltTy = Context.IntTy;
18488       }
18489     } else {
18490       // Assign the last value + 1.
18491       EnumVal = LastEnumConst->getInitVal();
18492       ++EnumVal;
18493       EltTy = LastEnumConst->getType();
18494 
18495       // Check for overflow on increment.
18496       if (EnumVal < LastEnumConst->getInitVal()) {
18497         // C++0x [dcl.enum]p5:
18498         //   If the underlying type is not fixed, the type of each enumerator
18499         //   is the type of its initializing value:
18500         //
18501         //     - Otherwise the type of the initializing value is the same as
18502         //       the type of the initializing value of the preceding enumerator
18503         //       unless the incremented value is not representable in that type,
18504         //       in which case the type is an unspecified integral type
18505         //       sufficient to contain the incremented value. If no such type
18506         //       exists, the program is ill-formed.
18507         QualType T = getNextLargerIntegralType(Context, EltTy);
18508         if (T.isNull() || Enum->isFixed()) {
18509           // There is no integral type larger enough to represent this
18510           // value. Complain, then allow the value to wrap around.
18511           EnumVal = LastEnumConst->getInitVal();
18512           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18513           ++EnumVal;
18514           if (Enum->isFixed())
18515             // When the underlying type is fixed, this is ill-formed.
18516             Diag(IdLoc, diag::err_enumerator_wrapped)
18517               << toString(EnumVal, 10)
18518               << EltTy;
18519           else
18520             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18521               << toString(EnumVal, 10);
18522         } else {
18523           EltTy = T;
18524         }
18525 
18526         // Retrieve the last enumerator's value, extent that type to the
18527         // type that is supposed to be large enough to represent the incremented
18528         // value, then increment.
18529         EnumVal = LastEnumConst->getInitVal();
18530         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18531         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18532         ++EnumVal;
18533 
18534         // If we're not in C++, diagnose the overflow of enumerator values,
18535         // which in C99 means that the enumerator value is not representable in
18536         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18537         // permits enumerator values that are representable in some larger
18538         // integral type.
18539         if (!getLangOpts().CPlusPlus && !T.isNull())
18540           Diag(IdLoc, diag::warn_enum_value_overflow);
18541       } else if (!getLangOpts().CPlusPlus &&
18542                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18543         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18544         Diag(IdLoc, diag::ext_enum_value_not_int)
18545           << toString(EnumVal, 10) << 1;
18546       }
18547     }
18548   }
18549 
18550   if (!EltTy->isDependentType()) {
18551     // Make the enumerator value match the signedness and size of the
18552     // enumerator's type.
18553     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18554     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18555   }
18556 
18557   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18558                                   Val, EnumVal);
18559 }
18560 
18561 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18562                                                 SourceLocation IILoc) {
18563   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18564       !getLangOpts().CPlusPlus)
18565     return SkipBodyInfo();
18566 
18567   // We have an anonymous enum definition. Look up the first enumerator to
18568   // determine if we should merge the definition with an existing one and
18569   // skip the body.
18570   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18571                                          forRedeclarationInCurContext());
18572   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18573   if (!PrevECD)
18574     return SkipBodyInfo();
18575 
18576   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18577   NamedDecl *Hidden;
18578   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18579     SkipBodyInfo Skip;
18580     Skip.Previous = Hidden;
18581     return Skip;
18582   }
18583 
18584   return SkipBodyInfo();
18585 }
18586 
18587 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18588                               SourceLocation IdLoc, IdentifierInfo *Id,
18589                               const ParsedAttributesView &Attrs,
18590                               SourceLocation EqualLoc, Expr *Val) {
18591   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18592   EnumConstantDecl *LastEnumConst =
18593     cast_or_null<EnumConstantDecl>(lastEnumConst);
18594 
18595   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18596   // we find one that is.
18597   S = getNonFieldDeclScope(S);
18598 
18599   // Verify that there isn't already something declared with this name in this
18600   // scope.
18601   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18602   LookupName(R, S);
18603   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18604 
18605   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18606     // Maybe we will complain about the shadowed template parameter.
18607     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18608     // Just pretend that we didn't see the previous declaration.
18609     PrevDecl = nullptr;
18610   }
18611 
18612   // C++ [class.mem]p15:
18613   // If T is the name of a class, then each of the following shall have a name
18614   // different from T:
18615   // - every enumerator of every member of class T that is an unscoped
18616   // enumerated type
18617   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18618     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18619                             DeclarationNameInfo(Id, IdLoc));
18620 
18621   EnumConstantDecl *New =
18622     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18623   if (!New)
18624     return nullptr;
18625 
18626   if (PrevDecl) {
18627     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18628       // Check for other kinds of shadowing not already handled.
18629       CheckShadow(New, PrevDecl, R);
18630     }
18631 
18632     // When in C++, we may get a TagDecl with the same name; in this case the
18633     // enum constant will 'hide' the tag.
18634     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18635            "Received TagDecl when not in C++!");
18636     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18637       if (isa<EnumConstantDecl>(PrevDecl))
18638         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18639       else
18640         Diag(IdLoc, diag::err_redefinition) << Id;
18641       notePreviousDefinition(PrevDecl, IdLoc);
18642       return nullptr;
18643     }
18644   }
18645 
18646   // Process attributes.
18647   ProcessDeclAttributeList(S, New, Attrs);
18648   AddPragmaAttributes(S, New);
18649 
18650   // Register this decl in the current scope stack.
18651   New->setAccess(TheEnumDecl->getAccess());
18652   PushOnScopeChains(New, S);
18653 
18654   ActOnDocumentableDecl(New);
18655 
18656   return New;
18657 }
18658 
18659 // Returns true when the enum initial expression does not trigger the
18660 // duplicate enum warning.  A few common cases are exempted as follows:
18661 // Element2 = Element1
18662 // Element2 = Element1 + 1
18663 // Element2 = Element1 - 1
18664 // Where Element2 and Element1 are from the same enum.
18665 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18666   Expr *InitExpr = ECD->getInitExpr();
18667   if (!InitExpr)
18668     return true;
18669   InitExpr = InitExpr->IgnoreImpCasts();
18670 
18671   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18672     if (!BO->isAdditiveOp())
18673       return true;
18674     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18675     if (!IL)
18676       return true;
18677     if (IL->getValue() != 1)
18678       return true;
18679 
18680     InitExpr = BO->getLHS();
18681   }
18682 
18683   // This checks if the elements are from the same enum.
18684   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18685   if (!DRE)
18686     return true;
18687 
18688   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18689   if (!EnumConstant)
18690     return true;
18691 
18692   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18693       Enum)
18694     return true;
18695 
18696   return false;
18697 }
18698 
18699 // Emits a warning when an element is implicitly set a value that
18700 // a previous element has already been set to.
18701 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18702                                         EnumDecl *Enum, QualType EnumType) {
18703   // Avoid anonymous enums
18704   if (!Enum->getIdentifier())
18705     return;
18706 
18707   // Only check for small enums.
18708   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18709     return;
18710 
18711   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18712     return;
18713 
18714   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18715   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18716 
18717   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18718 
18719   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18720   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18721 
18722   // Use int64_t as a key to avoid needing special handling for map keys.
18723   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18724     llvm::APSInt Val = D->getInitVal();
18725     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18726   };
18727 
18728   DuplicatesVector DupVector;
18729   ValueToVectorMap EnumMap;
18730 
18731   // Populate the EnumMap with all values represented by enum constants without
18732   // an initializer.
18733   for (auto *Element : Elements) {
18734     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18735 
18736     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18737     // this constant.  Skip this enum since it may be ill-formed.
18738     if (!ECD) {
18739       return;
18740     }
18741 
18742     // Constants with initalizers are handled in the next loop.
18743     if (ECD->getInitExpr())
18744       continue;
18745 
18746     // Duplicate values are handled in the next loop.
18747     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18748   }
18749 
18750   if (EnumMap.size() == 0)
18751     return;
18752 
18753   // Create vectors for any values that has duplicates.
18754   for (auto *Element : Elements) {
18755     // The last loop returned if any constant was null.
18756     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18757     if (!ValidDuplicateEnum(ECD, Enum))
18758       continue;
18759 
18760     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18761     if (Iter == EnumMap.end())
18762       continue;
18763 
18764     DeclOrVector& Entry = Iter->second;
18765     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18766       // Ensure constants are different.
18767       if (D == ECD)
18768         continue;
18769 
18770       // Create new vector and push values onto it.
18771       auto Vec = std::make_unique<ECDVector>();
18772       Vec->push_back(D);
18773       Vec->push_back(ECD);
18774 
18775       // Update entry to point to the duplicates vector.
18776       Entry = Vec.get();
18777 
18778       // Store the vector somewhere we can consult later for quick emission of
18779       // diagnostics.
18780       DupVector.emplace_back(std::move(Vec));
18781       continue;
18782     }
18783 
18784     ECDVector *Vec = Entry.get<ECDVector*>();
18785     // Make sure constants are not added more than once.
18786     if (*Vec->begin() == ECD)
18787       continue;
18788 
18789     Vec->push_back(ECD);
18790   }
18791 
18792   // Emit diagnostics.
18793   for (const auto &Vec : DupVector) {
18794     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18795 
18796     // Emit warning for one enum constant.
18797     auto *FirstECD = Vec->front();
18798     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18799       << FirstECD << toString(FirstECD->getInitVal(), 10)
18800       << FirstECD->getSourceRange();
18801 
18802     // Emit one note for each of the remaining enum constants with
18803     // the same value.
18804     for (auto *ECD : llvm::drop_begin(*Vec))
18805       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18806         << ECD << toString(ECD->getInitVal(), 10)
18807         << ECD->getSourceRange();
18808   }
18809 }
18810 
18811 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18812                              bool AllowMask) const {
18813   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18814   assert(ED->isCompleteDefinition() && "expected enum definition");
18815 
18816   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18817   llvm::APInt &FlagBits = R.first->second;
18818 
18819   if (R.second) {
18820     for (auto *E : ED->enumerators()) {
18821       const auto &EVal = E->getInitVal();
18822       // Only single-bit enumerators introduce new flag values.
18823       if (EVal.isPowerOf2())
18824         FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
18825     }
18826   }
18827 
18828   // A value is in a flag enum if either its bits are a subset of the enum's
18829   // flag bits (the first condition) or we are allowing masks and the same is
18830   // true of its complement (the second condition). When masks are allowed, we
18831   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18832   //
18833   // While it's true that any value could be used as a mask, the assumption is
18834   // that a mask will have all of the insignificant bits set. Anything else is
18835   // likely a logic error.
18836   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18837   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18838 }
18839 
18840 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18841                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18842                          const ParsedAttributesView &Attrs) {
18843   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18844   QualType EnumType = Context.getTypeDeclType(Enum);
18845 
18846   ProcessDeclAttributeList(S, Enum, Attrs);
18847 
18848   if (Enum->isDependentType()) {
18849     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18850       EnumConstantDecl *ECD =
18851         cast_or_null<EnumConstantDecl>(Elements[i]);
18852       if (!ECD) continue;
18853 
18854       ECD->setType(EnumType);
18855     }
18856 
18857     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18858     return;
18859   }
18860 
18861   // TODO: If the result value doesn't fit in an int, it must be a long or long
18862   // long value.  ISO C does not support this, but GCC does as an extension,
18863   // emit a warning.
18864   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18865   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18866   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18867 
18868   // Verify that all the values are okay, compute the size of the values, and
18869   // reverse the list.
18870   unsigned NumNegativeBits = 0;
18871   unsigned NumPositiveBits = 0;
18872 
18873   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18874     EnumConstantDecl *ECD =
18875       cast_or_null<EnumConstantDecl>(Elements[i]);
18876     if (!ECD) continue;  // Already issued a diagnostic.
18877 
18878     const llvm::APSInt &InitVal = ECD->getInitVal();
18879 
18880     // Keep track of the size of positive and negative values.
18881     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18882       NumPositiveBits = std::max(NumPositiveBits,
18883                                  (unsigned)InitVal.getActiveBits());
18884     else
18885       NumNegativeBits = std::max(NumNegativeBits,
18886                                  (unsigned)InitVal.getMinSignedBits());
18887   }
18888 
18889   // Figure out the type that should be used for this enum.
18890   QualType BestType;
18891   unsigned BestWidth;
18892 
18893   // C++0x N3000 [conv.prom]p3:
18894   //   An rvalue of an unscoped enumeration type whose underlying
18895   //   type is not fixed can be converted to an rvalue of the first
18896   //   of the following types that can represent all the values of
18897   //   the enumeration: int, unsigned int, long int, unsigned long
18898   //   int, long long int, or unsigned long long int.
18899   // C99 6.4.4.3p2:
18900   //   An identifier declared as an enumeration constant has type int.
18901   // The C99 rule is modified by a gcc extension
18902   QualType BestPromotionType;
18903 
18904   bool Packed = Enum->hasAttr<PackedAttr>();
18905   // -fshort-enums is the equivalent to specifying the packed attribute on all
18906   // enum definitions.
18907   if (LangOpts.ShortEnums)
18908     Packed = true;
18909 
18910   // If the enum already has a type because it is fixed or dictated by the
18911   // target, promote that type instead of analyzing the enumerators.
18912   if (Enum->isComplete()) {
18913     BestType = Enum->getIntegerType();
18914     if (BestType->isPromotableIntegerType())
18915       BestPromotionType = Context.getPromotedIntegerType(BestType);
18916     else
18917       BestPromotionType = BestType;
18918 
18919     BestWidth = Context.getIntWidth(BestType);
18920   }
18921   else if (NumNegativeBits) {
18922     // If there is a negative value, figure out the smallest integer type (of
18923     // int/long/longlong) that fits.
18924     // If it's packed, check also if it fits a char or a short.
18925     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18926       BestType = Context.SignedCharTy;
18927       BestWidth = CharWidth;
18928     } else if (Packed && NumNegativeBits <= ShortWidth &&
18929                NumPositiveBits < ShortWidth) {
18930       BestType = Context.ShortTy;
18931       BestWidth = ShortWidth;
18932     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18933       BestType = Context.IntTy;
18934       BestWidth = IntWidth;
18935     } else {
18936       BestWidth = Context.getTargetInfo().getLongWidth();
18937 
18938       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18939         BestType = Context.LongTy;
18940       } else {
18941         BestWidth = Context.getTargetInfo().getLongLongWidth();
18942 
18943         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18944           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18945         BestType = Context.LongLongTy;
18946       }
18947     }
18948     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18949   } else {
18950     // If there is no negative value, figure out the smallest type that fits
18951     // all of the enumerator values.
18952     // If it's packed, check also if it fits a char or a short.
18953     if (Packed && NumPositiveBits <= CharWidth) {
18954       BestType = Context.UnsignedCharTy;
18955       BestPromotionType = Context.IntTy;
18956       BestWidth = CharWidth;
18957     } else if (Packed && NumPositiveBits <= ShortWidth) {
18958       BestType = Context.UnsignedShortTy;
18959       BestPromotionType = Context.IntTy;
18960       BestWidth = ShortWidth;
18961     } else if (NumPositiveBits <= IntWidth) {
18962       BestType = Context.UnsignedIntTy;
18963       BestWidth = IntWidth;
18964       BestPromotionType
18965         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18966                            ? Context.UnsignedIntTy : Context.IntTy;
18967     } else if (NumPositiveBits <=
18968                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18969       BestType = Context.UnsignedLongTy;
18970       BestPromotionType
18971         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18972                            ? Context.UnsignedLongTy : Context.LongTy;
18973     } else {
18974       BestWidth = Context.getTargetInfo().getLongLongWidth();
18975       assert(NumPositiveBits <= BestWidth &&
18976              "How could an initializer get larger than ULL?");
18977       BestType = Context.UnsignedLongLongTy;
18978       BestPromotionType
18979         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18980                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18981     }
18982   }
18983 
18984   // Loop over all of the enumerator constants, changing their types to match
18985   // the type of the enum if needed.
18986   for (auto *D : Elements) {
18987     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18988     if (!ECD) continue;  // Already issued a diagnostic.
18989 
18990     // Standard C says the enumerators have int type, but we allow, as an
18991     // extension, the enumerators to be larger than int size.  If each
18992     // enumerator value fits in an int, type it as an int, otherwise type it the
18993     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18994     // that X has type 'int', not 'unsigned'.
18995 
18996     // Determine whether the value fits into an int.
18997     llvm::APSInt InitVal = ECD->getInitVal();
18998 
18999     // If it fits into an integer type, force it.  Otherwise force it to match
19000     // the enum decl type.
19001     QualType NewTy;
19002     unsigned NewWidth;
19003     bool NewSign;
19004     if (!getLangOpts().CPlusPlus &&
19005         !Enum->isFixed() &&
19006         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
19007       NewTy = Context.IntTy;
19008       NewWidth = IntWidth;
19009       NewSign = true;
19010     } else if (ECD->getType() == BestType) {
19011       // Already the right type!
19012       if (getLangOpts().CPlusPlus)
19013         // C++ [dcl.enum]p4: Following the closing brace of an
19014         // enum-specifier, each enumerator has the type of its
19015         // enumeration.
19016         ECD->setType(EnumType);
19017       continue;
19018     } else {
19019       NewTy = BestType;
19020       NewWidth = BestWidth;
19021       NewSign = BestType->isSignedIntegerOrEnumerationType();
19022     }
19023 
19024     // Adjust the APSInt value.
19025     InitVal = InitVal.extOrTrunc(NewWidth);
19026     InitVal.setIsSigned(NewSign);
19027     ECD->setInitVal(InitVal);
19028 
19029     // Adjust the Expr initializer and type.
19030     if (ECD->getInitExpr() &&
19031         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19032       ECD->setInitExpr(ImplicitCastExpr::Create(
19033           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19034           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19035     if (getLangOpts().CPlusPlus)
19036       // C++ [dcl.enum]p4: Following the closing brace of an
19037       // enum-specifier, each enumerator has the type of its
19038       // enumeration.
19039       ECD->setType(EnumType);
19040     else
19041       ECD->setType(NewTy);
19042   }
19043 
19044   Enum->completeDefinition(BestType, BestPromotionType,
19045                            NumPositiveBits, NumNegativeBits);
19046 
19047   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19048 
19049   if (Enum->isClosedFlag()) {
19050     for (Decl *D : Elements) {
19051       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19052       if (!ECD) continue;  // Already issued a diagnostic.
19053 
19054       llvm::APSInt InitVal = ECD->getInitVal();
19055       if (InitVal != 0 && !InitVal.isPowerOf2() &&
19056           !IsValueInFlagEnum(Enum, InitVal, true))
19057         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19058           << ECD << Enum;
19059     }
19060   }
19061 
19062   // Now that the enum type is defined, ensure it's not been underaligned.
19063   if (Enum->hasAttrs())
19064     CheckAlignasUnderalignment(Enum);
19065 }
19066 
19067 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
19068                                   SourceLocation StartLoc,
19069                                   SourceLocation EndLoc) {
19070   StringLiteral *AsmString = cast<StringLiteral>(expr);
19071 
19072   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
19073                                                    AsmString, StartLoc,
19074                                                    EndLoc);
19075   CurContext->addDecl(New);
19076   return New;
19077 }
19078 
19079 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
19080                                       IdentifierInfo* AliasName,
19081                                       SourceLocation PragmaLoc,
19082                                       SourceLocation NameLoc,
19083                                       SourceLocation AliasNameLoc) {
19084   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19085                                          LookupOrdinaryName);
19086   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19087                            AttributeCommonInfo::AS_Pragma);
19088   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19089       Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19090 
19091   // If a declaration that:
19092   // 1) declares a function or a variable
19093   // 2) has external linkage
19094   // already exists, add a label attribute to it.
19095   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19096     if (isDeclExternC(PrevDecl))
19097       PrevDecl->addAttr(Attr);
19098     else
19099       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19100           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19101   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
19102   } else
19103     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19104 }
19105 
19106 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
19107                              SourceLocation PragmaLoc,
19108                              SourceLocation NameLoc) {
19109   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19110 
19111   if (PrevDecl) {
19112     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
19113   } else {
19114     (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19115   }
19116 }
19117 
19118 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
19119                                 IdentifierInfo* AliasName,
19120                                 SourceLocation PragmaLoc,
19121                                 SourceLocation NameLoc,
19122                                 SourceLocation AliasNameLoc) {
19123   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
19124                                     LookupOrdinaryName);
19125   WeakInfo W = WeakInfo(Name, NameLoc);
19126 
19127   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19128     if (!PrevDecl->hasAttr<AliasAttr>())
19129       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
19130         DeclApplyPragmaWeak(TUScope, ND, W);
19131   } else {
19132     (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
19133   }
19134 }
19135 
19136 ObjCContainerDecl *Sema::getObjCDeclContext() const {
19137   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
19138 }
19139 
19140 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
19141                                                      bool Final) {
19142   assert(FD && "Expected non-null FunctionDecl");
19143 
19144   // SYCL functions can be template, so we check if they have appropriate
19145   // attribute prior to checking if it is a template.
19146   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
19147     return FunctionEmissionStatus::Emitted;
19148 
19149   // Templates are emitted when they're instantiated.
19150   if (FD->isDependentContext())
19151     return FunctionEmissionStatus::TemplateDiscarded;
19152 
19153   // Check whether this function is an externally visible definition.
19154   auto IsEmittedForExternalSymbol = [this, FD]() {
19155     // We have to check the GVA linkage of the function's *definition* -- if we
19156     // only have a declaration, we don't know whether or not the function will
19157     // be emitted, because (say) the definition could include "inline".
19158     FunctionDecl *Def = FD->getDefinition();
19159 
19160     return Def && !isDiscardableGVALinkage(
19161                       getASTContext().GetGVALinkageForFunction(Def));
19162   };
19163 
19164   if (LangOpts.OpenMPIsDevice) {
19165     // In OpenMP device mode we will not emit host only functions, or functions
19166     // we don't need due to their linkage.
19167     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19168         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19169     // DevTy may be changed later by
19170     //  #pragma omp declare target to(*) device_type(*).
19171     // Therefore DevTy having no value does not imply host. The emission status
19172     // will be checked again at the end of compilation unit with Final = true.
19173     if (DevTy)
19174       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
19175         return FunctionEmissionStatus::OMPDiscarded;
19176     // If we have an explicit value for the device type, or we are in a target
19177     // declare context, we need to emit all extern and used symbols.
19178     if (isInOpenMPDeclareTargetContext() || DevTy)
19179       if (IsEmittedForExternalSymbol())
19180         return FunctionEmissionStatus::Emitted;
19181     // Device mode only emits what it must, if it wasn't tagged yet and needed,
19182     // we'll omit it.
19183     if (Final)
19184       return FunctionEmissionStatus::OMPDiscarded;
19185   } else if (LangOpts.OpenMP > 45) {
19186     // In OpenMP host compilation prior to 5.0 everything was an emitted host
19187     // function. In 5.0, no_host was introduced which might cause a function to
19188     // be ommitted.
19189     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
19190         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
19191     if (DevTy)
19192       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
19193         return FunctionEmissionStatus::OMPDiscarded;
19194   }
19195 
19196   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
19197     return FunctionEmissionStatus::Emitted;
19198 
19199   if (LangOpts.CUDA) {
19200     // When compiling for device, host functions are never emitted.  Similarly,
19201     // when compiling for host, device and global functions are never emitted.
19202     // (Technically, we do emit a host-side stub for global functions, but this
19203     // doesn't count for our purposes here.)
19204     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
19205     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
19206       return FunctionEmissionStatus::CUDADiscarded;
19207     if (!LangOpts.CUDAIsDevice &&
19208         (T == Sema::CFT_Device || T == Sema::CFT_Global))
19209       return FunctionEmissionStatus::CUDADiscarded;
19210 
19211     if (IsEmittedForExternalSymbol())
19212       return FunctionEmissionStatus::Emitted;
19213   }
19214 
19215   // Otherwise, the function is known-emitted if it's in our set of
19216   // known-emitted functions.
19217   return FunctionEmissionStatus::Unknown;
19218 }
19219 
19220 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
19221   // Host-side references to a __global__ function refer to the stub, so the
19222   // function itself is never emitted and therefore should not be marked.
19223   // If we have host fn calls kernel fn calls host+device, the HD function
19224   // does not get instantiated on the host. We model this by omitting at the
19225   // call to the kernel from the callgraph. This ensures that, when compiling
19226   // for host, only HD functions actually called from the host get marked as
19227   // known-emitted.
19228   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
19229          IdentifyCUDATarget(Callee) == CFT_Global;
19230 }
19231